id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_2919_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W W PPPP GGGG % % W W P P G % % W W W PPPP G GGG % % WW WW P G G % % W W P GGG % % % % % % Read WordPerfect Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/constitute.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility.h" #include "magick/utility-private.h" typedef struct { unsigned char Red; unsigned char Blue; unsigned char Green; } RGB_Record; /* Default palette for WPG level 1 */ static const RGB_Record WPG1_Palette[256]={ { 0, 0, 0}, { 0, 0,168}, { 0,168, 0}, { 0,168,168}, {168, 0, 0}, {168, 0,168}, {168, 84, 0}, {168,168,168}, { 84, 84, 84}, { 84, 84,252}, { 84,252, 84}, { 84,252,252}, {252, 84, 84}, {252, 84,252}, {252,252, 84}, {252,252,252}, /*16*/ { 0, 0, 0}, { 20, 20, 20}, { 32, 32, 32}, { 44, 44, 44}, { 56, 56, 56}, { 68, 68, 68}, { 80, 80, 80}, { 96, 96, 96}, {112,112,112}, {128,128,128}, {144,144,144}, {160,160,160}, {180,180,180}, {200,200,200}, {224,224,224}, {252,252,252}, /*32*/ { 0, 0,252}, { 64, 0,252}, {124, 0,252}, {188, 0,252}, {252, 0,252}, {252, 0,188}, {252, 0,124}, {252, 0, 64}, {252, 0, 0}, {252, 64, 0}, {252,124, 0}, {252,188, 0}, {252,252, 0}, {188,252, 0}, {124,252, 0}, { 64,252, 0}, /*48*/ { 0,252, 0}, { 0,252, 64}, { 0,252,124}, { 0,252,188}, { 0,252,252}, { 0,188,252}, { 0,124,252}, { 0, 64,252}, {124,124,252}, {156,124,252}, {188,124,252}, {220,124,252}, {252,124,252}, {252,124,220}, {252,124,188}, {252,124,156}, /*64*/ {252,124,124}, {252,156,124}, {252,188,124}, {252,220,124}, {252,252,124}, {220,252,124}, {188,252,124}, {156,252,124}, {124,252,124}, {124,252,156}, {124,252,188}, {124,252,220}, {124,252,252}, {124,220,252}, {124,188,252}, {124,156,252}, /*80*/ {180,180,252}, {196,180,252}, {216,180,252}, {232,180,252}, {252,180,252}, {252,180,232}, {252,180,216}, {252,180,196}, {252,180,180}, {252,196,180}, {252,216,180}, {252,232,180}, {252,252,180}, {232,252,180}, {216,252,180}, {196,252,180}, /*96*/ {180,220,180}, {180,252,196}, {180,252,216}, {180,252,232}, {180,252,252}, {180,232,252}, {180,216,252}, {180,196,252}, {0,0,112}, {28,0,112}, {56,0,112}, {84,0,112}, {112,0,112}, {112,0,84}, {112,0,56}, {112,0,28}, /*112*/ {112,0,0}, {112,28,0}, {112,56,0}, {112,84,0}, {112,112,0}, {84,112,0}, {56,112,0}, {28,112,0}, {0,112,0}, {0,112,28}, {0,112,56}, {0,112,84}, {0,112,112}, {0,84,112}, {0,56,112}, {0,28,112}, /*128*/ {56,56,112}, {68,56,112}, {84,56,112}, {96,56,112}, {112,56,112}, {112,56,96}, {112,56,84}, {112,56,68}, {112,56,56}, {112,68,56}, {112,84,56}, {112,96,56}, {112,112,56}, {96,112,56}, {84,112,56}, {68,112,56}, /*144*/ {56,112,56}, {56,112,69}, {56,112,84}, {56,112,96}, {56,112,112}, {56,96,112}, {56,84,112}, {56,68,112}, {80,80,112}, {88,80,112}, {96,80,112}, {104,80,112}, {112,80,112}, {112,80,104}, {112,80,96}, {112,80,88}, /*160*/ {112,80,80}, {112,88,80}, {112,96,80}, {112,104,80}, {112,112,80}, {104,112,80}, {96,112,80}, {88,112,80}, {80,112,80}, {80,112,88}, {80,112,96}, {80,112,104}, {80,112,112}, {80,114,112}, {80,96,112}, {80,88,112}, /*176*/ {0,0,64}, {16,0,64}, {32,0,64}, {48,0,64}, {64,0,64}, {64,0,48}, {64,0,32}, {64,0,16}, {64,0,0}, {64,16,0}, {64,32,0}, {64,48,0}, {64,64,0}, {48,64,0}, {32,64,0}, {16,64,0}, /*192*/ {0,64,0}, {0,64,16}, {0,64,32}, {0,64,48}, {0,64,64}, {0,48,64}, {0,32,64}, {0,16,64}, {32,32,64}, {40,32,64}, {48,32,64}, {56,32,64}, {64,32,64}, {64,32,56}, {64,32,48}, {64,32,40}, /*208*/ {64,32,32}, {64,40,32}, {64,48,32}, {64,56,32}, {64,64,32}, {56,64,32}, {48,64,32}, {40,64,32}, {32,64,32}, {32,64,40}, {32,64,48}, {32,64,56}, {32,64,64}, {32,56,64}, {32,48,64}, {32,40,64}, /*224*/ {44,44,64}, {48,44,64}, {52,44,64}, {60,44,64}, {64,44,64}, {64,44,60}, {64,44,52}, {64,44,48}, {64,44,44}, {64,48,44}, {64,52,44}, {64,60,44}, {64,64,44}, {60,64,44}, {52,64,44}, {48,64,44}, /*240*/ {44,64,44}, {44,64,48}, {44,64,52}, {44,64,60}, {44,64,64}, {44,60,64}, {44,55,64}, {44,48,64}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} /*256*/ }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s W P G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsWPG() returns True if the image format type, identified by the magick % string, is WPG. % % The format of the IsWPG method is: % % unsigned int IsWPG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o status: Method IsWPG returns True if the image format type is WPG. % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static unsigned int IsWPG(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\377WPC",4) == 0) return(MagickTrue); return(MagickFalse); } static void Rd_WP_DWORD(Image *image,size_t *d) { unsigned char b; b=ReadBlobByte(image); *d=b; if (b < 0xFFU) return; b=ReadBlobByte(image); *d=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; if (*d < 0x8000) return; *d=(*d & 0x7FFF) << 16; b=ReadBlobByte(image); *d+=(size_t) b; b=ReadBlobByte(image); *d+=(size_t) b*256l; return; } static MagickBooleanType InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); indexes=GetAuthenticIndexQueue(image); switch (bpp) { case 1: /* Convert bitmap scanline. */ { for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } break; } case 2: /* Convert PseudoColor scanline. */ { if ((image->storage_class != PseudoClass) || (indexes == (IndexPacket *) NULL)) break; for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } break; } case 4: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } break; } case 8: /* Convert PseudoColor scanline. */ { for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } } break; case 24: /* Convert DirectColor scanline. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } break; } if (!SyncAuthenticPixels(image,exception)) return(MagickFalse); return(MagickTrue); } /* Helper for WPG1 raster reader. */ #define InsertByte(b) \ { \ BImgBuff[x]=b; \ x++; \ if((ssize_t) x>=ldblk) \ { \ if (InsertRow(BImgBuff,(ssize_t) y,image,bpp) != MagickFalse) \ y++; \ x=0; \ } \ } /* WPG1 raster reader. */ static int UnpackWPGRaster(Image *image,int bpp) { int x, y, i; unsigned char bbuf, *BImgBuff, RunCount; ssize_t ldblk; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, 8*sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while(y<(ssize_t) image->rows) { int c; c=ReadBlobByte(image); if (c == EOF) break; bbuf=(unsigned char) c; RunCount=bbuf & 0x7F; if(bbuf & 0x80) { if(RunCount) /* repeat next byte runcount * */ { bbuf=ReadBlobByte(image); for(i=0;i<(int) RunCount;i++) InsertByte(bbuf); } else { /* read next byte as RunCount; repeat 0xFF runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; for(i=0;i<(int) RunCount;i++) InsertByte(0xFF); } } else { if(RunCount) /* next runcount byte are readed directly */ { for(i=0;i < (int) RunCount;i++) { bbuf=ReadBlobByte(image); InsertByte(bbuf); } } else { /* repeat previous line runcount* */ c=ReadBlobByte(image); if (c < 0) break; RunCount=(unsigned char) c; if(x) { /* attempt to duplicate row from x position: */ /* I do not know what to do here */ BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-3); } for(i=0;i < (int) RunCount;i++) { x=0; y++; /* Here I need to duplicate previous row RUNCOUNT* */ if(y<2) continue; if(y>(ssize_t) image->rows) { BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-4); } InsertRow(BImgBuff,y-1,image,bpp); } } } if (EOFBlob(image) != MagickFalse) break; } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(y < (ssize_t) image->rows ? -5 : 0); } /* Helper for WPG2 reader. */ #define InsertByte6(b) \ { \ DisableMSCWarning(4310) \ if(XorMe)\ BImgBuff[x] = (unsigned char)~b;\ else\ BImgBuff[x] = b;\ RestoreMSCWarning \ x++; \ if((ssize_t) x >= ldblk) \ { \ if (InsertRow(BImgBuff,(ssize_t) y,image,bpp) != MagickFalse) \ y++; \ x=0; \ } \ } /* WPG2 raster reader. */ static int UnpackWPG2Raster(Image *image,int bpp) { int XorMe = 0; int RunCount; size_t x, y; ssize_t i, ldblk; unsigned int SampleSize=1; unsigned char bbuf, *BImgBuff, SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; x=0; y=0; ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); if(BImgBuff==NULL) return(-2); while( y< image->rows) { bbuf=ReadBlobByte(image); switch(bbuf) { case 0x7D: SampleSize=ReadBlobByte(image); /* DSZ */ if(SampleSize>8) { BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-2); } if(SampleSize<1) { BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-2); } break; case 0x7E: (void) FormatLocaleFile(stderr, "\nUnsupported WPG token XOR, please report!"); XorMe=!XorMe; break; case 0x7F: RunCount=ReadBlobByte(image); /* BLK */ if (RunCount < 0) break; for(i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0); } break; case 0xFD: RunCount=ReadBlobByte(image); /* EXT */ if (RunCount < 0) break; for(i=0; i<= RunCount;i++) for(bbuf=0; bbuf < SampleSize; bbuf++) InsertByte6(SampleBuffer[bbuf]); break; case 0xFE: RunCount=ReadBlobByte(image); /* RST */ if (RunCount < 0) break; if(x!=0) { (void) FormatLocaleFile(stderr, "\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n" ,(double) x); BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(-3); } { /* duplicate the previous row RunCount x */ for(i=0;i<=RunCount;i++) { if (InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), image,bpp) != MagickFalse) y++; } } break; case 0xFF: RunCount=ReadBlobByte(image); /* WHT */ if (RunCount < 0) break; for (i=0; i < SampleSize*(RunCount+1); i++) { InsertByte6(0xFF); } break; default: RunCount=bbuf & 0x7F; if(bbuf & 0x80) /* REP */ { for(i=0; i < SampleSize; i++) SampleBuffer[i]=ReadBlobByte(image); for(i=0;i<=RunCount;i++) for(bbuf=0;bbuf<SampleSize;bbuf++) InsertByte6(SampleBuffer[bbuf]); } else { /* NRP */ for(i=0; i< SampleSize*(RunCount+1);i++) { bbuf=ReadBlobByte(image); InsertByte6(bbuf); } } } if (EOFBlob(image) != MagickFalse) break; } BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); return(0); } typedef float tCTM[3][3]; static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM) { const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80; ssize_t x; unsigned DenX; unsigned Flags; (void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/ (*CTM)[0][0]=1; (*CTM)[1][1]=1; (*CTM)[2][2]=1; Flags=ReadBlobLSBShort(image); if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/ if(Flags & OID) { if(Precision==0) {(void) ReadBlobLSBShort(image);} /*ObjectID*/ else {(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/ } if(Flags & ROT) { x=ReadBlobLSBLong(image); /*Rot Angle*/ if(Angle) *Angle=x/65536.0; } if(Flags & (ROT|SCL)) { x=ReadBlobLSBLong(image); /*Sx*cos()*/ (*CTM)[0][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Sy*cos()*/ (*CTM)[1][1] = (float)x/0x10000; } if(Flags & (ROT|SKW)) { x=ReadBlobLSBLong(image); /*Kx*sin()*/ (*CTM)[1][0] = (float)x/0x10000; x=ReadBlobLSBLong(image); /*Ky*sin()*/ (*CTM)[0][1] = (float)x/0x10000; } if(Flags & TRN) { x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/ if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000; else (*CTM)[0][2] = (float)x-(float)DenX/0x10000; x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/ (*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000; if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000; else (*CTM)[1][2] = (float)x-(float)DenX/0x10000; } if(Flags & TPR) { x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/ (*CTM)[2][0] = x + (float)DenX/0x10000;; x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/ (*CTM)[2][1] = x + (float)DenX/0x10000; } return(Flags); } static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,"wb"); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf("Detected:%s \n",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent-1); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickString(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickString(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method ReadWPGImage reads an WPG X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadWPGImage method is: % % Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadWPGImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength = 0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); if (WPG_Palette.StartIndex > WPG_Palette.NumOfEntries) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterWPGImage adds attributes for the WPG image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterWPGImage method is: % % size_t RegisterWPGImage(void) % */ ModuleExport size_t RegisterWPGImage(void) { MagickInfo *entry; entry=SetMagickInfo("WPG"); entry->decoder=(DecodeImageHandler *) ReadWPGImage; entry->magick=(IsImageFormatHandler *) IsWPG; entry->description=AcquireString("Word Perfect Graphics"); entry->module=ConstantString("WPG"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r W P G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterWPGImage removes format registrations made by the % WPG module from the list of supported formats. % % The format of the UnregisterWPGImage method is: % % UnregisterWPGImage(void) % */ ModuleExport void UnregisterWPGImage(void) { (void) UnregisterMagickInfo("WPG"); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2919_0
crossvul-cpp_data_good_1050_1
/* Copyright (C) 2000-2012 by George Williams */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fontforge-config.h> #include "autosave.h" #include "autotrace.h" #include "autowidth.h" #include "autowidth2.h" #include "bitmapchar.h" #include "bvedit.h" #include "chardata.h" #include "cvundoes.h" #include "dumppfa.h" #include "encoding.h" #include "ffglib.h" #include "fontforgeui.h" #include "fvcomposite.h" #include "fvfonts.h" #include "gfile.h" #include "gio.h" #include "gkeysym.h" #include "gresedit.h" #include "gresource.h" #include "groups.h" #include "mm.h" #include "namelist.h" #include "nonlineartrans.h" #include "psfont.h" #include "pua.h" #include "scripting.h" #include "search.h" #include "sfd.h" #include "sfundo.h" #include "splinefill.h" #include "splinesaveafm.h" #include "splineutil.h" #include "splineutil2.h" #include "tottfgpos.h" #include "unicodelibinfo.h" #include "ustring.h" #include "utype.h" #include <math.h> #include <unistd.h> #if defined (__MINGW32__) #include <windows.h> #endif int OpenCharsInNewWindow = 0; char *RecentFiles[RECENT_MAX] = { NULL }; int save_to_dir = 0; /* use sfdir rather than sfd */ unichar_t *script_menu_names[SCRIPT_MENU_MAX]; char *script_filenames[SCRIPT_MENU_MAX]; extern int onlycopydisplayed, copymetadata, copyttfinstr, add_char_to_name_list; int home_char='A'; int compact_font_on_open=0; bool warn_script_unsaved = true; int navigation_mask = 0; /* Initialized in startui.c */ static char *fv_fontnames = MONO_UI_FAMILIES; extern void python_call_onClosingFunctions(); #define FV_LAB_HEIGHT 15 #ifdef BIGICONS #define fontview_width 32 #define fontview_height 32 static unsigned char fontview_bits[] = { 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x02, 0x20, 0x80, 0x00, 0x82, 0x20, 0x86, 0x08, 0x42, 0x21, 0x8a, 0x14, 0xc2, 0x21, 0x86, 0x04, 0x42, 0x21, 0x8a, 0x14, 0x42, 0x21, 0x86, 0x08, 0x02, 0x20, 0x80, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0x02, 0x20, 0x80, 0x00, 0x82, 0xa0, 0x8f, 0x18, 0x82, 0x20, 0x91, 0x24, 0x42, 0x21, 0x91, 0x02, 0x42, 0x21, 0x91, 0x02, 0x22, 0x21, 0x8f, 0x02, 0xe2, 0x23, 0x91, 0x02, 0x12, 0x22, 0x91, 0x02, 0x3a, 0x27, 0x91, 0x24, 0x02, 0xa0, 0x8f, 0x18, 0x02, 0x20, 0x80, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x02, 0x20, 0x80, 0x00, 0x42, 0x20, 0x86, 0x18, 0xa2, 0x20, 0x8a, 0x04, 0xa2, 0x20, 0x86, 0x08, 0xa2, 0x20, 0x8a, 0x10, 0x42, 0x20, 0x8a, 0x0c, 0x82, 0x20, 0x80, 0x00, 0x02, 0x20, 0x80, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0x02, 0x20, 0x80, 0x00}; #else #define fontview2_width 16 #define fontview2_height 16 static unsigned char fontview2_bits[] = { 0x00, 0x07, 0x80, 0x08, 0x40, 0x17, 0x40, 0x15, 0x60, 0x09, 0x10, 0x02, 0xa0, 0x01, 0xa0, 0x00, 0xa0, 0x00, 0xa0, 0x00, 0x50, 0x00, 0x52, 0x00, 0x55, 0x00, 0x5d, 0x00, 0x22, 0x00, 0x1c, 0x00}; #endif extern int _GScrollBar_Width; static int fv_fontsize = 11, fv_fs_init=0; static Color fvselcol = 0xffff00, fvselfgcol=0x000000; Color view_bgcol; static Color fvglyphinfocol = 0xff0000; static Color fvemtpyslotfgcol = 0xd08080; static Color fvchangedcol = 0x000060; static Color fvhintingneededcol = 0x0000ff; enum glyphlable { gl_glyph, gl_name, gl_unicode, gl_encoding }; int default_fv_showhmetrics=false, default_fv_showvmetrics=false, default_fv_glyphlabel = gl_glyph; #define METRICS_BASELINE 0x0000c0 #define METRICS_ORIGIN 0xc00000 #define METRICS_ADVANCE 0x008000 FontView *fv_list=NULL; static void FV_ToggleCharChanged(SplineChar *sc) { int i, j; int pos; FontView *fv; for ( fv = (FontView *) (sc->parent->fv); fv!=NULL; fv=(FontView *) (fv->b.nextsame) ) { if ( fv->b.sf!=sc->parent ) /* Can happen in CID fonts if char's parent is not currently active */ continue; if ( fv->v==NULL || fv->colcnt==0 ) /* Can happen in scripts */ continue; for ( pos=0; pos<fv->b.map->enccount; ++pos ) if ( fv->b.map->map[pos]==sc->orig_pos ) { i = pos / fv->colcnt; j = pos - i*fv->colcnt; i -= fv->rowoff; /* Normally we should be checking against fv->rowcnt (rather than <=rowcnt) */ /* but every now and then the WM forces us to use a window size which doesn't */ /* fit our expectations (maximized view) and we must be prepared for half */ /* lines */ if ( i>=0 && i<=fv->rowcnt ) { GRect r; r.x = j*fv->cbw+1; r.width = fv->cbw-1; r.y = i*fv->cbh+1; r.height = fv->lab_height-1; GDrawRequestExpose(fv->v,&r,false); } } } } void FVMarkHintsOutOfDate(SplineChar *sc) { int i, j; int pos; FontView *fv; if ( sc->parent->onlybitmaps || sc->parent->multilayer || sc->parent->strokedfont ) return; for ( fv = (FontView *) (sc->parent->fv); fv!=NULL; fv=(FontView *) (fv->b.nextsame) ) { if ( fv->b.sf!=sc->parent ) /* Can happen in CID fonts if char's parent is not currently active */ continue; if ( sc->layers[fv->b.active_layer].order2 ) continue; if ( fv->v==NULL || fv->colcnt==0 ) /* Can happen in scripts */ continue; for ( pos=0; pos<fv->b.map->enccount; ++pos ) if ( fv->b.map->map[pos]==sc->orig_pos ) { i = pos / fv->colcnt; j = pos - i*fv->colcnt; i -= fv->rowoff; /* Normally we should be checking against fv->rowcnt (rather than <=rowcnt) */ /* but every now and then the WM forces us to use a window size which doesn't */ /* fit our expectations (maximized view) and we must be prepared for half */ /* lines */ if ( i>=0 && i<=fv->rowcnt ) { GRect r; r.x = j*fv->cbw+1; r.width = fv->cbw-1; r.y = i*fv->cbh+1; r.height = fv->lab_height-1; GDrawDrawLine(fv->v,r.x,r.y,r.x,r.y+r.height-1,fvhintingneededcol); GDrawDrawLine(fv->v,r.x+1,r.y,r.x+1,r.y+r.height-1,fvhintingneededcol); GDrawDrawLine(fv->v,r.x+r.width-1,r.y,r.x+r.width-1,r.y+r.height-1,fvhintingneededcol); GDrawDrawLine(fv->v,r.x+r.width-2,r.y,r.x+r.width-2,r.y+r.height-1,fvhintingneededcol); } } } } static int FeatureTrans(FontView *fv, int enc) { SplineChar *sc; PST *pst; char *pt; int gid; if ( enc<0 || enc>=fv->b.map->enccount || (gid = fv->b.map->map[enc])==-1 ) return( -1 ); if ( fv->cur_subtable==NULL ) return( gid ); sc = fv->b.sf->glyphs[gid]; if ( sc==NULL ) return( -1 ); for ( pst = sc->possub; pst!=NULL; pst=pst->next ) { if (( pst->type == pst_substitution || pst->type == pst_alternate ) && pst->subtable == fv->cur_subtable ) break; } if ( pst==NULL ) return( -1 ); pt = strchr(pst->u.subs.variant,' '); if ( pt!=NULL ) *pt = '\0'; gid = SFFindExistingSlot(fv->b.sf, -1, pst->u.subs.variant ); if ( pt!=NULL ) *pt = ' '; return( gid ); } static void FVDrawGlyph(GWindow pixmap, FontView *fv, int index, int forcebg ) { GRect box, old2; int feat_gid; SplineChar *sc; struct _GImage base; GImage gi; GClut clut; int i,j; int em = fv->b.sf->ascent+fv->b.sf->descent; int yorg = fv->magnify*(fv->show->ascent); i = index / fv->colcnt; j = index - i*fv->colcnt; i -= fv->rowoff; if ( index<fv->b.map->enccount && (fv->b.selected[index] || forcebg)) { box.x = j*fv->cbw+1; box.width = fv->cbw-1; box.y = i*fv->cbh+fv->lab_height+1; box.height = fv->cbw; GDrawFillRect(pixmap,&box,fv->b.selected[index] ? fvselcol : view_bgcol ); } feat_gid = FeatureTrans(fv,index); sc = feat_gid!=-1 ? fv->b.sf->glyphs[feat_gid]: NULL; if ( !SCWorthOutputting(sc) ) { int x = j*fv->cbw+1, xend = x+fv->cbw-2; int y = i*fv->cbh+fv->lab_height+1, yend = y+fv->cbw-1; GDrawDrawLine(pixmap,x,y,xend,yend,fvemtpyslotfgcol); GDrawDrawLine(pixmap,x,yend,xend,y,fvemtpyslotfgcol); } if ( sc!=NULL ) { BDFChar *bdfc; if ( fv->show!=NULL && fv->show->piecemeal && feat_gid!=-1 && (feat_gid>=fv->show->glyphcnt || fv->show->glyphs[feat_gid]==NULL) && fv->b.sf->glyphs[feat_gid]!=NULL ) BDFPieceMeal(fv->show,feat_gid); if ( fv->show!=NULL && feat_gid!=-1 && feat_gid < fv->show->glyphcnt && fv->show->glyphs[feat_gid]==NULL && SCWorthOutputting(fv->b.sf->glyphs[feat_gid]) ) { /* If we have an outline but no bitmap for this slot */ box.x = j*fv->cbw+1; box.width = fv->cbw-2; box.y = i*fv->cbh+fv->lab_height+2; box.height = box.width+1; GDrawDrawRect(pixmap,&box,0xff0000); ++box.x; ++box.y; box.width -= 2; box.height -= 2; GDrawDrawRect(pixmap,&box,0xff0000); /* When reencoding a font we can find times where index>=show->charcnt */ } else if ( fv->show!=NULL && feat_gid<fv->show->glyphcnt && feat_gid!=-1 && fv->show->glyphs[feat_gid]!=NULL ) { /* If fontview is set to display an embedded bitmap font (not a temporary font, */ /* rasterized specially for this purpose), then we can't use it directly, as bitmap */ /* glyphs may contain selections and references. So create a temporary copy of */ /* the glyph merging all such elements into a single bitmap */ bdfc = fv->show->piecemeal ? fv->show->glyphs[feat_gid] : BDFGetMergedChar( fv->show->glyphs[feat_gid] ); memset(&gi,'\0',sizeof(gi)); memset(&base,'\0',sizeof(base)); if ( bdfc->byte_data ) { gi.u.image = &base; base.image_type = it_index; if ( !fv->b.selected[index] ) base.clut = fv->show->clut; else { int bgr=((fvselcol>>16)&0xff), bgg=((fvselcol>>8)&0xff), bgb= (fvselcol&0xff); int fgr=((fvselfgcol>>16)&0xff), fgg=((fvselfgcol>>8)&0xff), fgb= (fvselfgcol&0xff); int i; memset(&clut,'\0',sizeof(clut)); base.clut = &clut; clut.clut_len = fv->show->clut->clut_len; for ( i=0; i<clut.clut_len; ++i ) { clut.clut[i] = COLOR_CREATE( bgr + (i*(fgr-bgr))/(clut.clut_len-1), bgg + (i*(fgg-bgg))/(clut.clut_len-1), bgb + (i*(fgb-bgb))/(clut.clut_len-1)); } } GDrawSetDither(NULL, false); /* on 8 bit displays we don't want any dithering */ } else { memset(&clut,'\0',sizeof(clut)); gi.u.image = &base; base.image_type = it_mono; base.clut = &clut; clut.clut_len = 2; clut.clut[0] = fv->b.selected[index] ? fvselcol : view_bgcol ; clut.clut[1] = fv->b.selected[index] ? fvselfgcol : 0 ; } base.trans = 0; base.clut->trans_index = 0; base.data = bdfc->bitmap; base.bytes_per_line = bdfc->bytes_per_line; base.width = bdfc->xmax-bdfc->xmin+1; base.height = bdfc->ymax-bdfc->ymin+1; box.x = j*fv->cbw; box.width = fv->cbw; box.y = i*fv->cbh+fv->lab_height+1; box.height = box.width+1; GDrawPushClip(pixmap,&box,&old2); if ( !fv->b.sf->onlybitmaps && fv->show!=fv->filled && sc->layers[fv->b.active_layer].splines==NULL && sc->layers[fv->b.active_layer].refs==NULL && !sc->widthset && !(bdfc->xmax<=0 && bdfc->xmin==0 && bdfc->ymax<=0 && bdfc->ymax==0) ) { /* If we have a bitmap but no outline character... */ GRect b; b.x = box.x+1; b.y = box.y+1; b.width = box.width-2; b.height = box.height-2; GDrawDrawRect(pixmap,&b,0x008000); ++b.x; ++b.y; b.width -= 2; b.height -= 2; GDrawDrawRect(pixmap,&b,0x008000); } /* I assume that the bitmap image matches the bounding*/ /* box. In some bitmap fonts the bitmap has white space on the*/ /* right. This can throw off the centering algorithem */ if ( fv->magnify>1 ) { GDrawDrawImageMagnified(pixmap,&gi,NULL, j*fv->cbw+(fv->cbw-1-fv->magnify*base.width)/2, i*fv->cbh+fv->lab_height+1+fv->magnify*(fv->show->ascent-bdfc->ymax), fv->magnify*base.width,fv->magnify*base.height); } else if ( (GDrawHasCairo(pixmap)&gc_alpha) && base.image_type==it_index ) { GDrawDrawGlyph(pixmap,&gi,NULL, j*fv->cbw+(fv->cbw-1-base.width)/2, i*fv->cbh+fv->lab_height+1+fv->show->ascent-bdfc->ymax); } else GDrawDrawImage(pixmap,&gi,NULL, j*fv->cbw+(fv->cbw-1-base.width)/2, i*fv->cbh+fv->lab_height+1+fv->show->ascent-bdfc->ymax); if ( fv->showhmetrics ) { int x1, x0 = j*fv->cbw+(fv->cbw-1-fv->magnify*base.width)/2- bdfc->xmin*fv->magnify; /* Draw advance width & horizontal origin */ if ( fv->showhmetrics&fvm_origin ) GDrawDrawLine(pixmap,x0,i*fv->cbh+fv->lab_height+yorg-3,x0, i*fv->cbh+fv->lab_height+yorg+2,METRICS_ORIGIN); x1 = x0 + fv->magnify*bdfc->width; if ( fv->showhmetrics&fvm_advanceat ) GDrawDrawLine(pixmap,x1,i*fv->cbh+fv->lab_height+1,x1, (i+1)*fv->cbh-1,METRICS_ADVANCE); if ( fv->showhmetrics&fvm_advanceto ) GDrawDrawLine(pixmap,x0,(i+1)*fv->cbh-2,x1, (i+1)*fv->cbh-2,METRICS_ADVANCE); } if ( fv->showvmetrics ) { int x0 = j*fv->cbw+(fv->cbw-1-fv->magnify*base.width)/2- bdfc->xmin*fv->magnify + fv->magnify*fv->show->pixelsize/2; int y0 = i*fv->cbh+fv->lab_height+yorg; int yvw = y0 + fv->magnify*sc->vwidth*fv->show->pixelsize/em; if ( fv->showvmetrics&fvm_baseline ) GDrawDrawLine(pixmap,x0,i*fv->cbh+fv->lab_height+1,x0, (i+1)*fv->cbh-1,METRICS_BASELINE); if ( fv->showvmetrics&fvm_advanceat ) GDrawDrawLine(pixmap,j*fv->cbw,yvw,(j+1)*fv->cbw, yvw,METRICS_ADVANCE); if ( fv->showvmetrics&fvm_advanceto ) GDrawDrawLine(pixmap,j*fv->cbw+2,y0,j*fv->cbw+2, yvw,METRICS_ADVANCE); if ( fv->showvmetrics&fvm_origin ) GDrawDrawLine(pixmap,x0-3,i*fv->cbh+fv->lab_height+yorg,x0+2,i*fv->cbh+fv->lab_height+yorg,METRICS_ORIGIN); } GDrawPopClip(pixmap,&old2); if ( !fv->show->piecemeal ) BDFCharFree( bdfc ); } } } static void FVToggleCharSelected(FontView *fv,int enc) { int i, j; if ( fv->v==NULL || fv->colcnt==0 ) /* Can happen in scripts */ return; i = enc / fv->colcnt; j = enc - i*fv->colcnt; i -= fv->rowoff; /* Normally we should be checking against fv->rowcnt (rather than <=rowcnt) */ /* but every now and then the WM forces us to use a window size which doesn't */ /* fit our expectations (maximized view) and we must be prepared for half */ /* lines */ if ( i>=0 && i<=fv->rowcnt ) FVDrawGlyph(fv->v,fv,enc,true); } static void FontViewRefreshAll(SplineFont *sf) { FontView *fv; for ( fv = (FontView *) (sf->fv); fv!=NULL; fv = (FontView *) (fv->b.nextsame) ) if ( fv->v!=NULL ) GDrawRequestExpose(fv->v,NULL,false); } void FVDeselectAll(FontView *fv) { int i; for ( i=0; i<fv->b.map->enccount; ++i ) { if ( fv->b.selected[i] ) { fv->b.selected[i] = false; FVToggleCharSelected(fv,i); } } fv->sel_index = 0; } static void FVInvertSelection(FontView *fv) { int i; for ( i=0; i<fv->b.map->enccount; ++i ) { fv->b.selected[i] = !fv->b.selected[i]; FVToggleCharSelected(fv,i); } fv->sel_index = 1; } static void FVSelectAll(FontView *fv) { int i; for ( i=0; i<fv->b.map->enccount; ++i ) { if ( !fv->b.selected[i] ) { fv->b.selected[i] = true; FVToggleCharSelected(fv,i); } } fv->sel_index = 1; } static void FVReselect(FontView *fv, int newpos) { int i; if ( newpos<0 ) newpos = 0; else if ( newpos>=fv->b.map->enccount ) newpos = fv->b.map->enccount-1; if ( fv->pressed_pos<fv->end_pos ) { if ( newpos>fv->end_pos ) { for ( i=fv->end_pos+1; i<=newpos; ++i ) if ( !fv->b.selected[i] ) { fv->b.selected[i] = fv->sel_index; FVToggleCharSelected(fv,i); } } else if ( newpos<fv->pressed_pos ) { for ( i=fv->end_pos; i>fv->pressed_pos; --i ) if ( fv->b.selected[i] ) { fv->b.selected[i] = false; FVToggleCharSelected(fv,i); } for ( i=fv->pressed_pos-1; i>=newpos; --i ) if ( !fv->b.selected[i] ) { fv->b.selected[i] = fv->sel_index; FVToggleCharSelected(fv,i); } } else { for ( i=fv->end_pos; i>newpos; --i ) if ( fv->b.selected[i] ) { fv->b.selected[i] = false; FVToggleCharSelected(fv,i); } } } else { if ( newpos<fv->end_pos ) { for ( i=fv->end_pos-1; i>=newpos; --i ) if ( !fv->b.selected[i] ) { fv->b.selected[i] = fv->sel_index; FVToggleCharSelected(fv,i); } } else if ( newpos>fv->pressed_pos ) { for ( i=fv->end_pos; i<fv->pressed_pos; ++i ) if ( fv->b.selected[i] ) { fv->b.selected[i] = false; FVToggleCharSelected(fv,i); } for ( i=fv->pressed_pos+1; i<=newpos; ++i ) if ( !fv->b.selected[i] ) { fv->b.selected[i] = fv->sel_index; FVToggleCharSelected(fv,i); } } else { for ( i=fv->end_pos; i<newpos; ++i ) if ( fv->b.selected[i] ) { fv->b.selected[i] = false; FVToggleCharSelected(fv,i); } } } fv->end_pos = newpos; if ( newpos>=0 && newpos<fv->b.map->enccount && (i = fv->b.map->map[newpos])!=-1 && fv->b.sf->glyphs[i]!=NULL && fv->b.sf->glyphs[i]->unicodeenc>=0 && fv->b.sf->glyphs[i]->unicodeenc<0x10000 ) GInsCharSetChar(fv->b.sf->glyphs[i]->unicodeenc); } static void FVFlattenAllBitmapSelections(FontView *fv) { BDFFont *bdf; int i; for ( bdf = fv->b.sf->bitmaps; bdf!=NULL; bdf=bdf->next ) { for ( i=0; i<bdf->glyphcnt; ++i ) if ( bdf->glyphs[i]!=NULL && bdf->glyphs[i]->selection!=NULL ) BCFlattenFloat(bdf->glyphs[i]); } } static int AskChanged(SplineFont *sf) { int ret; char *buts[4]; char *filename, *fontname; if ( sf->cidmaster!=NULL ) sf = sf->cidmaster; filename = sf->filename; fontname = sf->fontname; if ( filename==NULL && sf->origname!=NULL && sf->onlybitmaps && sf->bitmaps!=NULL && sf->bitmaps->next==NULL ) filename = sf->origname; if ( filename==NULL ) filename = "untitled.sfd"; filename = GFileNameTail(filename); buts[0] = _("_Save"); buts[1] = _("_Don't Save"); buts[2] = _("_Cancel"); buts[3] = NULL; ret = gwwv_ask( _("Font changed"),(const char **) buts,0,2,_("Font %1$.40s in file %2$.40s has been changed.\nDo you want to save it?"),fontname,filename); return( ret ); } static int AskScriptChanged() { int ret; char *buts[4]; buts[0] = _("_Yes"); buts[1] = _("Yes, and don't _remind me again"); buts[2] = _("_No"); buts[3] = NULL; ret = gwwv_ask( _("Unsaved script"),(const char **) buts,0,2,_("You have an unsaved script in the «Execute Script» dialog. Do you intend to discard it?")); if (ret == 1) { warn_script_unsaved = false; SavePrefs(true); } return( ret ); } int _FVMenuGenerate(FontView *fv,int family) { FVFlattenAllBitmapSelections(fv); return( SFGenerateFont(fv->b.sf,fv->b.active_layer,family,fv->b.normal==NULL?fv->b.map:fv->b.normal) ); } static void FVMenuGenerate(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); _FVMenuGenerate(fv,gf_none); } static void FVMenuGenerateFamily(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); _FVMenuGenerate(fv,gf_macfamily); } static void FVMenuGenerateTTC(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); _FVMenuGenerate(fv,gf_ttc); } extern int save_to_dir; static int SaveAs_FormatChange(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_radiochanged ) { GGadget *fc = GWidgetGetControl(GGadgetGetWindow(g),1000); char *oldname = GGadgetGetTitle8(fc); int *_s2d = GGadgetGetUserData(g); int s2d = GGadgetIsChecked(g); char *pt, *newname = malloc(strlen(oldname)+8); strcpy(newname,oldname); pt = strrchr(newname,'.'); if ( pt==NULL ) pt = newname+strlen(newname); strcpy(pt,s2d ? ".sfdir" : ".sfd" ); GGadgetSetTitle8(fc,newname); save_to_dir = *_s2d = s2d; SavePrefs(true); } return( true ); } static enum fchooserret _FVSaveAsFilterFunc(GGadget *g,struct gdirentry *ent, const unichar_t *dir) { char* n = u_to_c(ent->name); int ew = endswithi( n, "sfd" ) || endswithi( n, "sfdir" ); if( ew ) return fc_show; if( ent->isdir ) return fc_show; return fc_hide; } int _FVMenuSaveAs(FontView *fv) { char *temp; char *ret; char *filename; int ok; int s2d = fv->b.cidmaster!=NULL ? fv->b.cidmaster->save_to_dir : fv->b.sf->mm!=NULL ? fv->b.sf->mm->normal->save_to_dir : fv->b.sf->save_to_dir; GGadgetCreateData gcd; GTextInfo label; if ( fv->b.cidmaster!=NULL && fv->b.cidmaster->filename!=NULL ) temp=def2utf8_copy(fv->b.cidmaster->filename); else if ( fv->b.sf->mm!=NULL && fv->b.sf->mm->normal->filename!=NULL ) temp=def2utf8_copy(fv->b.sf->mm->normal->filename); else if ( fv->b.sf->filename!=NULL ) temp=def2utf8_copy(fv->b.sf->filename); else { SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster: fv->b.sf->mm!=NULL?fv->b.sf->mm->normal:fv->b.sf; char *fn = sf->defbasefilename ? sf->defbasefilename : sf->fontname; temp = malloc((strlen(fn)+10)); strcpy(temp,fn); if ( sf->defbasefilename!=NULL ) /* Don't add a default suffix, they've already told us what name to use */; else if ( fv->b.cidmaster!=NULL ) strcat(temp,"CID"); else if ( sf->mm==NULL ) ; else if ( sf->mm->apple ) strcat(temp,"Var"); else strcat(temp,"MM"); strcat(temp,save_to_dir ? ".sfdir" : ".sfd"); s2d = save_to_dir; } memset(&gcd,0,sizeof(gcd)); memset(&label,0,sizeof(label)); gcd.gd.flags = s2d ? (gg_visible | gg_enabled | gg_cb_on) : (gg_visible | gg_enabled); label.text = (unichar_t *) _("Save as _Directory"); label.text_is_1byte = true; label.text_in_resource = true; gcd.gd.label = &label; gcd.gd.handle_controlevent = SaveAs_FormatChange; gcd.data = &s2d; gcd.creator = GCheckBoxCreate; GFileChooserInputFilenameFuncType FilenameFunc = GFileChooserDefInputFilenameFunc; #if defined(__MINGW32__) // // If they are "saving as" but there is no path, lets help // the poor user by starting someplace sane rather than in `pwd` // if( !GFileIsAbsolute(temp) ) { char* defaultSaveDir = GFileGetHomeDocumentsDir(); // printf("save-as:%s\n", temp ); char* temp2 = GFileAppendFile( defaultSaveDir, temp, 0 ); free(temp); temp = temp2; } #endif ret = GWidgetSaveAsFileWithGadget8(_("Save as..."),temp,0,NULL, _FVSaveAsFilterFunc, FilenameFunc, &gcd ); free(temp); if ( ret==NULL ) return( 0 ); filename = utf82def_copy(ret); free(ret); if(!(endswithi( filename, ".sfdir") || endswithi( filename, ".sfd"))) { // they forgot the extension, so we force the default of .sfd // and alert them to the fact that we have done this and we // are not saving to a OTF, TTF, UFO formatted file char* extension = ".sfd"; char* newpath = copyn( filename, strlen(filename) + strlen(".sfd") + 1 ); strcat( newpath, ".sfd" ); char* oldfn = GFileNameTail( filename ); char* newfn = GFileNameTail( newpath ); LogError( _("You tried to save with the filename %s but it was saved as %s. "), oldfn, newfn ); LogError( _("Please choose File/Generate Fonts to save to other formats.")); free(filename); filename = newpath; } FVFlattenAllBitmapSelections(fv); fv->b.sf->compression = 0; ok = SFDWrite(filename,fv->b.sf,fv->b.map,fv->b.normal,s2d); if ( ok ) { SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster:fv->b.sf->mm!=NULL?fv->b.sf->mm->normal:fv->b.sf; free(sf->filename); sf->filename = filename; sf->save_to_dir = s2d; free(sf->origname); sf->origname = copy(filename); sf->new = false; if ( sf->mm!=NULL ) { int i; for ( i=0; i<sf->mm->instance_count; ++i ) { free(sf->mm->instances[i]->filename); sf->mm->instances[i]->filename = filename; free(sf->mm->instances[i]->origname); sf->mm->instances[i]->origname = copy(filename); sf->mm->instances[i]->new = false; } } SplineFontSetUnChanged(sf); FVSetTitles(fv->b.sf); } else { ff_post_error(_("Save Failed"),_("Save Failed")); free(filename); } return( ok ); } static void FVMenuSaveAs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); _FVMenuSaveAs(fv); } static int IsBackupName(char *filename) { if ( filename==NULL ) return( false ); return( filename[strlen(filename)-1]=='~' ); } int _FVMenuSave(FontView *fv) { int ret = 0; SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster: fv->b.sf->mm!=NULL?fv->b.sf->mm->normal: fv->b.sf; if ( sf->filename==NULL || IsBackupName(sf->filename)) ret = _FVMenuSaveAs(fv); else { FVFlattenAllBitmapSelections(fv); if ( !SFDWriteBak(sf->filename,sf,fv->b.map,fv->b.normal) ) ff_post_error(_("Save Failed"),_("Save Failed")); else { SplineFontSetUnChanged(sf); ret = true; } } return( ret ); } static void FVMenuSave(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); _FVMenuSave(fv); } void _FVCloseWindows(FontView *fv) { int i, j; BDFFont *bdf; MetricsView *mv, *mnext; SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster:fv->b.sf->mm!=NULL?fv->b.sf->mm->normal : fv->b.sf; PrintWindowClose(); if ( fv->b.nextsame==NULL && fv->b.sf->fv==&fv->b && fv->b.sf->kcld!=NULL ) KCLD_End(fv->b.sf->kcld); if ( fv->b.nextsame==NULL && fv->b.sf->fv==&fv->b && fv->b.sf->vkcld!=NULL ) KCLD_End(fv->b.sf->vkcld); for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) { CharView *cv, *next; for ( cv = (CharView *) (sf->glyphs[i]->views); cv!=NULL; cv = next ) { next = (CharView *) (cv->b.next); GDrawDestroyWindow(cv->gw); } if ( sf->glyphs[i]->charinfo ) CharInfoDestroy(sf->glyphs[i]->charinfo); } if ( sf->mm!=NULL ) { MMSet *mm = sf->mm; for ( j=0; j<mm->instance_count; ++j ) { SplineFont *sf = mm->instances[j]; for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) { CharView *cv, *next; for ( cv = (CharView *) (sf->glyphs[i]->views); cv!=NULL; cv = next ) { next = (CharView *) (cv->b.next); GDrawDestroyWindow(cv->gw); } if ( sf->glyphs[i]->charinfo ) CharInfoDestroy(sf->glyphs[i]->charinfo); } for ( mv=sf->metrics; mv!=NULL; mv = mnext ) { mnext = mv->next; GDrawDestroyWindow(mv->gw); } } } else if ( sf->subfontcnt!=0 ) { for ( j=0; j<sf->subfontcnt; ++j ) { for ( i=0; i<sf->subfonts[j]->glyphcnt; ++i ) if ( sf->subfonts[j]->glyphs[i]!=NULL ) { CharView *cv, *next; for ( cv = (CharView *) (sf->subfonts[j]->glyphs[i]->views); cv!=NULL; cv = next ) { next = (CharView *) (cv->b.next); GDrawDestroyWindow(cv->gw); if ( sf->subfonts[j]->glyphs[i]->charinfo ) CharInfoDestroy(sf->subfonts[j]->glyphs[i]->charinfo); } } for ( mv=sf->subfonts[j]->metrics; mv!=NULL; mv = mnext ) { mnext = mv->next; GDrawDestroyWindow(mv->gw); } } } else { for ( mv=sf->metrics; mv!=NULL; mv = mnext ) { mnext = mv->next; GDrawDestroyWindow(mv->gw); } } for ( bdf = sf->bitmaps; bdf!=NULL; bdf=bdf->next ) { for ( i=0; i<bdf->glyphcnt; ++i ) if ( bdf->glyphs[i]!=NULL ) { BitmapView *bv, *next; for ( bv = bdf->glyphs[i]->views; bv!=NULL; bv = next ) { next = bv->next; GDrawDestroyWindow(bv->gw); } } } if ( fv->b.sf->fontinfo!=NULL ) FontInfoDestroy(fv->b.sf); if ( fv->b.sf->valwin!=NULL ) ValidationDestroy(fv->b.sf); SVDetachFV(fv); } static int SFAnyChanged(SplineFont *sf) { if ( sf->mm!=NULL ) { MMSet *mm = sf->mm; int i; if ( mm->changed ) return( true ); for ( i=0; i<mm->instance_count; ++i ) if ( sf->mm->instances[i]->changed ) return( true ); /* Changes to the blended font aren't real (for adobe fonts) */ if ( mm->apple && mm->normal->changed ) return( true ); return( false ); } else return( sf->changed ); } static int _FVMenuClose(FontView *fv) { int i; SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster:fv->b.sf; if ( !SFCloseAllInstrs(fv->b.sf) ) return( false ); if ( fv->b.nextsame!=NULL || fv->b.sf->fv!=&fv->b ) { /* There's another view, can close this one with no problems */ } else if ( warn_script_unsaved && fv->script_unsaved && AskScriptChanged()==2 ) { return false; } else if ( SFAnyChanged(sf) ) { i = AskChanged(fv->b.sf); if ( i==2 ) /* Cancel */ return( false ); if ( i==0 && !_FVMenuSave(fv)) /* Save */ return(false); else SFClearAutoSave(sf); /* if they didn't save it, remove change record */ } _FVCloseWindows(fv); if ( sf->filename!=NULL ) RecentFilesRemember(sf->filename); else if ( sf->origname!=NULL ) RecentFilesRemember(sf->origname); GDrawDestroyWindow(fv->gw); return( true ); } void MenuNew(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontNew(); } static void FVMenuClose(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.container ) (fv->b.container->funcs->doClose)(fv->b.container); else _FVMenuClose(fv); } static void FV_ReattachCVs(SplineFont *old,SplineFont *new) { int i, j, pos; CharView *cv, *cvnext; SplineFont *sub; for ( i=0; i<old->glyphcnt; ++i ) { if ( old->glyphs[i]!=NULL && old->glyphs[i]->views!=NULL ) { if ( new->subfontcnt==0 ) { pos = SFFindExistingSlot(new,old->glyphs[i]->unicodeenc,old->glyphs[i]->name); sub = new; } else { pos = -1; for ( j=0; j<new->subfontcnt && pos==-1 ; ++j ) { sub = new->subfonts[j]; pos = SFFindExistingSlot(sub,old->glyphs[i]->unicodeenc,old->glyphs[i]->name); } } if ( pos==-1 ) { for ( cv=(CharView *) (old->glyphs[i]->views); cv!=NULL; cv = cvnext ) { cvnext = (CharView *) (cv->b.next); GDrawDestroyWindow(cv->gw); } } else { for ( cv=(CharView *) (old->glyphs[i]->views); cv!=NULL; cv = cvnext ) { cvnext = (CharView *) (cv->b.next); CVChangeSC(cv,sub->glyphs[pos]); cv->b.layerheads[dm_grid] = &new->grid; } } GDrawProcessPendingEvents(NULL); /* Don't want to many destroy_notify events clogging up the queue */ } } } static void FVMenuRevert(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontViewBase *fv = (FontViewBase *) GDrawGetUserData(gw); FVRevert(fv); } static void FVMenuRevertBackup(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontViewBase *fv = (FontViewBase *) GDrawGetUserData(gw); FVRevertBackup(fv); } static void FVMenuRevertGlyph(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVRevertGlyph((FontViewBase *) fv); } static void FVMenuClearSpecialData(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVClearSpecialData((FontViewBase *) fv); } void MenuPrefs(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { DoPrefs(); } void MenuXRes(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { DoXRes(); } void MenuSaveAll(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv; for ( fv = fv_list; fv!=NULL; fv = (FontView *) (fv->b.next) ) { if ( SFAnyChanged(fv->b.sf) && !_FVMenuSave(fv)) return; } } static void _MenuExit(void *UNUSED(junk)) { FontView *fv, *next; #ifndef _NO_PYTHON python_call_onClosingFunctions(); #endif LastFonts_Save(); for ( fv = fv_list; fv!=NULL; fv = next ) { next = (FontView *) (fv->b.next); if ( !_FVMenuClose(fv)) return; if ( fv->b.nextsame!=NULL || fv->b.sf->fv!=&fv->b ) { GDrawSync(NULL); GDrawProcessPendingEvents(NULL); } } GDrawSync(NULL); GDrawProcessPendingEvents(NULL); exit(0); } static void FVMenuExit(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { _MenuExit(NULL); } void MenuExit(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *e) { if ( e==NULL ) /* Not from the menu directly, but a shortcut */ _MenuExit(NULL); else DelayEvent(_MenuExit,NULL); } char *GetPostScriptFontName(char *dir, int mult) { unichar_t *ret; char *u_dir; char *temp; u_dir = def2utf8_copy(dir); ret = FVOpenFont(_("Open Font"), u_dir,mult); temp = u2def_copy(ret); free(ret); return( temp ); } void MergeKernInfo(SplineFont *sf,EncMap *map) { #ifndef __Mac static char wild[] = "*.{afm,tfm,ofm,pfm,bin,hqx,dfont,feature,feat,fea}"; static char wild2[] = "*.{afm,amfm,tfm,ofm,pfm,bin,hqx,dfont,feature,feat,fea}"; #else static char wild[] = "*"; /* Mac resource files generally don't have extensions */ static char wild2[] = "*"; #endif char *ret = gwwv_open_filename(_("Merge Feature Info"),NULL, sf->mm!=NULL?wild2:wild,NULL); char *temp; if ( ret==NULL ) return; /* Cancelled */ temp = utf82def_copy(ret); if ( !LoadKerningDataFromMetricsFile(sf,temp,map)) ff_post_error(_("Load of Kerning Metrics Failed"),_("Failed to load kern data from %s"), temp); free(ret); free(temp); } static void FVMenuMergeKern(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); MergeKernInfo(fv->b.sf,fv->b.map); } void _FVMenuOpen(FontView *fv) { char *temp; char *eod, *fpt, *file, *full; FontView *test; int fvcnt, fvtest; char* OpenDir = NULL, *DefaultDir = NULL, *NewDir = NULL; #if defined(__MINGW32__) DefaultDir = copy(GFileGetHomeDocumentsDir()); //Default value if (fv && fv->b.sf && fv->b.sf->filename) { free(DefaultDir); DefaultDir = GFileDirNameEx(fv->b.sf->filename, true); } #endif for ( fvcnt=0, test=fv_list; test!=NULL; ++fvcnt, test=(FontView *) (test->b.next) ); do { if (NewDir != NULL) { if (OpenDir != DefaultDir) { free(OpenDir); } OpenDir = NewDir; NewDir = NULL; } else if (OpenDir != DefaultDir) { free(OpenDir); OpenDir = DefaultDir; } temp = GetPostScriptFontName(OpenDir,true); if ( temp==NULL ) return; //Make a copy of the folder; may be needed later if opening fails. NewDir = GFileDirName(temp); if (!GFileExists(NewDir)) { free(NewDir); NewDir = NULL; } eod = strrchr(temp,'/'); if (eod != NULL) { *eod = '\0'; file = eod+1; if (*file) { do { fpt = strstr(file,"; "); if ( fpt!=NULL ) *fpt = '\0'; full = malloc(strlen(temp)+1+strlen(file)+1); strcpy(full,temp); strcat(full,"/"); strcat(full,file); ViewPostScriptFont(full,0); file = fpt+2; free(full); } while ( fpt!=NULL ); } } free(temp); for ( fvtest=0, test=fv_list; test!=NULL; ++fvtest, test=(FontView *) (test->b.next) ); } while ( fvtest==fvcnt ); /* did the load fail for some reason? try again */ free( NewDir ); free( OpenDir ); if (OpenDir != DefaultDir) { free( DefaultDir ); } } static void FVMenuOpen(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView*) GDrawGetUserData(gw); _FVMenuOpen(fv); } static void FVMenuContextualHelp(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { help("fontview.html"); } void MenuHelp(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { help("overview.html"); } void MenuIndex(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { help("IndexFS.html"); } void MenuLicense(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { help("license.html"); } void MenuAbout(GWindow UNUSED(base), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { ShowAboutScreen(); } static void FVMenuImport(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int empty = fv->b.sf->onlybitmaps && fv->b.sf->bitmaps==NULL; BDFFont *bdf; FVImport(fv); if ( empty && fv->b.sf->bitmaps!=NULL ) { for ( bdf= fv->b.sf->bitmaps; bdf->next!=NULL; bdf = bdf->next ); FVChangeDisplayBitmap((FontViewBase *) fv,bdf); } } static int FVSelCount(FontView *fv) { int i, cnt=0; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) ++cnt; if ( cnt>10 ) { char *buts[3]; buts[0] = _("_OK"); buts[1] = _("_Cancel"); buts[2] = NULL; if ( gwwv_ask(_("Many Windows"),(const char **) buts,0,1,_("This involves opening more than 10 windows.\nIs that really what you want?"))==1 ) return( false ); } return( true ); } static void FVMenuOpenOutline(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i; SplineChar *sc; if ( !FVSelCount(fv)) return; if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) { sc = FVMakeChar(fv,i); CharViewCreate(sc,fv,i); } } static void FVMenuOpenBitmap(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i; SplineChar *sc; if ( fv->b.cidmaster==NULL ? (fv->b.sf->bitmaps==NULL) : (fv->b.cidmaster->bitmaps==NULL) ) return; if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; if ( !FVSelCount(fv)) return; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) { sc = FVMakeChar(fv,i); if ( sc!=NULL ) BitmapViewCreatePick(i,fv); } } void _MenuWarnings(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { ShowErrorWindow(); } static void FVMenuOpenMetrics(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; MetricsViewCreate(fv,NULL,fv->filled==fv->show?NULL:fv->show); } static void FVMenuPrint(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; PrintFFDlg(fv,NULL,NULL); } #if !defined(_NO_FFSCRIPT) || !defined(_NO_PYTHON) static void FVMenuExecute(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ScriptDlg(fv,NULL); } #endif static void FVMenuFontInfo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; FontMenuFontInfo(fv); } static void FVMenuMATHInfo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFMathDlg(fv->b.sf,fv->b.active_layer); } static void FVMenuFindProblems(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FindProblems(fv,NULL,NULL); } static void FVMenuValidate(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFValidationWindow(fv->b.sf,fv->b.active_layer,ff_none); } static void FVMenuSetExtremumBound(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); char buffer[40], *end, *ret; int val; sprintf( buffer, "%d", fv->b.sf->extrema_bound<=0 ? (int) rint((fv->b.sf->ascent+fv->b.sf->descent)/100.0) : fv->b.sf->extrema_bound ); ret = gwwv_ask_string(_("Extremum bound..."),buffer,_("Adobe says that \"big\" splines should not have extrema.\nBut they don't define what big means.\nIf the distance between the spline's end-points is bigger than this value, then the spline is \"big\" to fontforge.")); if ( ret==NULL ) return; val = (int) rint(strtod(ret,&end)); if ( *end!='\0' ) ff_post_error( _("Bad Number"),_("Bad Number") ); else { fv->b.sf->extrema_bound = val; if ( !fv->b.sf->changed ) { fv->b.sf->changed = true; FVSetTitles(fv->b.sf); } } free(ret); } static void FVMenuEmbolden(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); EmboldenDlg(fv,NULL); } static void FVMenuItalic(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ItalicDlg(fv,NULL); } static void FVMenuSmallCaps(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); GlyphChangeDlg(fv,NULL,gc_smallcaps); } static void FVMenuChangeXHeight(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ChangeXHeightDlg(fv,NULL); } static void FVMenuChangeGlyph(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); GlyphChangeDlg(fv,NULL,gc_generic); } static void FVMenuSubSup(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); GlyphChangeDlg(fv,NULL,gc_subsuper); } static void FVMenuOblique(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ObliqueDlg(fv,NULL); } static void FVMenuCondense(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); CondenseExtendDlg(fv,NULL); } #define MID_24 2001 #define MID_36 2002 #define MID_48 2004 #define MID_72 2014 #define MID_96 2015 #define MID_128 2018 #define MID_AntiAlias 2005 #define MID_Next 2006 #define MID_Prev 2007 #define MID_NextDef 2012 #define MID_PrevDef 2013 #define MID_ShowHMetrics 2016 #define MID_ShowVMetrics 2017 #define MID_Ligatures 2020 #define MID_KernPairs 2021 #define MID_AnchorPairs 2022 #define MID_FitToBbox 2023 #define MID_DisplaySubs 2024 #define MID_32x8 2025 #define MID_16x4 2026 #define MID_8x2 2027 #define MID_BitmapMag 2028 #define MID_Layers 2029 #define MID_FontInfo 2200 #define MID_CharInfo 2201 #define MID_Transform 2202 #define MID_Stroke 2203 #define MID_RmOverlap 2204 #define MID_Simplify 2205 #define MID_Correct 2206 #define MID_BuildAccent 2208 #define MID_AvailBitmaps 2210 #define MID_RegenBitmaps 2211 #define MID_Autotrace 2212 #define MID_Round 2213 #define MID_MergeFonts 2214 #define MID_InterpolateFonts 2215 #define MID_FindProblems 2216 #define MID_Embolden 2217 #define MID_Condense 2218 #define MID_ShowDependentRefs 2222 #define MID_AddExtrema 2224 #define MID_CleanupGlyph 2225 #define MID_TilePath 2226 #define MID_BuildComposite 2227 #define MID_NLTransform 2228 #define MID_Intersection 2229 #define MID_FindInter 2230 #define MID_Styles 2231 #define MID_SimplifyMore 2233 #define MID_ShowDependentSubs 2234 #define MID_DefaultATT 2235 #define MID_POV 2236 #define MID_BuildDuplicates 2237 #define MID_StrikeInfo 2238 #define MID_FontCompare 2239 #define MID_CanonicalStart 2242 #define MID_CanonicalContours 2243 #define MID_RemoveBitmaps 2244 #define MID_Validate 2245 #define MID_MassRename 2246 #define MID_Italic 2247 #define MID_SmallCaps 2248 #define MID_SubSup 2249 #define MID_ChangeXHeight 2250 #define MID_ChangeGlyph 2251 #define MID_SetColor 2252 #define MID_SetExtremumBound 2253 #define MID_Center 2600 #define MID_Thirds 2601 #define MID_SetWidth 2602 #define MID_SetLBearing 2603 #define MID_SetRBearing 2604 #define MID_SetVWidth 2605 #define MID_RmHKern 2606 #define MID_RmVKern 2607 #define MID_VKernByClass 2608 #define MID_VKernFromH 2609 #define MID_SetBearings 2610 #define MID_AutoHint 2501 #define MID_ClearHints 2502 #define MID_ClearWidthMD 2503 #define MID_AutoInstr 2504 #define MID_EditInstructions 2505 #define MID_Editfpgm 2506 #define MID_Editprep 2507 #define MID_ClearInstrs 2508 #define MID_HStemHist 2509 #define MID_VStemHist 2510 #define MID_BlueValuesHist 2511 #define MID_Editcvt 2512 #define MID_HintSubsPt 2513 #define MID_AutoCounter 2514 #define MID_DontAutoHint 2515 #define MID_RmInstrTables 2516 #define MID_Editmaxp 2517 #define MID_Deltas 2518 #define MID_OpenBitmap 2700 #define MID_OpenOutline 2701 #define MID_Revert 2702 #define MID_Recent 2703 #define MID_Print 2704 #define MID_ScriptMenu 2705 #define MID_RevertGlyph 2707 #define MID_RevertToBackup 2708 #define MID_GenerateTTC 2709 #define MID_OpenMetrics 2710 #define MID_ClearSpecialData 2711 #define MID_Cut 2101 #define MID_Copy 2102 #define MID_Paste 2103 #define MID_Clear 2104 #define MID_SelAll 2106 #define MID_CopyRef 2107 #define MID_UnlinkRef 2108 #define MID_Undo 2109 #define MID_Redo 2110 #define MID_CopyWidth 2111 #define MID_UndoFontLevel 2112 #define MID_AllFonts 2122 #define MID_DisplayedFont 2123 #define MID_CharName 2124 #define MID_RemoveUndoes 2114 #define MID_CopyFgToBg 2115 #define MID_ClearBackground 2116 #define MID_CopyLBearing 2125 #define MID_CopyRBearing 2126 #define MID_CopyVWidth 2127 #define MID_Join 2128 #define MID_PasteInto 2129 #define MID_SameGlyphAs 2130 #define MID_RplRef 2131 #define MID_PasteAfter 2132 #define MID_TTFInstr 2134 #define MID_CopyLookupData 2135 #define MID_CopyL2L 2136 #define MID_CorrectRefs 2137 #define MID_Convert2CID 2800 #define MID_Flatten 2801 #define MID_InsertFont 2802 #define MID_InsertBlank 2803 #define MID_CIDFontInfo 2804 #define MID_RemoveFromCID 2805 #define MID_ConvertByCMap 2806 #define MID_FlattenByCMap 2807 #define MID_ChangeSupplement 2808 #define MID_Reencode 2830 #define MID_ForceReencode 2831 #define MID_AddUnencoded 2832 #define MID_RemoveUnused 2833 #define MID_DetachGlyphs 2834 #define MID_DetachAndRemoveGlyphs 2835 #define MID_LoadEncoding 2836 #define MID_MakeFromFont 2837 #define MID_RemoveEncoding 2838 #define MID_DisplayByGroups 2839 #define MID_Compact 2840 #define MID_SaveNamelist 2841 #define MID_RenameGlyphs 2842 #define MID_NameGlyphs 2843 #define MID_HideNoGlyphSlots 2844 #define MID_CreateMM 2900 #define MID_MMInfo 2901 #define MID_MMValid 2902 #define MID_ChangeMMBlend 2903 #define MID_BlendToNew 2904 #define MID_ModifyComposition 20902 #define MID_BuildSyllables 20903 #define MID_Warnings 3000 /* returns -1 if nothing selected, if exactly one char return it, -2 if more than one */ static int FVAnyCharSelected(FontView *fv) { int i, val=-1; for ( i=0; i<fv->b.map->enccount; ++i ) { if ( fv->b.selected[i]) { if ( val==-1 ) val = i; else return( -2 ); } } return( val ); } static int FVAllSelected(FontView *fv) { int i, any = false; /* Is everything real selected? */ for ( i=0; i<fv->b.sf->glyphcnt; ++i ) if ( SCWorthOutputting(fv->b.sf->glyphs[i])) { if ( !fv->b.selected[fv->b.map->backmap[i]] ) return( false ); any = true; } return( any ); } static void FVMenuCopyFrom(GWindow UNUSED(gw), struct gmenuitem *mi, GEvent *UNUSED(e)) { /*FontView *fv = (FontView *) GDrawGetUserData(gw);*/ if ( mi->mid==MID_CharName ) copymetadata = !copymetadata; else if ( mi->mid==MID_TTFInstr ) copyttfinstr = !copyttfinstr; else onlycopydisplayed = (mi->mid==MID_DisplayedFont); SavePrefs(true); } static void FVMenuCopy(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; FVCopy((FontViewBase *) fv,ct_fullcopy); } static void FVMenuCopyLookupData(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; FVCopy((FontViewBase *) fv,ct_lookups); } static void FVMenuCopyRef(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; FVCopy((FontViewBase *) fv,ct_reference); } static void FVMenuCopyWidth(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; if ( mi->mid==MID_CopyVWidth && !fv->b.sf->hasvmetrics ) return; FVCopyWidth((FontViewBase *) fv, mi->mid==MID_CopyWidth?ut_width: mi->mid==MID_CopyVWidth?ut_vwidth: mi->mid==MID_CopyLBearing?ut_lbearing: ut_rbearing); } static void FVMenuPaste(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; PasteIntoFV((FontViewBase *) fv,false,NULL); } static void FVMenuPasteInto(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; PasteIntoFV((FontViewBase *) fv,true,NULL); } static void FVMenuPasteAfter(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int pos = FVAnyCharSelected(fv); if ( pos<0 ) return; PasteIntoFV(&fv->b,2,NULL); } static void FVMenuSameGlyphAs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVSameGlyphAs((FontViewBase *) fv); GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuCopyFgBg(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVCopyFgtoBg( (FontViewBase *) fv ); } static void FVMenuCopyL2L(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVCopyLayerToLayer( fv ); } static void FVMenuCompareL2L(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVCompareLayerToLayer( fv ); } static void FVMenuClear(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVClear( (FontViewBase *) fv ); } static void FVMenuClearBackground(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVClearBackground( (FontViewBase *) fv ); } static void FVMenuJoin(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVJoin( (FontViewBase *) fv ); } static void FVMenuUnlinkRef(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVUnlinkRef( (FontViewBase *) fv ); } static void FVMenuRemoveUndoes(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFRemoveUndoes(fv->b.sf,fv->b.selected,fv->b.map); } static void FVMenuUndo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVUndo((FontViewBase *) fv); } static void FVMenuRedo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVRedo((FontViewBase *) fv); } static void FVMenuUndoFontLevel(GWindow gw,struct gmenuitem *mi,GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); FontViewBase * fvb = (FontViewBase *) fv; SplineFont *sf = fvb->sf; if( !sf->undoes ) return; struct sfundoes *undo = sf->undoes; // printf("font level undo msg:%s\n", undo->msg ); SFUndoPerform( undo, sf ); SFUndoRemoveAndFree( sf, undo ); } static void FVMenuCut(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVCopy(&fv->b,ct_fullcopy); FVClear(&fv->b); } static void FVMenuSelectAll(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVSelectAll(fv); } static void FVMenuInvertSelection(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVInvertSelection(fv); } static void FVMenuDeselectAll(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVDeselectAll(fv); } enum merge_type { mt_set=0, mt_merge=4, mt_or=mt_merge, mt_restrict=8, mt_and=12 }; /* Index array by merge_type(*4) + selection*2 + doit */ const uint8 mergefunc[] = { /* mt_set */ 0, 1, 0, 1, /* mt_merge */ 0, 1, 1, 1, /* mt_restrict */ 0, 0, 1, 0, /* mt_and */ 0, 0, 0, 1, }; static enum merge_type SelMergeType(GEvent *e) { if ( e->type!=et_mouseup ) return( mt_set ); return( ((e->u.mouse.state&ksm_shift)?mt_merge:0) | ((e->u.mouse.state&ksm_control)?mt_restrict:0) ); } static char *SubMatch(char *pattern, char *eop, char *name,int ignorecase) { char ch, *ppt, *npt, *ept, *eon; while ( pattern<eop && ( ch = *pattern)!='\0' ) { if ( ch=='*' ) { if ( pattern[1]=='\0' ) return( name+strlen(name)); for ( npt=name; ; ++npt ) { if ( (eon = SubMatch(pattern+1,eop,npt,ignorecase))!= NULL ) return( eon ); if ( *npt=='\0' ) return( NULL ); } } else if ( ch=='?' ) { if ( *name=='\0' ) return( NULL ); ++name; } else if ( ch=='[' ) { /* [<char>...] matches the chars * [<char>-<char>...] matches any char within the range (inclusive) * the above may be concattenated and the resultant pattern matches * anything thing which matches any of them. * [^<char>...] matches any char which does not match the rest of * the pattern * []...] as a special case a ']' immediately after the '[' matches * itself and does not end the pattern */ int found = 0, not=0; ++pattern; if ( pattern[0]=='^' ) { not = 1; ++pattern; } for ( ppt = pattern; (ppt!=pattern || *ppt!=']') && *ppt!='\0' ; ++ppt ) { ch = *ppt; if ( ppt[1]=='-' && ppt[2]!=']' && ppt[2]!='\0' ) { char ch2 = ppt[2]; if ( (*name>=ch && *name<=ch2) || (ignorecase && islower(ch) && islower(ch2) && *name>=toupper(ch) && *name<=toupper(ch2)) || (ignorecase && isupper(ch) && isupper(ch2) && *name>=tolower(ch) && *name<=tolower(ch2))) { if ( !not ) { found = 1; break; } } else { if ( not ) { found = 1; break; } } ppt += 2; } else if ( ch==*name || (ignorecase && tolower(ch)==tolower(*name)) ) { if ( !not ) { found = 1; break; } } else { if ( not ) { found = 1; break; } } } if ( !found ) return( NULL ); while ( *ppt!=']' && *ppt!='\0' ) ++ppt; pattern = ppt; ++name; } else if ( ch=='{' ) { /* matches any of a comma separated list of substrings */ for ( ppt = pattern+1; *ppt!='\0' ; ppt = ept ) { for ( ept=ppt; *ept!='}' && *ept!=',' && *ept!='\0'; ++ept ); npt = SubMatch(ppt,ept,name,ignorecase); if ( npt!=NULL ) { char *ecurly = ept; while ( *ecurly!='}' && ecurly<eop && *ecurly!='\0' ) ++ecurly; if ( (eon=SubMatch(ecurly+1,eop,npt,ignorecase))!=NULL ) return( eon ); } if ( *ept=='}' ) return( NULL ); if ( *ept==',' ) ++ept; } } else if ( ch==*name ) { ++name; } else if ( ignorecase && tolower(ch)==tolower(*name)) { ++name; } else return( NULL ); ++pattern; } return( name ); } /* Handles *?{}[] wildcards */ static int WildMatch(char *pattern, char *name,int ignorecase) { char *eop = pattern + strlen(pattern); if ( pattern==NULL ) return( true ); name = SubMatch(pattern,eop,name,ignorecase); if ( name==NULL ) return( false ); if ( *name=='\0' ) return( true ); return( false ); } static int SS_ScriptChanged(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype != et_textfocuschanged ) { char *txt = GGadgetGetTitle8(g); char buf[8]; int i; extern GTextInfo scripts[]; for ( i=0; scripts[i].text!=NULL; ++i ) { if ( strcmp((char *) scripts[i].text,txt)==0 ) break; } free(txt); if ( scripts[i].text==NULL ) return( true ); buf[0] = ((intpt) scripts[i].userdata)>>24; buf[1] = ((intpt) scripts[i].userdata)>>16; buf[2] = ((intpt) scripts[i].userdata)>>8 ; buf[3] = ((intpt) scripts[i].userdata) ; buf[4] = 0; GGadgetSetTitle8(g,buf); } return( true ); } static int SS_OK(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { int *done = GDrawGetUserData(GGadgetGetWindow(g)); *done = 2; } return( true ); } static int SS_Cancel(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { int *done = GDrawGetUserData(GGadgetGetWindow(g)); *done = true; } return( true ); } static int ss_e_h(GWindow gw, GEvent *event) { int *done = GDrawGetUserData(gw); switch ( event->type ) { case et_char: return( false ); case et_close: *done = true; break; } return( true ); } static void FVSelectByScript(FontView *fv,int merge) { int j, gid; SplineChar *sc; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; extern GTextInfo scripts[]; GRect pos; GWindow gw; GWindowAttrs wattrs; GGadgetCreateData gcd[10], *hvarray[21][2], *barray[8], boxes[3]; GTextInfo label[10]; int i,k; int done = 0, doit; char tagbuf[4]; uint32 tag; const unichar_t *ret; int lc_k, uc_k, select_k; int only_uc=0, only_lc=0; LookupUIInit(); memset(&wattrs,0,sizeof(wattrs)); memset(&gcd,0,sizeof(gcd)); memset(&label,0,sizeof(label)); memset(&boxes,0,sizeof(boxes)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.restrict_input_to_me = false; wattrs.is_dlg = 1; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Select by Script"); wattrs.is_dlg = true; pos.x = pos.y = 0; pos.width = 100; pos.height = 100; gw = GDrawCreateTopWindow(NULL,&pos,ss_e_h,&done,&wattrs); k = i = 0; gcd[k].gd.flags = gg_visible|gg_enabled ; gcd[k].gd.u.list = scripts; gcd[k].gd.handle_controlevent = SS_ScriptChanged; gcd[k++].creator = GListFieldCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("All glyphs"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup|gg_cb_on; gcd[k].gd.popup_msg = (unichar_t *) _("Set the selection of the font view to all glyphs in the script."); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; hvarray[i][0] = GCD_HPad10; hvarray[i++][1] = NULL; uc_k = k; label[k].text = (unichar_t *) _("Only upper case"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Set the selection of the font view to any upper case glyphs in the script."); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; lc_k = k; label[k].text = (unichar_t *) _("Only lower case"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Set the selection of the font view to any lower case glyphs in the script."); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; hvarray[i][0] = GCD_HPad10; hvarray[i++][1] = NULL; select_k = k; label[k].text = (unichar_t *) _("Select Results"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup|gg_rad_startnew; gcd[k].gd.popup_msg = (unichar_t *) _("Set the selection of the font view to the glyphs\nwhich match"); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Merge Results"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Expand the selection of the font view to include\nall the glyphs which match"); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Restrict Selection"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Remove matching glyphs from the selection." ); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Logical And with Selection"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Remove glyphs which do not match from the selection." ); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; gcd[k-4 + merge/4].gd.flags |= gg_cb_on; hvarray[i][0] = GCD_Glue; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("_OK"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible|gg_enabled | gg_but_default; gcd[k].gd.handle_controlevent = SS_OK; gcd[k++].creator = GButtonCreate; label[k].text = (unichar_t *) _("_Cancel"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible|gg_enabled | gg_but_cancel; gcd[k].gd.handle_controlevent = SS_Cancel; gcd[k++].creator = GButtonCreate; barray[0] = barray[2] = barray[3] = barray[4] = barray[6] = GCD_Glue; barray[7] = NULL; barray[1] = &gcd[k-2]; barray[5] = &gcd[k-1]; hvarray[i][0] = &boxes[2]; hvarray[i++][1] = NULL; hvarray[i][0] = NULL; memset(boxes,0,sizeof(boxes)); boxes[0].gd.pos.x = boxes[0].gd.pos.y = 2; boxes[0].gd.flags = gg_enabled|gg_visible; boxes[0].gd.u.boxelements = hvarray[0]; boxes[0].creator = GHVGroupCreate; boxes[2].gd.flags = gg_enabled|gg_visible; boxes[2].gd.u.boxelements = barray; boxes[2].creator = GHBoxCreate; GGadgetsCreate(gw,boxes); GHVBoxSetExpandableCol(boxes[2].ret,gb_expandgluesame); GHVBoxSetExpandableRow(boxes[0].ret,gb_expandglue); GHVBoxFitWindow(boxes[0].ret); GDrawSetVisible(gw,true); ret = NULL; while ( !done ) { GDrawProcessOneEvent(NULL); if ( done==2 ) { ret = _GGadgetGetTitle(gcd[0].ret); if ( *ret=='\0' ) { ff_post_error(_("No Script"),_("Please specify a script")); done = 0; } else if ( u_strlen(ret)>4 ) { ff_post_error(_("Bad Script"),_("Scripts are 4 letter tags")); done = 0; } } } memset(tagbuf,' ',4); if ( done==2 && ret!=NULL ) { tagbuf[0] = *ret; if ( ret[1]!='\0' ) { tagbuf[1] = ret[1]; if ( ret[2]!='\0' ) { tagbuf[2] = ret[2]; if ( ret[3]!='\0' ) tagbuf[3] = ret[3]; } } } merge = GGadgetIsChecked(gcd[select_k+0].ret) ? mt_set : GGadgetIsChecked(gcd[select_k+1].ret) ? mt_merge : GGadgetIsChecked(gcd[select_k+2].ret) ? mt_restrict : mt_and; only_uc = GGadgetIsChecked(gcd[uc_k+0].ret); only_lc = GGadgetIsChecked(gcd[lc_k+0].ret); GDrawDestroyWindow(gw); if ( done==1 ) return; tag = (tagbuf[0]<<24) | (tagbuf[1]<<16) | (tagbuf[2]<<8) | tagbuf[3]; for ( j=0; j<map->enccount; ++j ) if ( (gid=map->map[j])!=-1 && (sc=sf->glyphs[gid])!=NULL ) { doit = ( SCScriptFromUnicode(sc)==tag ); if ( doit ) { if ( only_uc && (sc->unicodeenc==-1 || sc->unicodeenc>0xffff || !isupper(sc->unicodeenc)) ) doit = false; else if ( only_lc && (sc->unicodeenc==-1 || sc->unicodeenc>0xffff || !islower(sc->unicodeenc)) ) doit = false; } fv->b.selected[j] = mergefunc[ merge + (fv->b.selected[j]?2:0) + doit ]; } else if ( merge==mt_set ) fv->b.selected[j] = false; GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSelectByScript(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVSelectByScript(fv,SelMergeType(e)); } static void FVSelectColor(FontView *fv, uint32 col, int merge) { int i, doit; uint32 sccol; SplineChar **glyphs = fv->b.sf->glyphs; for ( i=0; i<fv->b.map->enccount; ++i ) { int gid = fv->b.map->map[i]; sccol = ( gid==-1 || glyphs[gid]==NULL ) ? COLOR_DEFAULT : glyphs[gid]->color; doit = sccol==col; fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSelectColor(GWindow gw, struct gmenuitem *mi, GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); Color col = (Color) (intpt) (mi->ti.userdata); if ( (intpt) mi->ti.userdata == (intpt) -10 ) { struct hslrgb retcol, font_cols[6]; retcol = GWidgetColor(_("Pick a color"),NULL,SFFontCols(fv->b.sf,font_cols)); if ( !retcol.rgb ) return; col = (((int) rint(255.*retcol.r))<<16 ) | (((int) rint(255.*retcol.g))<<8 ) | (((int) rint(255.*retcol.b)) ); } FVSelectColor(fv,col,SelMergeType(e)); } static int FVSelectByName(FontView *fv, char *ret, int merge) { int j, gid, doit; char *end; SplineChar *sc; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; struct altuni *alt; if ( !merge ) FVDeselectAll(fv); if (( *ret=='0' && ( ret[1]=='x' || ret[1]=='X' )) || ((*ret=='u' || *ret=='U') && ret[1]=='+' )) { int uni = (int) strtol(ret+2,&end,16); int vs= -2; if ( *end=='.' ) { ++end; if (( *end=='0' && ( end[1]=='x' || end[1]=='X' )) || ((*end=='u' || *end=='U') && end[1]=='+' )) end += 2; vs = (int) strtoul(end,&end,16); } if ( *end!='\0' || uni<0 || uni>=0x110000 ) { ff_post_error( _("Bad Number"),_("Bad Number") ); return( false ); } for ( j=0; j<map->enccount; ++j ) if ( (gid=map->map[j])!=-1 && (sc=sf->glyphs[gid])!=NULL ) { if ( vs==-2 ) { for ( alt=sc->altuni; alt!=NULL && (alt->unienc!=uni || alt->fid!=0); alt=alt->next ); } else { for ( alt=sc->altuni; alt!=NULL && (alt->unienc!=uni || alt->vs!=vs || alt->fid!=0); alt=alt->next ); } doit = (sc->unicodeenc == uni && vs<0) || alt!=NULL; fv->b.selected[j] = mergefunc[ merge + (fv->b.selected[j]?2:0) + doit ]; } else if ( merge==mt_set ) fv->b.selected[j] = false; } else { for ( j=0; j<map->enccount; ++j ) if ( (gid=map->map[j])!=-1 && (sc=sf->glyphs[gid])!=NULL ) { doit = WildMatch(ret,sc->name,false); fv->b.selected[j] = mergefunc[ merge + (fv->b.selected[j]?2:0) + doit ]; } else if ( merge==mt_set ) fv->b.selected[j] = false; } GDrawRequestExpose(fv->v,NULL,false); fv->sel_index = 1; return( true ); } static void FVMenuSelectByName(GWindow _gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(_gw); GRect pos; GWindow gw; GWindowAttrs wattrs; GGadgetCreateData gcd[8], *hvarray[12][2], *barray[8], boxes[3]; GTextInfo label[8]; int merge = SelMergeType(e); int done=0,k,i; memset(&wattrs,0,sizeof(wattrs)); memset(&gcd,0,sizeof(gcd)); memset(&label,0,sizeof(label)); memset(&boxes,0,sizeof(boxes)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.restrict_input_to_me = false; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Select by Name"); wattrs.is_dlg = false; pos.x = pos.y = 0; pos.width = 100; pos.height = 100; gw = GDrawCreateTopWindow(NULL,&pos,ss_e_h,&done,&wattrs); k = i = 0; label[k].text = (unichar_t *) _("Enter either a wildcard pattern (to match glyph names)\n or a unicode encoding like \"U+0065\"."); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _( "Unix style wildcarding is accepted:\n" "Most characters match themselves\n" "A \"?\" will match any single character\n" "A \"*\" will match an arbitrary number of characters (including none)\n" "An \"[abd]\" set of characters within square brackets will match any (single) character\n" "A \"{scmp,c2sc}\" set of strings within curly brackets will match any string\n" "So \"a.*\" would match \"a.\" or \"a.sc\" or \"a.swash\"\n" "While \"a.{scmp,c2sc}\" would match \"a.scmp\" or \"a.c2sc\"\n" "And \"a.[abd]\" would match \"a.a\" or \"a.b\" or \"a.d\""); gcd[k++].creator = GLabelCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup; gcd[k].gd.popup_msg = gcd[k-1].gd.popup_msg; gcd[k++].creator = GTextFieldCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Select Results"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Set the selection of the font view to the glyphs\nwhich match"); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Merge Results"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Expand the selection of the font view to include\nall the glyphs which match"); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Restrict Selection"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Remove matching glyphs from the selection." ); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("Logical And with Selection"); label[k].text_is_1byte = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_enabled|gg_visible|gg_utf8_popup; gcd[k].gd.popup_msg = (unichar_t *) _("Remove glyphs which do not match from the selection." ); gcd[k++].creator = GRadioCreate; hvarray[i][0] = &gcd[k-1]; hvarray[i++][1] = NULL; gcd[k-4 + merge/4].gd.flags |= gg_cb_on; hvarray[i][0] = GCD_Glue; hvarray[i++][1] = NULL; label[k].text = (unichar_t *) _("_OK"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible|gg_enabled | gg_but_default; gcd[k].gd.handle_controlevent = SS_OK; gcd[k++].creator = GButtonCreate; label[k].text = (unichar_t *) _("_Cancel"); label[k].text_is_1byte = true; label[k].text_in_resource = true; gcd[k].gd.label = &label[k]; gcd[k].gd.flags = gg_visible|gg_enabled | gg_but_cancel; gcd[k].gd.handle_controlevent = SS_Cancel; gcd[k++].creator = GButtonCreate; barray[0] = barray[2] = barray[3] = barray[4] = barray[6] = GCD_Glue; barray[7] = NULL; barray[1] = &gcd[k-2]; barray[5] = &gcd[k-1]; hvarray[i][0] = &boxes[2]; hvarray[i++][1] = NULL; hvarray[i][0] = NULL; memset(boxes,0,sizeof(boxes)); boxes[0].gd.pos.x = boxes[0].gd.pos.y = 2; boxes[0].gd.flags = gg_enabled|gg_visible; boxes[0].gd.u.boxelements = hvarray[0]; boxes[0].creator = GHVGroupCreate; boxes[2].gd.flags = gg_enabled|gg_visible; boxes[2].gd.u.boxelements = barray; boxes[2].creator = GHBoxCreate; GGadgetsCreate(gw,boxes); GHVBoxSetExpandableCol(boxes[2].ret,gb_expandgluesame); GHVBoxSetExpandableRow(boxes[0].ret,gb_expandglue); GHVBoxFitWindow(boxes[0].ret); GDrawSetVisible(gw,true); while ( !done ) { GDrawProcessOneEvent(NULL); if ( done==2 ) { char *str = GGadgetGetTitle8(gcd[1].ret); int merge = GGadgetIsChecked(gcd[2].ret) ? mt_set : GGadgetIsChecked(gcd[3].ret) ? mt_merge : GGadgetIsChecked(gcd[4].ret) ? mt_restrict : mt_and; int ret = FVSelectByName(fv,str,merge); free(str); if ( !ret ) done = 0; } } GDrawDestroyWindow(gw); } static void FVMenuSelectWorthOutputting(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && SCWorthOutputting(sf->glyphs[gid]) ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuGlyphsRefs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); int layer = fv->b.active_layer; for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && sf->glyphs[gid]->layers[layer].refs!=NULL && sf->glyphs[gid]->layers[layer].splines==NULL ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuGlyphsSplines(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); int layer = fv->b.active_layer; for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && sf->glyphs[gid]->layers[layer].refs==NULL && sf->glyphs[gid]->layers[layer].splines!=NULL ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuGlyphsBoth(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); int layer = fv->b.active_layer; for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && sf->glyphs[gid]->layers[layer].refs!=NULL && sf->glyphs[gid]->layers[layer].splines!=NULL ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuGlyphsWhite(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); int layer = fv->b.active_layer; for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && sf->glyphs[gid]->layers[layer].refs==NULL && sf->glyphs[gid]->layers[layer].splines==NULL ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSelectChanged(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && sf->glyphs[gid]->changed ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSelectHintingNeeded(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int order2 = sf->layers[fv->b.active_layer].order2; int merge = SelMergeType(e); for ( i=0; i< map->enccount; ++i ) { doit = ( (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && ((!order2 && sf->glyphs[gid]->changedsincelasthinted ) || ( order2 && sf->glyphs[gid]->layers[fv->b.active_layer].splines!=NULL && sf->glyphs[gid]->ttf_instrs_len<=0 ) || ( order2 && sf->glyphs[gid]->instructions_out_of_date )) ); fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSelectAutohintable(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid, doit; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; int merge = SelMergeType(e); for ( i=0; i< map->enccount; ++i ) { doit = (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL && !sf->glyphs[gid]->manualhints; fv->b.selected[i] = mergefunc[ merge + (fv->b.selected[i]?2:0) + doit ]; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSelectByPST(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVSelectByPST(fv); } static void FVMenuFindRpl(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SVCreate(fv); } static void FVMenuReplaceWithRef(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVReplaceOutlineWithReference(fv,.001); } static void FVMenuCorrectRefs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontViewBase *fv = (FontViewBase *) GDrawGetUserData(gw); FVCorrectReferences(fv); } static void FVMenuCharInfo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int pos = FVAnyCharSelected(fv); if ( pos<0 ) return; if ( fv->b.cidmaster!=NULL && (fv->b.map->map[pos]==-1 || fv->b.sf->glyphs[fv->b.map->map[pos]]==NULL )) return; SCCharInfo(SFMakeChar(fv->b.sf,fv->b.map,pos),fv->b.active_layer,fv->b.map,pos); } static void FVMenuBDFInfo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.sf->bitmaps==NULL ) return; if ( fv->show!=fv->filled ) SFBdfProperties(fv->b.sf,fv->b.map,fv->show); else SFBdfProperties(fv->b.sf,fv->b.map,NULL); } static void FVMenuBaseHoriz(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *sf = fv->b.cidmaster == NULL ? fv->b.sf : fv->b.cidmaster; sf->horiz_base = SFBaselines(sf,sf->horiz_base,false); SFBaseSort(sf); } static void FVMenuBaseVert(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *sf = fv->b.cidmaster == NULL ? fv->b.sf : fv->b.cidmaster; sf->vert_base = SFBaselines(sf,sf->vert_base,true); SFBaseSort(sf); } static void FVMenuJustify(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *sf = fv->b.cidmaster == NULL ? fv->b.sf : fv->b.cidmaster; JustifyDlg(sf); } static void FVMenuMassRename(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVMassGlyphRename(fv); } static void FVSetColor(FontView *fv, uint32 col) { int i; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) { SplineChar *sc = SFMakeChar(fv->b.sf,fv->b.map,i); sc->color = col; } GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuSetColor(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); Color col = (Color) (intpt) (mi->ti.userdata); if ( (intpt) mi->ti.userdata == (intpt) -10 ) { struct hslrgb retcol, font_cols[6]; retcol = GWidgetColor(_("Pick a color"),NULL,SFFontCols(fv->b.sf,font_cols)); if ( !retcol.rgb ) return; col = (((int) rint(255.*retcol.r))<<16 ) | (((int) rint(255.*retcol.g))<<8 ) | (((int) rint(255.*retcol.b)) ); } FVSetColor(fv,col); } static void FVMenuShowDependentRefs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int pos = FVAnyCharSelected(fv); SplineChar *sc; if ( pos<0 || fv->b.map->map[pos]==-1 ) return; sc = fv->b.sf->glyphs[fv->b.map->map[pos]]; if ( sc==NULL || sc->dependents==NULL ) return; SCRefBy(sc); } static void FVMenuShowDependentSubs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int pos = FVAnyCharSelected(fv); SplineChar *sc; if ( pos<0 || fv->b.map->map[pos]==-1 ) return; sc = fv->b.sf->glyphs[fv->b.map->map[pos]]; if ( sc==NULL ) return; SCSubBy(sc); } static int getorigin(void *UNUSED(d), BasePoint *base, int index) { /*FontView *fv = (FontView *) d;*/ base->x = base->y = 0; switch ( index ) { case 0: /* Character origin */ /* all done */ break; case 1: /* Center of selection */ /*CVFindCenter(cv,base,!CVAnySel(cv,NULL,NULL,NULL,NULL));*/ break; default: return( false ); } return( true ); } static void FVDoTransform(FontView *fv) { enum transdlg_flags flags=tdf_enableback|tdf_enablekerns; if ( FVAnyCharSelected(fv)==-1 ) return; if ( FVAllSelected(fv)) flags=tdf_enableback|tdf_enablekerns|tdf_defaultkerns; TransformDlgCreate(fv,FVTransFunc,getorigin,flags,cvt_none); } static void FVMenuTransform(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVDoTransform(fv); } static void FVMenuPOV(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); struct pov_data pov_data; if ( FVAnyCharSelected(fv)==-1 || fv->b.sf->onlybitmaps ) return; if ( PointOfViewDlg(&pov_data,fv->b.sf,false)==-1 ) return; FVPointOfView((FontViewBase *) fv,&pov_data); } static void FVMenuNLTransform(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; NonLinearDlg(fv,NULL); } static void FVMenuBitmaps(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); BitmapDlg(fv,NULL,mi->mid==MID_RemoveBitmaps?-1:(mi->mid==MID_AvailBitmaps) ); } static void FVMenuStroke(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVStroke(fv); } # ifdef FONTFORGE_CONFIG_TILEPATH static void FVMenuTilePath(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVTile(fv); } static void FVMenuPatternTile(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVPatternTile(fv); } #endif static void FVMenuOverlap(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.sf->onlybitmaps ) return; /* We know it's more likely that we'll find a problem in the overlap code */ /* than anywhere else, so let's save the current state against a crash */ DoAutoSaves(); FVOverlap(&fv->b,mi->mid==MID_RmOverlap ? over_remove : mi->mid==MID_Intersection ? over_intersect : over_findinter); } static void FVMenuInline(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); OutlineDlg(fv,NULL,NULL,true); } static void FVMenuOutline(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); OutlineDlg(fv,NULL,NULL,false); } static void FVMenuShadow(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ShadowDlg(fv,NULL,NULL,false); } static void FVMenuWireframe(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ShadowDlg(fv,NULL,NULL,true); } static void FVSimplify(FontView *fv,int type) { static struct simplifyinfo smpls[] = { { sf_normal, 0, 0, 0, 0, 0, 0 }, { sf_normal,.75,.05,0,-1, 0, 0 }, { sf_normal,.75,.05,0,-1, 0, 0 }}; struct simplifyinfo *smpl = &smpls[type+1]; if ( smpl->linelenmax==-1 || (type==0 && !smpl->set_as_default)) { smpl->err = (fv->b.sf->ascent+fv->b.sf->descent)/1000.; smpl->linelenmax = (fv->b.sf->ascent+fv->b.sf->descent)/100.; } if ( type==1 ) { if ( !SimplifyDlg(fv->b.sf,smpl)) return; if ( smpl->set_as_default ) smpls[1] = *smpl; } _FVSimplify((FontViewBase *) fv,smpl); } static void FVMenuSimplify(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVSimplify( (FontView *) GDrawGetUserData(gw),false ); } static void FVMenuSimplifyMore(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVSimplify( (FontView *) GDrawGetUserData(gw),true ); } static void FVMenuCleanup(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVSimplify( (FontView *) GDrawGetUserData(gw),-1 ); } static void FVMenuCanonicalStart(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVCanonicalStart( (FontViewBase *) GDrawGetUserData(gw) ); } static void FVMenuCanonicalContours(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVCanonicalContours( (FontViewBase *) GDrawGetUserData(gw) ); } static void FVMenuAddExtrema(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVAddExtrema( (FontViewBase *) GDrawGetUserData(gw) , false); } static void FVMenuCorrectDir(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVCorrectDir((FontViewBase *) fv); } static void FVMenuRound2Int(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVRound2Int( (FontViewBase *) GDrawGetUserData(gw), 1.0 ); } static void FVMenuRound2Hundredths(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVRound2Int( (FontViewBase *) GDrawGetUserData(gw),100.0 ); } static void FVMenuCluster(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVCluster( (FontViewBase *) GDrawGetUserData(gw)); } static void FVMenuAutotrace(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); GCursor ct=0; if ( fv->v!=NULL ) { ct = GDrawGetCursor(fv->v); GDrawSetCursor(fv->v,ct_watch); GDrawSync(NULL); GDrawProcessPendingEvents(NULL); } FVAutoTrace(&fv->b,e!=NULL && (e->u.mouse.state&ksm_shift)); if ( fv->v!=NULL ) GDrawSetCursor(fv->v,ct); } static void FVMenuBuildAccent(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVBuildAccent( (FontViewBase *) GDrawGetUserData(gw), true ); } static void FVMenuBuildComposite(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVBuildAccent( (FontViewBase *) GDrawGetUserData(gw), false ); } static void FVMenuBuildDuplicate(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FVBuildDuplicate( (FontViewBase *) GDrawGetUserData(gw)); } #ifdef KOREAN static void FVMenuShowGroup(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { ShowGroup( ((FontView *) GDrawGetUserData(gw))->sf ); } #endif #if HANYANG static void FVMenuModifyComposition(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.sf->rules!=NULL ) SFModifyComposition(fv->b.sf); } static void FVMenuBuildSyllables(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->b.sf->rules!=NULL ) SFBuildSyllables(fv->b.sf); } #endif static void FVMenuCompareFonts(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FontCompareDlg(fv); } static void FVMenuMergeFonts(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVMergeFonts(fv); } static void FVMenuInterpFonts(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVInterpolateFonts(fv); } static void FVShowInfo(FontView *fv); void FVChangeChar(FontView *fv,int i) { if ( i!=-1 ) { FVDeselectAll(fv); fv->b.selected[i] = true; fv->sel_index = 1; fv->end_pos = fv->pressed_pos = i; FVToggleCharSelected(fv,i); FVScrollToChar(fv,i); FVShowInfo(fv); } } void FVScrollToChar(FontView *fv,int i) { if ( fv->v==NULL || fv->colcnt==0 ) /* Can happen in scripts */ return; if ( i!=-1 ) { if ( i/fv->colcnt<fv->rowoff || i/fv->colcnt >= fv->rowoff+fv->rowcnt ) { fv->rowoff = i/fv->colcnt; if ( fv->rowcnt>= 3 ) --fv->rowoff; if ( fv->rowoff+fv->rowcnt>=fv->rowltot ) fv->rowoff = fv->rowltot-fv->rowcnt; if ( fv->rowoff<0 ) fv->rowoff = 0; GScrollBarSetPos(fv->vsb,fv->rowoff); GDrawRequestExpose(fv->v,NULL,false); } } } static void FVScrollToGID(FontView *fv,int gid) { FVScrollToChar(fv,fv->b.map->backmap[gid]); } static void FV_ChangeGID(FontView *fv,int gid) { FVChangeChar(fv,fv->b.map->backmap[gid]); } static void _FVMenuChangeChar(FontView *fv,int mid ) { SplineFont *sf = fv->b.sf; EncMap *map = fv->b.map; int pos = FVAnyCharSelected(fv); if ( pos>=0 ) { if ( mid==MID_Next ) ++pos; else if ( mid==MID_Prev ) --pos; else if ( mid==MID_NextDef ) { for ( ++pos; pos<map->enccount && (map->map[pos]==-1 || !SCWorthOutputting(sf->glyphs[map->map[pos]]) || (fv->show!=fv->filled && fv->show->glyphs[map->map[pos]]==NULL )); ++pos ); if ( pos>=map->enccount ) { int selpos = FVAnyCharSelected(fv); char *iconv_name = map->enc->iconv_name ? map->enc->iconv_name : map->enc->enc_name; if ( strstr(iconv_name,"2022")!=NULL && selpos<0x2121 ) pos = 0x2121; else if ( strstr(iconv_name,"EUC")!=NULL && selpos<0xa1a1 ) pos = 0xa1a1; else if ( map->enc->is_tradchinese ) { if ( strstrmatch(map->enc->enc_name,"HK")!=NULL && selpos<0x8140 ) pos = 0x8140; else pos = 0xa140; } else if ( map->enc->is_japanese ) { if ( strstrmatch(iconv_name,"SJIS")!=NULL || (strstrmatch(iconv_name,"JIS")!=NULL && strstrmatch(iconv_name,"SHIFT")!=NULL )) { if ( selpos<0x8100 ) pos = 0x8100; else if ( selpos<0xb000 ) pos = 0xb000; } } else if ( map->enc->is_korean ) { if ( strstrmatch(iconv_name,"JOHAB")!=NULL ) { if ( selpos<0x8431 ) pos = 0x8431; } else { /* Wansung, EUC-KR */ if ( selpos<0xa1a1 ) pos = 0xa1a1; } } else if ( map->enc->is_simplechinese ) { if ( strmatch(iconv_name,"EUC-CN")==0 && selpos<0xa1a1 ) pos = 0xa1a1; } if ( pos>=map->enccount ) return; } } else if ( mid==MID_PrevDef ) { for ( --pos; pos>=0 && (map->map[pos]==-1 || !SCWorthOutputting(sf->glyphs[map->map[pos]]) || (fv->show!=fv->filled && fv->show->glyphs[map->map[pos]]==NULL )); --pos ); if ( pos<0 ) return; } } if ( pos<0 ) pos = map->enccount-1; else if ( pos>= map->enccount ) pos = 0; if ( pos>=0 && pos<map->enccount ) FVChangeChar(fv,pos); } static void FVMenuChangeChar(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); _FVMenuChangeChar(fv,mi->mid); } static void FVShowSubFont(FontView *fv,SplineFont *new) { MetricsView *mv, *mvnext; BDFFont *newbdf; int wascompact = fv->b.normal!=NULL; extern int use_freetype_to_rasterize_fv; for ( mv=fv->b.sf->metrics; mv!=NULL; mv = mvnext ) { /* Don't bother trying to fix up metrics views, just not worth it */ mvnext = mv->next; GDrawDestroyWindow(mv->gw); } if ( wascompact ) { EncMapFree(fv->b.map); if (fv->b.map == fv->b.sf->map) { fv->b.sf->map = fv->b.normal; } fv->b.map = fv->b.normal; fv->b.normal = NULL; fv->b.selected = realloc(fv->b.selected,fv->b.map->enccount); memset(fv->b.selected,0,fv->b.map->enccount); } CIDSetEncMap((FontViewBase *) fv,new); if ( wascompact ) { fv->b.normal = EncMapCopy(fv->b.map); CompactEncMap(fv->b.map,fv->b.sf); FontViewReformatOne(&fv->b); FVSetTitle(&fv->b); } newbdf = SplineFontPieceMeal(fv->b.sf,fv->b.active_layer,fv->filled->pixelsize,72, (fv->antialias?pf_antialias:0)|(fv->bbsized?pf_bbsized:0)| (use_freetype_to_rasterize_fv && !fv->b.sf->strokedfont && !fv->b.sf->multilayer?pf_ft_nohints:0), NULL); BDFFontFree(fv->filled); if ( fv->filled == fv->show ) fv->show = newbdf; fv->filled = newbdf; GDrawRequestExpose(fv->v,NULL,true); } static void FVMenuGotoChar(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int merge_with_selection = false; int pos = GotoChar(fv->b.sf,fv->b.map,&merge_with_selection); if ( fv->b.cidmaster!=NULL && pos!=-1 && !fv->b.map->enc->is_compact ) { SplineFont *cidmaster = fv->b.cidmaster; int k, hadk= cidmaster->subfontcnt; for ( k=0; k<cidmaster->subfontcnt; ++k ) { SplineFont *sf = cidmaster->subfonts[k]; if ( pos<sf->glyphcnt && sf->glyphs[pos]!=NULL ) break; if ( pos<sf->glyphcnt ) hadk = k; } if ( k==cidmaster->subfontcnt && pos>=fv->b.sf->glyphcnt ) k = hadk; if ( k!=cidmaster->subfontcnt && cidmaster->subfonts[k] != fv->b.sf ) FVShowSubFont(fv,cidmaster->subfonts[k]); if ( pos>=fv->b.sf->glyphcnt ) pos = -1; } if ( !merge_with_selection ) FVChangeChar(fv,pos); else { if ( !fv->b.selected[pos] ) { fv->b.selected[pos] = ++fv->sel_index; FVToggleCharSelected(fv,pos); } fv->end_pos = fv->pressed_pos = pos; FVScrollToChar(fv,pos); FVShowInfo(fv); } } static void FVMenuLigatures(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFShowLigatures(fv->b.sf,NULL); } static void FVMenuKernPairs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFKernClassTempDecompose(fv->b.sf,false); SFShowKernPairs(fv->b.sf,NULL,NULL,fv->b.active_layer); SFKernCleanup(fv->b.sf,false); } static void FVMenuAnchorPairs(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFShowKernPairs(fv->b.sf,NULL,mi->ti.userdata,fv->b.active_layer); } static void FVMenuShowAtt(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ShowAtt(fv->b.sf,fv->b.active_layer); } static void FVMenuDisplaySubs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( fv->cur_subtable!=0 ) { fv->cur_subtable = NULL; } else { SplineFont *sf = fv->b.sf; OTLookup *otf; struct lookup_subtable *sub; int cnt, k; char **names = NULL; if ( sf->cidmaster ) sf=sf->cidmaster; for ( k=0; k<2; ++k ) { cnt = 0; for ( otf = sf->gsub_lookups; otf!=NULL; otf=otf->next ) { if ( otf->lookup_type==gsub_single ) { for ( sub=otf->subtables; sub!=NULL; sub=sub->next ) { if ( names ) names[cnt] = sub->subtable_name; ++cnt; } } } if ( cnt==0 ) break; if ( names==NULL ) names = malloc((cnt+3) * sizeof(char *)); else { names[cnt++] = "-"; names[cnt++] = _("New Lookup Subtable..."); names[cnt] = NULL; } } sub = NULL; if ( names!=NULL ) { int ret = gwwv_choose(_("Display Substitution..."), (const char **) names, cnt, 0, _("Pick a substitution to display in the window.")); if ( ret!=-1 ) sub = SFFindLookupSubtable(sf,names[ret]); free(names); if ( ret==-1 ) return; } if ( sub==NULL ) sub = SFNewLookupSubtableOfType(sf,gsub_single,NULL,fv->b.active_layer); if ( sub!=NULL ) fv->cur_subtable = sub; } GDrawRequestExpose(fv->v,NULL,false); } static void FVChangeDisplayFont(FontView *fv,BDFFont *bdf) { int samesize=0; int rcnt, ccnt; int oldr, oldc; int first_time = fv->show==NULL; if ( fv->v==NULL ) /* Can happen in scripts */ return; if ( fv->show!=bdf ) { oldc = fv->cbw*fv->colcnt; oldr = fv->cbh*fv->rowcnt; fv->show = bdf; fv->b.active_bitmap = bdf==fv->filled ? NULL : bdf; if ( fv->user_requested_magnify!=-1 ) fv->magnify=fv->user_requested_magnify; else if ( bdf->pixelsize<20 ) { if ( bdf->pixelsize<=9 ) fv->magnify = 3; else fv->magnify = 2; samesize = ( fv->show && fv->cbw == (bdf->pixelsize*fv->magnify)+1 ); } else fv->magnify = 1; if ( !first_time && fv->cbw == fv->magnify*bdf->pixelsize+1 ) samesize = true; fv->cbw = (bdf->pixelsize*fv->magnify)+1; fv->cbh = (bdf->pixelsize*fv->magnify)+1+fv->lab_height+1; fv->resize_expected = !samesize; ccnt = fv->b.sf->desired_col_cnt; rcnt = fv->b.sf->desired_row_cnt; if ((( bdf->pixelsize<=fv->b.sf->display_size || bdf->pixelsize<=-fv->b.sf->display_size ) && fv->b.sf->top_enc!=-1 /* Not defaulting */ ) || bdf->pixelsize<=48 ) { /* use the desired sizes */ } else { if ( bdf->pixelsize>48 ) { ccnt = 8; rcnt = 2; } else if ( bdf->pixelsize>=96 ) { ccnt = 4; rcnt = 1; } if ( !first_time ) { if ( ccnt < oldc/fv->cbw ) ccnt = oldc/fv->cbw; if ( rcnt < oldr/fv->cbh ) rcnt = oldr/fv->cbh; } } if ( samesize ) { GDrawRequestExpose(fv->v,NULL,false); } else if ( fv->b.container!=NULL && fv->b.container->funcs->doResize!=NULL ) { (fv->b.container->funcs->doResize)(fv->b.container,&fv->b, ccnt*fv->cbw+1+GDrawPointsToPixels(fv->gw,_GScrollBar_Width), rcnt*fv->cbh+1+fv->mbh+fv->infoh); } else { GDrawResize(fv->gw, ccnt*fv->cbw+1+GDrawPointsToPixels(fv->gw,_GScrollBar_Width), rcnt*fv->cbh+1+fv->mbh+fv->infoh); } } } struct md_data { int done; int ish; FontView *fv; }; static int md_e_h(GWindow gw, GEvent *e) { if ( e->type==et_close ) { struct md_data *d = GDrawGetUserData(gw); d->done = true; } else if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct md_data *d = GDrawGetUserData(gw); static int masks[] = { fvm_baseline, fvm_origin, fvm_advanceat, fvm_advanceto, -1 }; int i, metrics; if ( GGadgetGetCid(e->u.control.g)==10 ) { metrics = 0; for ( i=0; masks[i]!=-1 ; ++i ) if ( GGadgetIsChecked(GWidgetGetControl(gw,masks[i]))) metrics |= masks[i]; if ( d->ish ) default_fv_showhmetrics = d->fv->showhmetrics = metrics; else default_fv_showvmetrics = d->fv->showvmetrics = metrics; } d->done = true; } else if ( e->type==et_char ) { return( false ); } return( true ); } static void FVMenuShowMetrics(GWindow fvgw,struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(fvgw); GRect pos; GWindow gw; GWindowAttrs wattrs; struct md_data d; GGadgetCreateData gcd[7]; GTextInfo label[6]; int metrics = mi->mid==MID_ShowHMetrics ? fv->showhmetrics : fv->showvmetrics; d.fv = fv; d.done = 0; d.ish = mi->mid==MID_ShowHMetrics; memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.restrict_input_to_me = 1; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = d.ish?_("Show H. Metrics"):_("Show V. Metrics"); pos.x = pos.y = 0; pos.width =GDrawPointsToPixels(NULL,GGadgetScale(170)); pos.height = GDrawPointsToPixels(NULL,130); gw = GDrawCreateTopWindow(NULL,&pos,md_e_h,&d,&wattrs); memset(&label,0,sizeof(label)); memset(&gcd,0,sizeof(gcd)); label[0].text = (unichar_t *) _("Baseline"); label[0].text_is_1byte = true; gcd[0].gd.label = &label[0]; gcd[0].gd.pos.x = 8; gcd[0].gd.pos.y = 8; gcd[0].gd.flags = gg_enabled|gg_visible|(metrics&fvm_baseline?gg_cb_on:0); gcd[0].gd.cid = fvm_baseline; gcd[0].creator = GCheckBoxCreate; label[1].text = (unichar_t *) _("Origin"); label[1].text_is_1byte = true; gcd[1].gd.label = &label[1]; gcd[1].gd.pos.x = 8; gcd[1].gd.pos.y = gcd[0].gd.pos.y+16; gcd[1].gd.flags = gg_enabled|gg_visible|(metrics&fvm_origin?gg_cb_on:0); gcd[1].gd.cid = fvm_origin; gcd[1].creator = GCheckBoxCreate; label[2].text = (unichar_t *) _("Advance Width as a Line"); label[2].text_is_1byte = true; gcd[2].gd.label = &label[2]; gcd[2].gd.pos.x = 8; gcd[2].gd.pos.y = gcd[1].gd.pos.y+16; gcd[2].gd.flags = gg_enabled|gg_visible|gg_utf8_popup|(metrics&fvm_advanceat?gg_cb_on:0); gcd[2].gd.cid = fvm_advanceat; gcd[2].gd.popup_msg = (unichar_t *) _("Display the advance width as a line\nperpendicular to the advance direction"); gcd[2].creator = GCheckBoxCreate; label[3].text = (unichar_t *) _("Advance Width as a Bar"); label[3].text_is_1byte = true; gcd[3].gd.label = &label[3]; gcd[3].gd.pos.x = 8; gcd[3].gd.pos.y = gcd[2].gd.pos.y+16; gcd[3].gd.flags = gg_enabled|gg_visible|gg_utf8_popup|(metrics&fvm_advanceto?gg_cb_on:0); gcd[3].gd.cid = fvm_advanceto; gcd[3].gd.popup_msg = (unichar_t *) _("Display the advance width as a bar under the glyph\nshowing the extent of the advance"); gcd[3].creator = GCheckBoxCreate; label[4].text = (unichar_t *) _("_OK"); label[4].text_is_1byte = true; label[4].text_in_resource = true; gcd[4].gd.label = &label[4]; gcd[4].gd.pos.x = 20-3; gcd[4].gd.pos.y = GDrawPixelsToPoints(NULL,pos.height)-35-3; gcd[4].gd.pos.width = -1; gcd[4].gd.pos.height = 0; gcd[4].gd.flags = gg_visible | gg_enabled | gg_but_default; gcd[4].gd.cid = 10; gcd[4].creator = GButtonCreate; label[5].text = (unichar_t *) _("_Cancel"); label[5].text_is_1byte = true; label[5].text_in_resource = true; gcd[5].gd.label = &label[5]; gcd[5].gd.pos.x = -20; gcd[5].gd.pos.y = gcd[4].gd.pos.y+3; gcd[5].gd.pos.width = -1; gcd[5].gd.pos.height = 0; gcd[5].gd.flags = gg_visible | gg_enabled | gg_but_cancel; gcd[5].creator = GButtonCreate; GGadgetsCreate(gw,gcd); GDrawSetVisible(gw,true); while ( !d.done ) GDrawProcessOneEvent(NULL); GDrawDestroyWindow(gw); SavePrefs(true); GDrawRequestExpose(fv->v,NULL,false); } static void FV_ChangeDisplayBitmap(FontView *fv,BDFFont *bdf) { FVChangeDisplayFont(fv,bdf); if (fv->show != NULL) { fv->b.sf->display_size = fv->show->pixelsize; } else { fv->b.sf->display_size = 1; } } static void FVMenuSize(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int dspsize = fv->filled->pixelsize; int changedmodifier = false; extern int use_freetype_to_rasterize_fv; fv->magnify = 1; fv->user_requested_magnify = -1; if ( mi->mid == MID_24 ) default_fv_font_size = dspsize = 24; else if ( mi->mid == MID_36 ) default_fv_font_size = dspsize = 36; else if ( mi->mid == MID_48 ) default_fv_font_size = dspsize = 48; else if ( mi->mid == MID_72 ) default_fv_font_size = dspsize = 72; else if ( mi->mid == MID_96 ) default_fv_font_size = dspsize = 96; else if ( mi->mid == MID_128 ) default_fv_font_size = dspsize = 128; else if ( mi->mid == MID_FitToBbox ) { default_fv_bbsized = fv->bbsized = !fv->bbsized; fv->b.sf->display_bbsized = fv->bbsized; changedmodifier = true; } else { default_fv_antialias = fv->antialias = !fv->antialias; fv->b.sf->display_antialias = fv->antialias; changedmodifier = true; } SavePrefs(true); if ( fv->filled!=fv->show || fv->filled->pixelsize != dspsize || changedmodifier ) { BDFFont *new, *old; old = fv->filled; new = SplineFontPieceMeal(fv->b.sf,fv->b.active_layer,dspsize,72, (fv->antialias?pf_antialias:0)|(fv->bbsized?pf_bbsized:0)| (use_freetype_to_rasterize_fv && !fv->b.sf->strokedfont && !fv->b.sf->multilayer?pf_ft_nohints:0), NULL); fv->filled = new; FVChangeDisplayFont(fv,new); BDFFontFree(old); fv->b.sf->display_size = -dspsize; if ( fv->b.cidmaster!=NULL ) { int i; for ( i=0; i<fv->b.cidmaster->subfontcnt; ++i ) fv->b.cidmaster->subfonts[i]->display_size = -dspsize; } } } void FVSetUIToMatch(FontView *destfv,FontView *srcfv) { extern int use_freetype_to_rasterize_fv; if ( destfv->filled==NULL || srcfv->filled==NULL ) return; if ( destfv->magnify!=srcfv->magnify || destfv->user_requested_magnify!=srcfv->user_requested_magnify || destfv->bbsized!=srcfv->bbsized || destfv->antialias!=srcfv->antialias || destfv->filled->pixelsize != srcfv->filled->pixelsize ) { BDFFont *new, *old; destfv->magnify = srcfv->magnify; destfv->user_requested_magnify = srcfv->user_requested_magnify; destfv->bbsized = srcfv->bbsized; destfv->antialias = srcfv->antialias; old = destfv->filled; new = SplineFontPieceMeal(destfv->b.sf,destfv->b.active_layer,srcfv->filled->pixelsize,72, (destfv->antialias?pf_antialias:0)|(destfv->bbsized?pf_bbsized:0)| (use_freetype_to_rasterize_fv && !destfv->b.sf->strokedfont && !destfv->b.sf->multilayer?pf_ft_nohints:0), NULL); destfv->filled = new; FVChangeDisplayFont(destfv,new); BDFFontFree(old); } } static void FV_LayerChanged( FontView *fv ) { extern int use_freetype_to_rasterize_fv; BDFFont *new, *old; fv->magnify = 1; fv->user_requested_magnify = -1; old = fv->filled; new = SplineFontPieceMeal(fv->b.sf,fv->b.active_layer,fv->filled->pixelsize,72, (fv->antialias?pf_antialias:0)|(fv->bbsized?pf_bbsized:0)| (use_freetype_to_rasterize_fv && !fv->b.sf->strokedfont && !fv->b.sf->multilayer?pf_ft_nohints:0), NULL); fv->filled = new; FVChangeDisplayFont(fv,new); fv->b.sf->display_size = -fv->filled->pixelsize; BDFFontFree(old); } static void FVMenuChangeLayer(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); fv->b.active_layer = mi->mid; fv->b.sf->display_layer = mi->mid; FV_LayerChanged(fv); } static void FVMenuMagnify(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int magnify = fv->user_requested_magnify!=-1 ? fv->user_requested_magnify : fv->magnify; char def[20], *end, *ret; int val; BDFFont *show = fv->show; sprintf( def, "%d", magnify ); ret = gwwv_ask_string(_("Bitmap Magnification..."),def,_("Please specify a bitmap magnification factor.")); if ( ret==NULL ) return; val = strtol(ret,&end,10); if ( val<1 || val>5 || *end!='\0' ) ff_post_error( _("Bad Number"),_("Bad Number") ); else { fv->user_requested_magnify = val; fv->show = fv->filled; fv->b.active_bitmap = NULL; FVChangeDisplayFont(fv,show); } free(ret); } static void FVMenuWSize(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int h,v; extern int default_fv_col_count, default_fv_row_count; if ( mi->mid == MID_32x8 ) { h = 32; v=8; } else if ( mi->mid == MID_16x4 ) { h = 16; v=4; } else { h = 8; v=2; } GDrawResize(fv->gw, h*fv->cbw+1+GDrawPointsToPixels(fv->gw,_GScrollBar_Width), v*fv->cbh+1+fv->mbh+fv->infoh); fv->b.sf->desired_col_cnt = default_fv_col_count = h; fv->b.sf->desired_row_cnt = default_fv_row_count = v; SavePrefs(true); } static void FVMenuGlyphLabel(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); default_fv_glyphlabel = fv->glyphlabel = mi->mid; GDrawRequestExpose(fv->v,NULL,false); SavePrefs(true); } static void FVMenuShowBitmap(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); BDFFont *bdf = mi->ti.userdata; FV_ChangeDisplayBitmap(fv,bdf); /* Let's not change any of the others */ } static void FV_ShowFilled(FontView *fv) { fv->magnify = 1; fv->user_requested_magnify = 1; if ( fv->show!=fv->filled ) FVChangeDisplayFont(fv,fv->filled); fv->b.sf->display_size = -fv->filled->pixelsize; fv->b.active_bitmap = NULL; } static void FVMenuCenter(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontViewBase *fv = (FontViewBase *) GDrawGetUserData(gw); FVMetricsCenter(fv,mi->mid==MID_Center); } static void FVMenuSetWidth(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( FVAnyCharSelected(fv)==-1 ) return; if ( mi->mid == MID_SetVWidth && !fv->b.sf->hasvmetrics ) return; FVSetWidth(fv,mi->mid==MID_SetWidth ?wt_width: mi->mid==MID_SetLBearing?wt_lbearing: mi->mid==MID_SetRBearing?wt_rbearing: mi->mid==MID_SetBearings?wt_bearings: wt_vwidth); } static void FVMenuAutoWidth(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVAutoWidth2(fv); } static void FVMenuKernByClasses(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ShowKernClasses(fv->b.sf,NULL,fv->b.active_layer,false); } static void FVMenuVKernByClasses(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); ShowKernClasses(fv->b.sf,NULL,fv->b.active_layer,true); } static void FVMenuRemoveKern(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVRemoveKerns(&fv->b); } static void FVMenuRemoveVKern(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVRemoveVKerns(&fv->b); } static void FVMenuKPCloseup(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) break; KernPairD(fv->b.sf,i==fv->b.map->enccount?NULL: fv->b.map->map[i]==-1?NULL: fv->b.sf->glyphs[fv->b.map->map[i]],NULL,fv->b.active_layer, false); } static void FVMenuVKernFromHKern(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVVKernFromHKern(&fv->b); } static void FVMenuAutoHint(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVAutoHint( &fv->b ); } static void FVMenuAutoHintSubs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVAutoHintSubs( &fv->b ); } static void FVMenuAutoCounter(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVAutoCounter( &fv->b ); } static void FVMenuDontAutoHint(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVDontAutoHint( &fv->b ); } static void FVMenuDeltas(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( !hasFreeTypeDebugger()) return; DeltaSuggestionDlg(fv,NULL); } static void FVMenuAutoInstr(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVAutoInstr( &fv->b ); } static void FVMenuEditInstrs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int index = FVAnyCharSelected(fv); SplineChar *sc; if ( index<0 ) return; sc = SFMakeChar(fv->b.sf,fv->b.map,index); SCEditInstructions(sc); } static void FVMenuEditTable(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFEditTable(fv->b.sf, mi->mid==MID_Editprep?CHR('p','r','e','p'): mi->mid==MID_Editfpgm?CHR('f','p','g','m'): mi->mid==MID_Editmaxp?CHR('m','a','x','p'): CHR('c','v','t',' ')); } static void FVMenuRmInstrTables(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); TtfTablesFree(fv->b.sf->ttf_tables); fv->b.sf->ttf_tables = NULL; if ( !fv->b.sf->changed ) { fv->b.sf->changed = true; FVSetTitles(fv->b.sf); } } static void FVMenuClearInstrs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVClearInstrs(&fv->b); } static void FVMenuClearHints(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVClearHints(&fv->b); } static void FVMenuHistograms(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SFHistogram(fv->b.sf, fv->b.active_layer, NULL, FVAnyCharSelected(fv)!=-1?fv->b.selected:NULL, fv->b.map, mi->mid==MID_HStemHist ? hist_hstem : mi->mid==MID_VStemHist ? hist_vstem : hist_blues); } static void FontViewSetTitle(FontView *fv) { unichar_t *title, *ititle, *temp; char *file=NULL; char *enc; int len; if ( fv->gw==NULL ) /* In scripting */ return; enc = SFEncodingName(fv->b.sf,fv->b.normal?fv->b.normal:fv->b.map); len = strlen(fv->b.sf->fontname)+1 + strlen(enc)+6; if ( fv->b.normal ) len += strlen(_("Compact"))+1; if ( fv->b.cidmaster!=NULL ) { if ( (file = fv->b.cidmaster->filename)==NULL ) file = fv->b.cidmaster->origname; } else { if ( (file = fv->b.sf->filename)==NULL ) file = fv->b.sf->origname; } if ( file!=NULL ) len += 2+strlen(file); title = malloc((len+1)*sizeof(unichar_t)); uc_strcpy(title,""); uc_strcat(title,fv->b.sf->fontname); if ( fv->b.sf->changed ) uc_strcat(title,"*"); if ( file!=NULL ) { uc_strcat(title," "); temp = def2u_copy(GFileNameTail(file)); u_strcat(title,temp); free(temp); } uc_strcat(title, " (" ); if ( fv->b.normal ) { utf82u_strcat(title,_("Compact")); uc_strcat(title," "); } uc_strcat(title,enc); uc_strcat(title, ")" ); free(enc); ititle = uc_copy(fv->b.sf->fontname); GDrawSetWindowTitles(fv->gw,title,ititle); free(title); free(ititle); } void FVTitleUpdate(FontViewBase *fv) { FontViewSetTitle( (FontView*)fv ); } static void FontViewSetTitles(SplineFont *sf) { FontView *fv; for ( fv = (FontView *) (sf->fv); fv!=NULL; fv=(FontView *) (fv->b.nextsame)) FontViewSetTitle(fv); } static void FVMenuShowSubFont(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *new = mi->ti.userdata; FVShowSubFont(fv,new); } static void FVMenuConvert2CID(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; struct cidmap *cidmap; if ( cidmaster!=NULL ) return; SFFindNearTop(fv->b.sf); cidmap = AskUserForCIDMap(); if ( cidmap==NULL ) return; MakeCIDMaster(fv->b.sf,fv->b.map,false,NULL,cidmap); SFRestoreNearTop(fv->b.sf); } static enum fchooserret CMapFilter(GGadget *g,GDirEntry *ent, const unichar_t *dir) { enum fchooserret ret = GFileChooserDefFilter(g,ent,dir); char buf2[256]; FILE *file; static char *cmapflag = "%!PS-Adobe-3.0 Resource-CMap"; if ( ret==fc_show && !ent->isdir ) { int len = 3*(u_strlen(dir)+u_strlen(ent->name)+5); char *filename = malloc(len); u2def_strncpy(filename,dir,len); strcat(filename,"/"); u2def_strncpy(buf2,ent->name,sizeof(buf2)); strcat(filename,buf2); file = fopen(filename,"r"); if ( file==NULL ) ret = fc_hide; else { if ( fgets(buf2,sizeof(buf2),file)==NULL || strncmp(buf2,cmapflag,strlen(cmapflag))!=0 ) ret = fc_hide; fclose(file); } free(filename); } return( ret ); } static void FVMenuConvertByCMap(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; char *cmapfilename; if ( cidmaster!=NULL ) return; cmapfilename = gwwv_open_filename(_("Find an adobe CMap file..."),NULL,NULL,CMapFilter); if ( cmapfilename==NULL ) return; MakeCIDMaster(fv->b.sf,fv->b.map,true,cmapfilename,NULL); free(cmapfilename); } static void FVMenuFlatten(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; if ( cidmaster==NULL ) return; SFFlatten(&cidmaster); } static void FVMenuFlattenByCMap(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; char *cmapname; if ( cidmaster==NULL ) return; cmapname = gwwv_open_filename(_("Find an adobe CMap file..."),NULL,NULL,CMapFilter); if ( cmapname==NULL ) return; SFFindNearTop(fv->b.sf); SFFlattenByCMap(&cidmaster,cmapname); SFRestoreNearTop(fv->b.sf); free(cmapname); } static void FVMenuInsertFont(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; SplineFont *new; struct cidmap *map; char *filename; extern NameList *force_names_when_opening; if ( cidmaster==NULL || cidmaster->subfontcnt>=255 ) /* Open type allows 1 byte to specify the fdselect */ return; filename = GetPostScriptFontName(NULL,false); if ( filename==NULL ) return; new = LoadSplineFont(filename,0); free(filename); if ( new==NULL ) return; if ( new->fv == &fv->b ) /* Already part of us */ return; if ( new->fv != NULL ) { if ( ((FontView *) (new->fv))->gw!=NULL ) GDrawRaise( ((FontView *) (new->fv))->gw); ff_post_error(_("Please close font"),_("Please close %s before inserting it into a CID font"),new->origname); return; } EncMapFree(new->map); if ( force_names_when_opening!=NULL ) SFRenameGlyphsToNamelist(new,force_names_when_opening ); map = FindCidMap(cidmaster->cidregistry,cidmaster->ordering,cidmaster->supplement,cidmaster); SFEncodeToMap(new,map); if ( !PSDictHasEntry(new->private,"lenIV")) PSDictChangeEntry(new->private,"lenIV","1"); /* It's 4 by default, in CIDs the convention seems to be 1 */ new->display_antialias = fv->b.sf->display_antialias; new->display_bbsized = fv->b.sf->display_bbsized; new->display_size = fv->b.sf->display_size; FVInsertInCID((FontViewBase *) fv,new); CIDMasterAsDes(new); } static void FVMenuInsertBlank(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster, *sf; struct cidmap *map; if ( cidmaster==NULL || cidmaster->subfontcnt>=255 ) /* Open type allows 1 byte to specify the fdselect */ return; map = FindCidMap(cidmaster->cidregistry,cidmaster->ordering,cidmaster->supplement,cidmaster); sf = SplineFontBlank(MaxCID(map)); sf->glyphcnt = sf->glyphmax; sf->cidmaster = cidmaster; sf->display_antialias = fv->b.sf->display_antialias; sf->display_bbsized = fv->b.sf->display_bbsized; sf->display_size = fv->b.sf->display_size; sf->private = calloc(1,sizeof(struct psdict)); PSDictChangeEntry(sf->private,"lenIV","1"); /* It's 4 by default, in CIDs the convention seems to be 1 */ FVInsertInCID((FontViewBase *) fv,sf); } static void FVMenuRemoveFontFromCID(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); char *buts[3]; SplineFont *cidmaster = fv->b.cidmaster, *sf = fv->b.sf, *replace; int i; MetricsView *mv, *mnext; FontView *fvs; if ( cidmaster==NULL || cidmaster->subfontcnt<=1 ) /* Can't remove last font */ return; buts[0] = _("_Remove"); buts[1] = _("_Cancel"); buts[2] = NULL; if ( gwwv_ask(_("_Remove Font"),(const char **) buts,0,1,_("Are you sure you wish to remove sub-font %1$.40s from the CID font %2$.40s"), sf->fontname,cidmaster->fontname)==1 ) return; for ( i=0; i<sf->glyphcnt; ++i ) if ( sf->glyphs[i]!=NULL ) { CharView *cv, *next; for ( cv = (CharView *) (sf->glyphs[i]->views); cv!=NULL; cv = next ) { next = (CharView *) (cv->b.next); GDrawDestroyWindow(cv->gw); } } GDrawProcessPendingEvents(NULL); for ( mv=fv->b.sf->metrics; mv!=NULL; mv = mnext ) { mnext = mv->next; GDrawDestroyWindow(mv->gw); } GDrawSync(NULL); GDrawProcessPendingEvents(NULL); /* Just in case... */ GDrawSync(NULL); GDrawProcessPendingEvents(NULL); for ( i=0; i<cidmaster->subfontcnt; ++i ) if ( cidmaster->subfonts[i]==sf ) break; replace = i==0?cidmaster->subfonts[1]:cidmaster->subfonts[i-1]; while ( i<cidmaster->subfontcnt-1 ) { cidmaster->subfonts[i] = cidmaster->subfonts[i+1]; ++i; } --cidmaster->subfontcnt; for ( fvs=(FontView *) (fv->b.sf->fv); fvs!=NULL; fvs=(FontView *) (fvs->b.nextsame) ) { if ( fvs->b.sf==sf ) CIDSetEncMap((FontViewBase *) fvs,replace); } FontViewReformatAll(fv->b.sf); SplineFontFree(sf); } static void FVMenuCIDFontInfo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; if ( cidmaster==NULL ) return; FontInfo(cidmaster,fv->b.active_layer,-1,false); } static void FVMenuChangeSupplement(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *cidmaster = fv->b.cidmaster; struct cidmap *cidmap; char buffer[20]; char *ret, *end; int supple; if ( cidmaster==NULL ) return; sprintf(buffer,"%d",cidmaster->supplement); ret = gwwv_ask_string(_("Change Supplement..."),buffer,_("Please specify a new supplement for %.20s-%.20s"), cidmaster->cidregistry,cidmaster->ordering); if ( ret==NULL ) return; supple = strtol(ret,&end,10); if ( *end!='\0' || supple<=0 ) { free(ret); ff_post_error( _("Bad Number"),_("Bad Number") ); return; } free(ret); if ( supple!=cidmaster->supplement ) { /* this will make noises if it can't find an appropriate cidmap */ cidmap = FindCidMap(cidmaster->cidregistry,cidmaster->ordering,supple,cidmaster); cidmaster->supplement = supple; FontViewSetTitle(fv); } } static SplineChar *FVFindACharInDisplay(FontView *fv) { int start, end, enc, gid; EncMap *map = fv->b.map; SplineFont *sf = fv->b.sf; SplineChar *sc; start = fv->rowoff*fv->colcnt; end = start + fv->rowcnt*fv->colcnt; for ( enc = start; enc<end && enc<map->enccount; ++enc ) { if ( (gid=map->map[enc])!=-1 && (sc=sf->glyphs[gid])!=NULL ) return( sc ); } return( NULL ); } static void FVMenuReencode(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); Encoding *enc = NULL; SplineChar *sc; sc = FVFindACharInDisplay(fv); enc = FindOrMakeEncoding(mi->ti.userdata); if ( enc==NULL ) { IError("Known encoding could not be found"); return; } FVReencode((FontViewBase *) fv,enc); if ( sc!=NULL ) { int enc = fv->b.map->backmap[sc->orig_pos]; if ( enc!=-1 ) FVScrollToChar(fv,enc); } } static void FVMenuForceEncode(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); Encoding *enc = NULL; int oldcnt = fv->b.map->enccount; enc = FindOrMakeEncoding(mi->ti.userdata); if ( enc==NULL ) { IError("Known encoding could not be found"); return; } SFForceEncoding(fv->b.sf,fv->b.map,enc); if ( oldcnt < fv->b.map->enccount ) { fv->b.selected = realloc(fv->b.selected,fv->b.map->enccount); memset(fv->b.selected+oldcnt,0,fv->b.map->enccount-oldcnt); } if ( fv->b.normal!=NULL ) { EncMapFree(fv->b.normal); if (fv->b.normal == fv->b.sf->map) { fv->b.sf->map = NULL; } fv->b.normal = NULL; } SFReplaceEncodingBDFProps(fv->b.sf,fv->b.map); FontViewSetTitle(fv); FontViewReformatOne(&fv->b); } static void FVMenuDisplayByGroups(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); DisplayGroups(fv); } static void FVMenuDefineGroups(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); DefineGroups(fv); } static void FVMenuMMValid(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); MMSet *mm = fv->b.sf->mm; if ( mm==NULL ) return; MMValid(mm,true); } static void FVMenuCreateMM(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { MMWizard(NULL); } static void FVMenuMMInfo(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); MMSet *mm = fv->b.sf->mm; if ( mm==NULL ) return; MMWizard(mm); } static void FVMenuChangeMMBlend(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); MMSet *mm = fv->b.sf->mm; if ( mm==NULL || mm->apple ) return; MMChangeBlend(mm,fv,false); } static void FVMenuBlendToNew(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); MMSet *mm = fv->b.sf->mm; if ( mm==NULL ) return; MMChangeBlend(mm,fv,true); } static void cflistcheck(GWindow UNUSED(gw), struct gmenuitem *mi, GEvent *UNUSED(e)) { /*FontView *fv = (FontView *) GDrawGetUserData(gw);*/ for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_AllFonts: mi->ti.checked = !onlycopydisplayed; break; case MID_DisplayedFont: mi->ti.checked = onlycopydisplayed; break; case MID_CharName: mi->ti.checked = copymetadata; break; case MID_TTFInstr: mi->ti.checked = copyttfinstr; break; } } } static void sllistcheck(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); fv = fv; } static void htlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); int multilayer = fv->b.sf->multilayer; for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_AutoHint: mi->ti.disabled = anychars==-1 || multilayer; break; case MID_HintSubsPt: mi->ti.disabled = fv->b.sf->layers[fv->b.active_layer].order2 || anychars==-1 || multilayer; if ( fv->b.sf->mm!=NULL && fv->b.sf->mm->apple ) mi->ti.disabled = true; break; case MID_AutoCounter: case MID_DontAutoHint: mi->ti.disabled = fv->b.sf->layers[fv->b.active_layer].order2 || anychars==-1 || multilayer; break; case MID_AutoInstr: case MID_EditInstructions: case MID_Deltas: mi->ti.disabled = !fv->b.sf->layers[fv->b.active_layer].order2 || anychars==-1 || multilayer; break; case MID_RmInstrTables: mi->ti.disabled = fv->b.sf->ttf_tables==NULL; break; case MID_Editfpgm: case MID_Editprep: case MID_Editcvt: case MID_Editmaxp: mi->ti.disabled = !fv->b.sf->layers[fv->b.active_layer].order2 || multilayer; break; case MID_ClearHints: case MID_ClearWidthMD: case MID_ClearInstrs: mi->ti.disabled = anychars==-1; break; } } } static void fllistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); FontView *fvs; int in_modal = (fv->b.container!=NULL && fv->b.container->funcs->is_modal); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_GenerateTTC: for ( fvs=fv_list; fvs!=NULL; fvs=(FontView *) (fvs->b.next) ) { if ( fvs!=fv ) break; } mi->ti.disabled = fvs==NULL; break; case MID_Revert: mi->ti.disabled = fv->b.sf->origname==NULL || fv->b.sf->new; break; case MID_RevertToBackup: /* We really do want to use filename here and origname above */ mi->ti.disabled = true; if ( fv->b.sf->filename!=NULL ) { if ( fv->b.sf->backedup == bs_dontknow ) { char *buf = malloc(strlen(fv->b.sf->filename)+20); strcpy(buf,fv->b.sf->filename); if ( fv->b.sf->compression!=0 ) strcat(buf,compressors[fv->b.sf->compression-1].ext); strcat(buf,"~"); if ( access(buf,F_OK)==0 ) fv->b.sf->backedup = bs_backedup; else fv->b.sf->backedup = bs_not; free(buf); } if ( fv->b.sf->backedup == bs_backedup ) mi->ti.disabled = false; } break; case MID_RevertGlyph: mi->ti.disabled = fv->b.sf->origname==NULL || fv->b.sf->sfd_version<2 || anychars==-1 || fv->b.sf->compression!=0; break; case MID_Recent: mi->ti.disabled = !RecentFilesAny(); break; case MID_ScriptMenu: mi->ti.disabled = script_menu_names[0]==NULL; break; case MID_Print: mi->ti.disabled = fv->b.sf->onlybitmaps || in_modal; break; } } } static void edlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int pos = FVAnyCharSelected(fv), i, gid; int not_pasteable = pos==-1 || (!CopyContainsSomething() && #ifndef _NO_LIBPNG !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/png") && #endif !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/svg+xml") && !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/svg-xml") && !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/svg") && !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/bmp") && !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/eps") && !GDrawSelectionHasType(fv->gw,sn_clipboard,"image/ps")); RefChar *base = CopyContainsRef(fv->b.sf); int base_enc = base!=NULL ? fv->b.map->backmap[base->orig_pos] : -1; for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Paste: case MID_PasteInto: mi->ti.disabled = not_pasteable; break; case MID_PasteAfter: mi->ti.disabled = not_pasteable || pos<0; break; case MID_SameGlyphAs: mi->ti.disabled = not_pasteable || base==NULL || fv->b.cidmaster!=NULL || base_enc==-1 || fv->b.selected[base_enc]; /* Can't be self-referential */ break; case MID_Join: case MID_Cut: case MID_Copy: case MID_Clear: case MID_CopyWidth: case MID_CopyLBearing: case MID_CopyRBearing: case MID_CopyRef: case MID_UnlinkRef: case MID_RemoveUndoes: case MID_CopyFgToBg: case MID_CopyL2L: mi->ti.disabled = pos==-1; break; case MID_RplRef: case MID_CorrectRefs: mi->ti.disabled = pos==-1 || fv->b.cidmaster!=NULL || fv->b.sf->multilayer; break; case MID_CopyLookupData: mi->ti.disabled = pos==-1 || (fv->b.sf->gpos_lookups==NULL && fv->b.sf->gsub_lookups==NULL); break; case MID_CopyVWidth: mi->ti.disabled = pos==-1 || !fv->b.sf->hasvmetrics; break; case MID_ClearBackground: mi->ti.disabled = true; if ( pos!=-1 && !( onlycopydisplayed && fv->filled!=fv->show )) { for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] && (gid = fv->b.map->map[i])!=-1 && fv->b.sf->glyphs[gid]!=NULL ) if ( fv->b.sf->glyphs[gid]->layers[ly_back].images!=NULL || fv->b.sf->glyphs[gid]->layers[ly_back].splines!=NULL ) { mi->ti.disabled = false; break; } } break; case MID_Undo: for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] && (gid = fv->b.map->map[i])!=-1 && fv->b.sf->glyphs[gid]!=NULL ) if ( fv->b.sf->glyphs[gid]->layers[fv->b.active_layer].undoes!=NULL ) break; mi->ti.disabled = i==fv->b.map->enccount; break; case MID_Redo: for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] && (gid = fv->b.map->map[i])!=-1 && fv->b.sf->glyphs[gid]!=NULL ) if ( fv->b.sf->glyphs[gid]->layers[fv->b.active_layer].redoes!=NULL ) break; mi->ti.disabled = i==fv->b.map->enccount; break; case MID_UndoFontLevel: mi->ti.disabled = dlist_isempty( (struct dlistnode **)&fv->b.sf->undoes ); break; } } } static void trlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Transform: mi->ti.disabled = anychars==-1; break; case MID_NLTransform: case MID_POV: mi->ti.disabled = anychars==-1 || fv->b.sf->onlybitmaps; break; } } } static void validlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_FindProblems: mi->ti.disabled = anychars==-1; break; case MID_Validate: mi->ti.disabled = fv->b.sf->strokedfont || fv->b.sf->multilayer; break; } } } static void ellistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv), gid; int anybuildable, anytraceable; int in_modal = (fv->b.container!=NULL && fv->b.container->funcs->is_modal); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_FontInfo: mi->ti.disabled = in_modal; break; case MID_CharInfo: mi->ti.disabled = anychars<0 || (gid = fv->b.map->map[anychars])==-1 || (fv->b.cidmaster!=NULL && fv->b.sf->glyphs[gid]==NULL) || in_modal; break; case MID_Transform: mi->ti.disabled = anychars==-1; /* some Transformations make sense on bitmaps now */ break; case MID_AddExtrema: mi->ti.disabled = anychars==-1 || fv->b.sf->onlybitmaps; break; case MID_Simplify: case MID_Stroke: case MID_RmOverlap: mi->ti.disabled = anychars==-1 || fv->b.sf->onlybitmaps; break; case MID_Styles: mi->ti.disabled = anychars==-1 || fv->b.sf->onlybitmaps; break; case MID_Round: case MID_Correct: mi->ti.disabled = anychars==-1 || fv->b.sf->onlybitmaps; break; #ifdef FONTFORGE_CONFIG_TILEPATH case MID_TilePath: mi->ti.disabled = anychars==-1 || fv->b.sf->onlybitmaps; break; #endif case MID_AvailBitmaps: mi->ti.disabled = fv->b.sf->mm!=NULL; break; case MID_RegenBitmaps: case MID_RemoveBitmaps: mi->ti.disabled = fv->b.sf->bitmaps==NULL || fv->b.sf->onlybitmaps || fv->b.sf->mm!=NULL; break; case MID_BuildAccent: anybuildable = false; if ( anychars!=-1 ) { int i; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) { SplineChar *sc=NULL, dummy; gid = fv->b.map->map[i]; if ( gid!=-1 ) sc = fv->b.sf->glyphs[gid]; if ( sc==NULL ) sc = SCBuildDummy(&dummy,fv->b.sf,fv->b.map,i); if ( SFIsSomethingBuildable(fv->b.sf,sc,fv->b.active_layer,false) || SFIsDuplicatable(fv->b.sf,sc)) { anybuildable = true; break; } } } mi->ti.disabled = !anybuildable; break; case MID_Autotrace: anytraceable = false; if ( FindAutoTraceName()!=NULL && anychars!=-1 ) { int i; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] && (gid = fv->b.map->map[i])!=-1 && fv->b.sf->glyphs[gid]!=NULL && fv->b.sf->glyphs[gid]->layers[ly_back].images!=NULL ) { anytraceable = true; break; } } mi->ti.disabled = !anytraceable; break; case MID_MergeFonts: mi->ti.disabled = fv->b.sf->bitmaps!=NULL && fv->b.sf->onlybitmaps; break; case MID_FontCompare: mi->ti.disabled = fv_list->b.next==NULL; break; case MID_InterpolateFonts: mi->ti.disabled = fv->b.sf->onlybitmaps; break; } } } static void mtlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Center: case MID_Thirds: case MID_SetWidth: case MID_SetLBearing: case MID_SetRBearing: case MID_SetBearings: mi->ti.disabled = anychars==-1; break; case MID_SetVWidth: mi->ti.disabled = anychars==-1 || !fv->b.sf->hasvmetrics; break; case MID_VKernByClass: case MID_VKernFromH: case MID_RmVKern: mi->ti.disabled = !fv->b.sf->hasvmetrics; break; } } } #if HANYANG static void hglistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { if ( mi->mid==MID_BuildSyllables || mi->mid==MID_ModifyComposition ) mi->ti.disabled = fv->b.sf->rules==NULL; } } static GMenuItem2 hglist[] = { { { (unichar_t *) N_("_New Composition..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'N' }, H_("New Composition...|No Shortcut"), NULL, NULL, MenuNewComposition }, { { (unichar_t *) N_("_Modify Composition..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("Modify Composition...|No Shortcut"), NULL, NULL, FVMenuModifyComposition, MID_ModifyComposition }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, }}, { { (unichar_t *) N_("_Build Syllables"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Build Syllables|No Shortcut"), NULL, NULL, FVMenuBuildSyllables, MID_BuildSyllables }, { NULL } }; #endif static void balistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { if ( mi->mid==MID_BuildAccent || mi->mid==MID_BuildComposite ) { int anybuildable = false; int onlyaccents = mi->mid==MID_BuildAccent; int i, gid; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) { SplineChar *sc=NULL, dummy; if ( (gid=fv->b.map->map[i])!=-1 ) sc = fv->b.sf->glyphs[gid]; if ( sc==NULL ) sc = SCBuildDummy(&dummy,fv->b.sf,fv->b.map,i); if ( SFIsSomethingBuildable(fv->b.sf,sc,fv->b.active_layer,onlyaccents)) { anybuildable = true; break; } } mi->ti.disabled = !anybuildable; } else if ( mi->mid==MID_BuildDuplicates ) { int anybuildable = false; int i, gid; for ( i=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i] ) { SplineChar *sc=NULL, dummy; if ( (gid=fv->b.map->map[i])!=-1 ) sc = fv->b.sf->glyphs[gid]; if ( sc==NULL ) sc = SCBuildDummy(&dummy,fv->b.sf,fv->b.map,i); if ( SFIsDuplicatable(fv->b.sf,sc)) { anybuildable = true; break; } } mi->ti.disabled = !anybuildable; } } } static void delistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i = FVAnyCharSelected(fv); int gid = i<0 ? -1 : fv->b.map->map[i]; for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_ShowDependentRefs: mi->ti.disabled = gid<0 || fv->b.sf->glyphs[gid]==NULL || fv->b.sf->glyphs[gid]->dependents == NULL; break; case MID_ShowDependentSubs: mi->ti.disabled = gid<0 || fv->b.sf->glyphs[gid]==NULL || !SCUsedBySubs(fv->b.sf->glyphs[gid]); break; } } } static void infolistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_StrikeInfo: mi->ti.disabled = fv->b.sf->bitmaps==NULL; break; case MID_MassRename: mi->ti.disabled = anychars==-1; break; case MID_SetColor: mi->ti.disabled = anychars==-1; break; } } } static GMenuItem2 dummyitem[] = { { { (unichar_t *) N_("Font|_New"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'N' }, NULL, NULL, NULL, NULL, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 fllist[] = { { { (unichar_t *) N_("Font|_New"), (GImage *) "filenew.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'N' }, H_("New|No Shortcut"), NULL, NULL, MenuNew, 0 }, #if HANYANG { { (unichar_t *) N_("_Hangul"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Hangul|No Shortcut"), hglist, hglistcheck, NULL, 0 }, #endif { { (unichar_t *) N_("_Open"), (GImage *) "fileopen.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'O' }, H_("Open|No Shortcut"), NULL, NULL, FVMenuOpen, 0 }, { { (unichar_t *) N_("Recen_t"), (GImage *) "filerecent.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 't' }, H_("Recent|No Shortcut"), dummyitem, MenuRecentBuild, NULL, MID_Recent }, { { (unichar_t *) N_("_Close"), (GImage *) "fileclose.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Close|No Shortcut"), NULL, NULL, FVMenuClose, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Save"), (GImage *) "filesave.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'S' }, H_("Save|No Shortcut"), NULL, NULL, FVMenuSave, 0 }, { { (unichar_t *) N_("S_ave as..."), (GImage *) "filesaveas.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'a' }, H_("Save as...|No Shortcut"), NULL, NULL, FVMenuSaveAs, 0 }, { { (unichar_t *) N_("Save A_ll"), (GImage *) "filesaveall.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Save All|No Shortcut"), NULL, NULL, MenuSaveAll, 0 }, { { (unichar_t *) N_("_Generate Fonts..."), (GImage *) "filegenerate.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'G' }, H_("Generate Fonts...|No Shortcut"), NULL, NULL, FVMenuGenerate, 0 }, { { (unichar_t *) N_("Generate Mac _Family..."), (GImage *) "filegeneratefamily.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Generate Mac Family...|No Shortcut"), NULL, NULL, FVMenuGenerateFamily, 0 }, { { (unichar_t *) N_("Generate TTC..."), (GImage *) "filegeneratefamily.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Generate TTC...|No Shortcut"), NULL, NULL, FVMenuGenerateTTC, MID_GenerateTTC }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Import..."), (GImage *) "fileimport.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Import...|No Shortcut"), NULL, NULL, FVMenuImport, 0 }, { { (unichar_t *) N_("_Merge Feature Info..."), (GImage *) "filemergefeature.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("Merge Feature Info...|No Shortcut"), NULL, NULL, FVMenuMergeKern, 0 }, { { (unichar_t *) N_("_Revert File"), (GImage *) "filerevert.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Revert File|No Shortcut"), NULL, NULL, FVMenuRevert, MID_Revert }, { { (unichar_t *) N_("Revert To _Backup"), (GImage *) "filerevertbackup.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Revert To Backup|No Shortcut"), NULL, NULL, FVMenuRevertBackup, MID_RevertToBackup }, { { (unichar_t *) N_("Revert Gl_yph"), (GImage *) "filerevertglyph.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Revert Glyph|No Shortcut"), NULL, NULL, FVMenuRevertGlyph, MID_RevertGlyph }, { { (unichar_t *) N_("Clear Special Data"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Clear Special Data|No Shortcut"), NULL, NULL, FVMenuClearSpecialData, MID_ClearSpecialData }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Print..."), (GImage *) "fileprint.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Print...|No Shortcut"), NULL, NULL, FVMenuPrint, MID_Print }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ #if !defined(_NO_PYTHON) { { (unichar_t *) N_("E_xecute Script..."), (GImage *) "python.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'x' }, H_("Execute Script...|No Shortcut"), NULL, NULL, FVMenuExecute, 0 }, #elif !defined(_NO_FFSCRIPT) { { (unichar_t *) N_("E_xecute Script..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'x' }, H_("Execute Script...|No Shortcut"), NULL, NULL, FVMenuExecute, 0 }, #endif #if !defined(_NO_FFSCRIPT) { { (unichar_t *) N_("Script Menu"), (GImage *) "fileexecute.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'r' }, H_("Script Menu|No Shortcut"), dummyitem, MenuScriptsBuild, NULL, MID_ScriptMenu }, #endif #if !defined(_NO_FFSCRIPT) || !defined(_NO_PYTHON) { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ #endif { { (unichar_t *) N_("Pr_eferences..."), (GImage *) "fileprefs.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'e' }, H_("Preferences...|No Shortcut"), NULL, NULL, MenuPrefs, 0 }, { { (unichar_t *) N_("_X Resource Editor..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'e' }, H_("X Resource Editor...|No Shortcut"), NULL, NULL, MenuXRes, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Quit"), (GImage *) "filequit.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'Q' }, H_("Quit|Ctl+Q"), /* WARNING: THIS BINDING TO PROPERLY INITIALIZE KEYBOARD INPUT */ NULL, NULL, FVMenuExit, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 cflist[] = { { { (unichar_t *) N_("_All Fonts"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'A' }, H_("All Fonts|No Shortcut"), NULL, NULL, FVMenuCopyFrom, MID_AllFonts }, { { (unichar_t *) N_("_Displayed Font"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'D' }, H_("Displayed Font|No Shortcut"), NULL, NULL, FVMenuCopyFrom, MID_DisplayedFont }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Glyph _Metadata"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'N' }, H_("Glyph Metadata|No Shortcut"), NULL, NULL, FVMenuCopyFrom, MID_CharName }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_TrueType Instructions"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'N' }, H_("TrueType Instructions|No Shortcut"), NULL, NULL, FVMenuCopyFrom, MID_TTFInstr }, GMENUITEM2_EMPTY }; static GMenuItem2 sclist[] = { { { (unichar_t *) N_("Color|Choose..."), (GImage *)"colorwheel.png", COLOR_DEFAULT, COLOR_DEFAULT, (void *) -10, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Choose...|No Shortcut"), NULL, NULL, FVMenuSelectColor, 0 }, { { (unichar_t *) N_("Color|Default"), &def_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Default|No Shortcut"), NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &white_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &red_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &green_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &blue_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &yellow_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &cyan_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, { { NULL, &magenta_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSelectColor, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 sllist[] = { { { (unichar_t *) N_("Select _All"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'A' }, H_("Select All|No Shortcut"), NULL, NULL, FVMenuSelectAll, 0 }, { { (unichar_t *) N_("_Invert Selection"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Invert Selection|No Shortcut"), NULL, NULL, FVMenuInvertSelection, 0 }, { { (unichar_t *) N_("_Deselect All"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Deselect All|Escape"), NULL, NULL, FVMenuDeselectAll, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Select by _Color"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Select by Color|No Shortcut"), sclist, NULL, NULL, 0 }, { { (unichar_t *) N_("Select by _Wildcard..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Select by Wildcard...|No Shortcut"), NULL, NULL, FVMenuSelectByName, 0 }, { { (unichar_t *) N_("Select by _Script..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Select by Script...|No Shortcut"), NULL, NULL, FVMenuSelectByScript, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Glyphs Worth Outputting"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Glyphs Worth Outputting|No Shortcut"), NULL,NULL, FVMenuSelectWorthOutputting, 0 }, { { (unichar_t *) N_("Glyphs with only _References"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Glyphs with only References|No Shortcut"), NULL,NULL, FVMenuGlyphsRefs, 0 }, { { (unichar_t *) N_("Glyphs with only S_plines"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Glyphs with only Splines|No Shortcut"), NULL,NULL, FVMenuGlyphsSplines, 0 }, { { (unichar_t *) N_("Glyphs with both"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Glyphs with both|No Shortcut"), NULL,NULL, FVMenuGlyphsBoth, 0 }, { { (unichar_t *) N_("W_hitespace Glyphs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Whitespace Glyphs|No Shortcut"), NULL,NULL, FVMenuGlyphsWhite, 0 }, { { (unichar_t *) N_("_Changed Glyphs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Changed Glyphs|No Shortcut"), NULL,NULL, FVMenuSelectChanged, 0 }, { { (unichar_t *) N_("_Hinting Needed"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Hinting Needed|No Shortcut"), NULL,NULL, FVMenuSelectHintingNeeded, 0 }, { { (unichar_t *) N_("Autohinta_ble"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Autohintable|No Shortcut"), NULL,NULL, FVMenuSelectAutohintable, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Hold [Shift] key to merge"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 1, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, { { (unichar_t *) N_("Hold [Control] key to restrict"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 1, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Selec_t By Lookup Subtable..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("Select By Lookup Subtable...|No Shortcut"), NULL, NULL, FVMenuSelectByPST, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 edlist[] = { { { (unichar_t *) N_("_Undo"), (GImage *) "editundo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'U' }, H_("Undo|No Shortcut"), NULL, NULL, FVMenuUndo, MID_Undo }, { { (unichar_t *) N_("_Redo"), (GImage *) "editredo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Redo|No Shortcut"), NULL, NULL, FVMenuRedo, MID_Redo}, { { (unichar_t *) N_("Undo Fontlevel"), (GImage *) "editundo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'U' }, H_("Undo Fontlevel|No Shortcut"), NULL, NULL, FVMenuUndoFontLevel, MID_UndoFontLevel }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Cu_t"), (GImage *) "editcut.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 't' }, H_("Cut|No Shortcut"), NULL, NULL, FVMenuCut, MID_Cut }, { { (unichar_t *) N_("_Copy"), (GImage *) "editcopy.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Copy|No Shortcut"), NULL, NULL, FVMenuCopy, MID_Copy }, { { (unichar_t *) N_("C_opy Reference"), (GImage *) "editcopyref.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Copy Reference|No Shortcut"), NULL, NULL, FVMenuCopyRef, MID_CopyRef }, { { (unichar_t *) N_("Copy _Lookup Data"), (GImage *) "editcopylookupdata.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Copy Lookup Data|No Shortcut"), NULL, NULL, FVMenuCopyLookupData, MID_CopyLookupData }, { { (unichar_t *) N_("Copy _Width"), (GImage *) "editcopywidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'W' }, H_("Copy Width|No Shortcut"), NULL, NULL, FVMenuCopyWidth, MID_CopyWidth }, { { (unichar_t *) N_("Copy _VWidth"), (GImage *) "editcopyvwidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, H_("Copy VWidth|No Shortcut"), NULL, NULL, FVMenuCopyWidth, MID_CopyVWidth }, { { (unichar_t *) N_("Co_py LBearing"), (GImage *) "editcopylbearing.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'p' }, H_("Copy LBearing|No Shortcut"), NULL, NULL, FVMenuCopyWidth, MID_CopyLBearing }, { { (unichar_t *) N_("Copy RBearin_g"), (GImage *) "editcopyrbearing.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'g' }, H_("Copy RBearing|No Shortcut"), NULL, NULL, FVMenuCopyWidth, MID_CopyRBearing }, { { (unichar_t *) N_("_Paste"), (GImage *) "editpaste.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Paste|No Shortcut"), NULL, NULL, FVMenuPaste, MID_Paste }, { { (unichar_t *) N_("Paste Into"), (GImage *) "editpasteinto.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Paste Into|No Shortcut"), NULL, NULL, FVMenuPasteInto, MID_PasteInto }, { { (unichar_t *) N_("Paste After"), (GImage *) "editpasteafter.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Paste After|No Shortcut"), NULL, NULL, FVMenuPasteAfter, MID_PasteAfter }, { { (unichar_t *) N_("Sa_me Glyph As"), (GImage *) "editsameas.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'm' }, H_("Same Glyph As|No Shortcut"), NULL, NULL, FVMenuSameGlyphAs, MID_SameGlyphAs }, { { (unichar_t *) N_("C_lear"), (GImage *) "editclear.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Clear|No Shortcut"), NULL, NULL, FVMenuClear, MID_Clear }, { { (unichar_t *) N_("Clear _Background"), (GImage *) "editclearback.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Clear Background|No Shortcut"), NULL, NULL, FVMenuClearBackground, MID_ClearBackground }, { { (unichar_t *) N_("Copy _Fg To Bg"), (GImage *) "editcopyfg2bg.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Copy Fg To Bg|No Shortcut"), NULL, NULL, FVMenuCopyFgBg, MID_CopyFgToBg }, { { (unichar_t *) N_("Copy Layer To Layer"), (GImage *) "editcopylayer2layer.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Copy Layer To Layer|No Shortcut"), NULL, NULL, FVMenuCopyL2L, MID_CopyL2L }, { { (unichar_t *) N_("_Join"), (GImage *) "editjoin.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'J' }, H_("Join|No Shortcut"), NULL, NULL, FVMenuJoin, MID_Join }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Select"), (GImage *) "editselect.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'S' }, H_("Select|No Shortcut"), sllist, sllistcheck, NULL, 0 }, { { (unichar_t *) N_("F_ind / Replace..."), (GImage *) "editfind.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'i' }, H_("Find / Replace...|No Shortcut"), NULL, NULL, FVMenuFindRpl, 0 }, { { (unichar_t *) N_("Replace with Reference"), (GImage *) "editrplref.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'i' }, H_("Replace with Reference|No Shortcut"), NULL, NULL, FVMenuReplaceWithRef, MID_RplRef }, { { (unichar_t *) N_("Correct References"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'i' }, H_("Correct References|No Shortcut"), NULL, NULL, FVMenuCorrectRefs, MID_CorrectRefs }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("U_nlink Reference"), (GImage *) "editunlink.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'U' }, H_("Unlink Reference|No Shortcut"), NULL, NULL, FVMenuUnlinkRef, MID_UnlinkRef }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Copy _From"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Copy From|No Shortcut"), cflist, cflistcheck, NULL, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Remo_ve Undoes"), (GImage *) "editrmundoes.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'e' }, H_("Remove Undoes|No Shortcut"), NULL, NULL, FVMenuRemoveUndoes, MID_RemoveUndoes }, GMENUITEM2_EMPTY }; static GMenuItem2 smlist[] = { { { (unichar_t *) N_("_Simplify"), (GImage *) "elementsimplify.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'S' }, H_("Simplify|No Shortcut"), NULL, NULL, FVMenuSimplify, MID_Simplify }, { { (unichar_t *) N_("Simplify More..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("Simplify More...|No Shortcut"), NULL, NULL, FVMenuSimplifyMore, MID_SimplifyMore }, { { (unichar_t *) N_("Clea_nup Glyph"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'n' }, H_("Cleanup Glyph|No Shortcut"), NULL, NULL, FVMenuCleanup, MID_CleanupGlyph }, { { (unichar_t *) N_("Canonical Start _Point"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'n' }, H_("Canonical Start Point|No Shortcut"), NULL, NULL, FVMenuCanonicalStart, MID_CanonicalStart }, { { (unichar_t *) N_("Canonical _Contours"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'n' }, H_("Canonical Contours|No Shortcut"), NULL, NULL, FVMenuCanonicalContours, MID_CanonicalContours }, GMENUITEM2_EMPTY }; static GMenuItem2 rmlist[] = { { { (unichar_t *) N_("_Remove Overlap"), (GImage *) "overlaprm.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 'O' }, H_("Remove Overlap|No Shortcut"), NULL, NULL, FVMenuOverlap, MID_RmOverlap }, { { (unichar_t *) N_("_Intersect"), (GImage *) "overlapintersection.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Intersect|No Shortcut"), NULL, NULL, FVMenuOverlap, MID_Intersection }, { { (unichar_t *) N_("_Find Intersections"), (GImage *) "overlapfindinter.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, 'O' }, H_("Find Intersections|No Shortcut"), NULL, NULL, FVMenuOverlap, MID_FindInter }, GMENUITEM2_EMPTY }; static GMenuItem2 eflist[] = { { { (unichar_t *) N_("Change _Weight..."), (GImage *) "styleschangeweight.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Change Weight...|No Shortcut"), NULL, NULL, FVMenuEmbolden, MID_Embolden }, { { (unichar_t *) N_("_Italic..."), (GImage *) "stylesitalic.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Italic...|No Shortcut"), NULL, NULL, FVMenuItalic, MID_Italic }, { { (unichar_t *) N_("Obli_que..."), (GImage *) "stylesoblique.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Oblique...|No Shortcut"), NULL, NULL, FVMenuOblique, 0 }, { { (unichar_t *) N_("_Condense/Extend..."), (GImage *) "stylesextendcondense.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Condense/Extend...|No Shortcut"), NULL, NULL, FVMenuCondense, MID_Condense }, { { (unichar_t *) N_("Change _X-Height..."), (GImage *) "styleschangexheight.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Change X-Height...|No Shortcut"), NULL, NULL, FVMenuChangeXHeight, MID_ChangeXHeight }, { { (unichar_t *) N_("Change _Glyph..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Change Glyph...|No Shortcut"), NULL, NULL, FVMenuChangeGlyph, MID_ChangeGlyph }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Add _Small Capitals..."), (GImage *) "stylessmallcaps.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Add Small Capitals...|No Shortcut"), NULL, NULL, FVMenuSmallCaps, MID_SmallCaps }, { { (unichar_t *) N_("Add Subscripts/Superscripts..."), (GImage *) "stylessubsuper.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Add Subscripts/Superscripts...|No Shortcut"), NULL, NULL, FVMenuSubSup, MID_SubSup }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("In_line..."), (GImage *) "stylesinline.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Inline...|No Shortcut"), NULL, NULL, FVMenuInline, 0 }, { { (unichar_t *) N_("_Outline..."), (GImage *) "stylesoutline.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Outline...|No Shortcut"), NULL, NULL, FVMenuOutline, 0 }, { { (unichar_t *) N_("S_hadow..."), (GImage *) "stylesshadow.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Shadow...|No Shortcut"), NULL, NULL, FVMenuShadow, 0 }, { { (unichar_t *) N_("_Wireframe..."), (GImage *) "styleswireframe.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, true, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Wireframe...|No Shortcut"), NULL, NULL, FVMenuWireframe, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 balist[] = { { { (unichar_t *) N_("_Build Accented Glyph"), (GImage *) "elementbuildaccent.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Build Accented Glyph|No Shortcut"), NULL, NULL, FVMenuBuildAccent, MID_BuildAccent }, { { (unichar_t *) N_("Build _Composite Glyph"), (GImage *) "elementbuildcomposite.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Build Composite Glyph|No Shortcut"), NULL, NULL, FVMenuBuildComposite, MID_BuildComposite }, { { (unichar_t *) N_("Buil_d Duplicate Glyph"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Build Duplicate Glyph|No Shortcut"), NULL, NULL, FVMenuBuildDuplicate, MID_BuildDuplicates }, #ifdef KOREAN { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) _STR_ShowGrp, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, NULL, NULL, NULL, FVMenuShowGroup }, #endif GMENUITEM2_EMPTY }; static GMenuItem2 delist[] = { { { (unichar_t *) N_("_References..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'u' }, H_("References...|No Shortcut"), NULL, NULL, FVMenuShowDependentRefs, MID_ShowDependentRefs }, { { (unichar_t *) N_("_Substitutions..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Substitutions...|No Shortcut"), NULL, NULL, FVMenuShowDependentSubs, MID_ShowDependentSubs }, GMENUITEM2_EMPTY }; static GMenuItem2 trlist[] = { { { (unichar_t *) N_("_Transform..."), (GImage *) "elementtransform.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("Transform...|No Shortcut"), NULL, NULL, FVMenuTransform, MID_Transform }, { { (unichar_t *) N_("_Point of View Projection..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("Point of View Projection...|No Shortcut"), NULL, NULL, FVMenuPOV, MID_POV }, { { (unichar_t *) N_("_Non Linear Transform..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("Non Linear Transform...|No Shortcut"), NULL, NULL, FVMenuNLTransform, MID_NLTransform }, GMENUITEM2_EMPTY }; static GMenuItem2 rndlist[] = { { { (unichar_t *) N_("To _Int"), (GImage *) "elementround.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("To Int|No Shortcut"), NULL, NULL, FVMenuRound2Int, MID_Round }, { { (unichar_t *) N_("To _Hundredths"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("To Hundredths|No Shortcut"), NULL, NULL, FVMenuRound2Hundredths, 0 }, { { (unichar_t *) N_("_Cluster"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Cluster|No Shortcut"), NULL, NULL, FVMenuCluster, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 scollist[] = { { { (unichar_t *) N_("Color|Choose..."), (GImage *)"colorwheel.png", COLOR_DEFAULT, COLOR_DEFAULT, (void *) -10, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Choose...|No Shortcut"), NULL, NULL, FVMenuSetColor, 0 }, { { (unichar_t *) N_("Color|Default"), &def_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Default|No Shortcut"), NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &white_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &red_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &green_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &blue_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &yellow_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &cyan_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, { { NULL, &magenta_image, COLOR_DEFAULT, COLOR_DEFAULT, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' }, NULL, NULL, NULL, FVMenuSetColor, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 infolist[] = { { { (unichar_t *) N_("_MATH Info..."), (GImage *) "elementmathinfo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("MATH Info...|No Shortcut"), NULL, NULL, FVMenuMATHInfo, 0 }, { { (unichar_t *) N_("_BDF Info..."), (GImage *) "elementbdfinfo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("BDF Info...|No Shortcut"), NULL, NULL, FVMenuBDFInfo, MID_StrikeInfo }, { { (unichar_t *) N_("_Horizontal Baselines..."), (GImage *) "elementhbaselines.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Horizontal Baselines...|No Shortcut"), NULL, NULL, FVMenuBaseHoriz, 0 }, { { (unichar_t *) N_("_Vertical Baselines..."), (GImage *) "elementvbaselines.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Vertical Baselines...|No Shortcut"), NULL, NULL, FVMenuBaseVert, 0 }, { { (unichar_t *) N_("_Justification..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Justification...|No Shortcut"), NULL, NULL, FVMenuJustify, 0 }, { { (unichar_t *) N_("Show _Dependent"), (GImage *) "elementshowdep.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Show Dependent|No Shortcut"), delist, delistcheck, NULL, 0 }, { { (unichar_t *) N_("Mass Glyph _Rename..."), (GImage *) "elementrenameglyph.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Mass Glyph Rename...|No Shortcut"), NULL, NULL, FVMenuMassRename, MID_MassRename }, { { (unichar_t *) N_("Set _Color"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Set Color|No Shortcut"), scollist, NULL, NULL, MID_SetColor }, GMENUITEM2_EMPTY }; static GMenuItem2 validlist[] = { { { (unichar_t *) N_("Find Pr_oblems..."), (GImage *) "elementfindprobs.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Find Problems...|No Shortcut"), NULL, NULL, FVMenuFindProblems, MID_FindProblems }, { { (unichar_t *) N_("_Validate..."), (GImage *) "elementvalidate.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Validate...|No Shortcut"), NULL, NULL, FVMenuValidate, MID_Validate }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Set E_xtremum Bound..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Set Extremum Bound...|No Shortcut"), NULL, NULL, FVMenuSetExtremumBound, MID_SetExtremumBound }, GMENUITEM2_EMPTY }; static GMenuItem2 ellist[] = { { { (unichar_t *) N_("_Font Info..."), (GImage *) "elementfontinfo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Font Info...|No Shortcut"), NULL, NULL, FVMenuFontInfo, MID_FontInfo }, { { (unichar_t *) N_("_Glyph Info..."), (GImage *) "elementglyphinfo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Glyph Info...|No Shortcut"), NULL, NULL, FVMenuCharInfo, MID_CharInfo }, { { (unichar_t *) N_("Other Info"), (GImage *) "elementotherinfo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Other Info|No Shortcut"), infolist, infolistcheck, NULL, 0 }, { { (unichar_t *) N_("_Validation"), (GImage *) "elementvalidate.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Validation|No Shortcut"), validlist, validlistcheck, NULL, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Bitm_ap Strikes Available..."), (GImage *) "elementbitmapsavail.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'A' }, H_("Bitmap Strikes Available...|No Shortcut"), NULL, NULL, FVMenuBitmaps, MID_AvailBitmaps }, { { (unichar_t *) N_("Regenerate _Bitmap Glyphs..."), (GImage *) "elementregenbitmaps.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Regenerate Bitmap Glyphs...|No Shortcut"), NULL, NULL, FVMenuBitmaps, MID_RegenBitmaps }, { { (unichar_t *) N_("Remove Bitmap Glyphs..."), (GImage *) "elementremovebitmaps.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Remove Bitmap Glyphs...|No Shortcut"), NULL, NULL, FVMenuBitmaps, MID_RemoveBitmaps }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("St_yle"), (GImage *) "elementstyles.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'S' }, H_("Style|No Shortcut"), eflist, NULL, NULL, MID_Styles }, { { (unichar_t *) N_("_Transformations"), (GImage *) "elementtransform.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("Transformations|No Shortcut"), trlist, trlistcheck, NULL, MID_Transform }, { { (unichar_t *) N_("_Expand Stroke..."), (GImage *) "elementexpandstroke.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'E' }, H_("Expand Stroke...|No Shortcut"), NULL, NULL, FVMenuStroke, MID_Stroke }, #ifdef FONTFORGE_CONFIG_TILEPATH { { (unichar_t *) N_("Tile _Path..."), (GImage *) "elementtilepath.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Tile Path...|No Shortcut"), NULL, NULL, FVMenuTilePath, MID_TilePath }, { { (unichar_t *) N_("Tile Pattern..."), (GImage *) "elementtilepattern.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Tile Pattern...|No Shortcut"), NULL, NULL, FVMenuPatternTile, 0 }, #endif { { (unichar_t *) N_("O_verlap"), (GImage *) "overlaprm.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'O' }, H_("Overlap|No Shortcut"), rmlist, NULL, NULL, MID_RmOverlap }, { { (unichar_t *) N_("_Simplify"), (GImage *) "elementsimplify.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'S' }, H_("Simplify|No Shortcut"), smlist, NULL, NULL, MID_Simplify }, { { (unichar_t *) N_("Add E_xtrema"), (GImage *) "elementaddextrema.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'x' }, H_("Add Extrema|No Shortcut"), NULL, NULL, FVMenuAddExtrema, MID_AddExtrema }, { { (unichar_t *) N_("Roun_d"), (GImage *) "elementround.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Round|No Shortcut"), rndlist, NULL, NULL, MID_Round }, { { (unichar_t *) N_("Autot_race"), (GImage *) "elementautotrace.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'r' }, H_("Autotrace|No Shortcut"), NULL, NULL, FVMenuAutotrace, MID_Autotrace }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Correct Direction"), (GImage *) "elementcorrectdir.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'D' }, H_("Correct Direction|No Shortcut"), NULL, NULL, FVMenuCorrectDir, MID_Correct }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("B_uild"), (GImage *) "elementbuildaccent.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Build|No Shortcut"), balist, balistcheck, NULL, MID_BuildAccent }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Merge Fonts..."), (GImage *) "elementmergefonts.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("Merge Fonts...|No Shortcut"), NULL, NULL, FVMenuMergeFonts, MID_MergeFonts }, { { (unichar_t *) N_("Interpo_late Fonts..."), (GImage *) "elementinterpolatefonts.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'p' }, H_("Interpolate Fonts...|No Shortcut"), NULL, NULL, FVMenuInterpFonts, MID_InterpolateFonts }, { { (unichar_t *) N_("Compare Fonts..."), (GImage *) "elementcomparefonts.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'p' }, H_("Compare Fonts...|No Shortcut"), NULL, NULL, FVMenuCompareFonts, MID_FontCompare }, { { (unichar_t *) N_("Compare Layers..."), (GImage *) "elementcomparelayers.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'p' }, H_("Compare Layers...|No Shortcut"), NULL, NULL, FVMenuCompareL2L, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 dummyall[] = { { { (unichar_t *) N_("All"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 1, 0, 0, 0, 0, 0, 1, 1, 0, 'K' }, H_("All|No Shortcut"), NULL, NULL, NULL, 0 }, GMENUITEM2_EMPTY }; /* Builds up a menu containing all the anchor classes */ static void aplistbuild(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); GMenuItemArrayFree(mi->sub); mi->sub = NULL; _aplistbuild(mi,fv->b.sf,FVMenuAnchorPairs); } static GMenuItem2 cblist[] = { { { (unichar_t *) N_("_Kern Pairs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'K' }, H_("Kern Pairs|No Shortcut"), NULL, NULL, FVMenuKernPairs, MID_KernPairs }, { { (unichar_t *) N_("_Anchored Pairs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'K' }, H_("Anchored Pairs|No Shortcut"), dummyall, aplistbuild, NULL, MID_AnchorPairs }, { { (unichar_t *) N_("_Ligatures"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'L' }, H_("Ligatures|No Shortcut"), NULL, NULL, FVMenuLigatures, MID_Ligatures }, GMENUITEM2_EMPTY }; static void cblistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *sf = fv->b.sf; int i, anyligs=0, anykerns=0, gid; PST *pst; if ( sf->kerns ) anykerns=true; for ( i=0; i<fv->b.map->enccount; ++i ) if ( (gid = fv->b.map->map[i])!=-1 && sf->glyphs[gid]!=NULL ) { for ( pst=sf->glyphs[gid]->possub; pst!=NULL; pst=pst->next ) { if ( pst->type==pst_ligature ) { anyligs = true; if ( anykerns ) break; } } if ( sf->glyphs[gid]->kerns!=NULL ) { anykerns = true; if ( anyligs ) break; } } for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Ligatures: mi->ti.disabled = !anyligs; break; case MID_KernPairs: mi->ti.disabled = !anykerns; break; case MID_AnchorPairs: mi->ti.disabled = sf->anchor==NULL; break; } } } static GMenuItem2 gllist[] = { { { (unichar_t *) N_("_Glyph Image"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'K' }, H_("Glyph Image|No Shortcut"), NULL, NULL, FVMenuGlyphLabel, gl_glyph }, { { (unichar_t *) N_("_Name"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'K' }, H_("Name|No Shortcut"), NULL, NULL, FVMenuGlyphLabel, gl_name }, { { (unichar_t *) N_("_Unicode"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'L' }, H_("Unicode|No Shortcut"), NULL, NULL, FVMenuGlyphLabel, gl_unicode }, { { (unichar_t *) N_("_Encoding Hex"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'L' }, H_("Encoding Hex|No Shortcut"), NULL, NULL, FVMenuGlyphLabel, gl_encoding }, GMENUITEM2_EMPTY }; static void gllistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { mi->ti.checked = fv->glyphlabel == mi->mid; } } static GMenuItem2 emptymenu[] = { { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0}, GMENUITEM2_EMPTY }; static void FVEncodingMenuBuild(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( mi->sub!=NULL ) { GMenuItemArrayFree(mi->sub); mi->sub = NULL; } mi->sub = GetEncodingMenu(FVMenuReencode,fv->b.map->enc); } static void FVMenuAddUnencoded(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); char *ret, *end; int cnt; ret = gwwv_ask_string(_("Add Encoding Slots..."),"1",fv->b.cidmaster?_("How many CID slots do you wish to add?"):_("How many unencoded glyph slots do you wish to add?")); if ( ret==NULL ) return; cnt = strtol(ret,&end,10); if ( *end!='\0' || cnt<=0 ) { free(ret); ff_post_error( _("Bad Number"),_("Bad Number") ); return; } free(ret); FVAddUnencoded((FontViewBase *) fv, cnt); } static void FVMenuRemoveUnused(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVRemoveUnused((FontViewBase *) fv); } static void FVMenuCompact(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineChar *sc; sc = FVFindACharInDisplay(fv); FVCompact((FontViewBase *) fv); if ( sc!=NULL ) { int enc = fv->b.map->backmap[sc->orig_pos]; if ( enc!=-1 ) FVScrollToChar(fv,enc); } } static void FVMenuDetachGlyphs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); FVDetachGlyphs((FontViewBase *) fv); } static void FVMenuDetachAndRemoveGlyphs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); char *buts[3]; buts[0] = _("_Remove"); buts[1] = _("_Cancel"); buts[2] = NULL; if ( gwwv_ask(_("Detach & Remove Glyphs"),(const char **) buts,0,1,_("Are you sure you wish to remove these glyphs? This operation cannot be undone."))==1 ) return; FVDetachAndRemoveGlyphs((FontViewBase *) fv); } static void FVForceEncodingMenuBuild(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); if ( mi->sub!=NULL ) { GMenuItemArrayFree(mi->sub); mi->sub = NULL; } mi->sub = GetEncodingMenu(FVMenuForceEncode,fv->b.map->enc); } static void FVMenuAddEncodingName(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { char *ret; Encoding *enc; /* Search the iconv database for the named encoding */ ret = gwwv_ask_string(_("Add Encoding Name..."),NULL,_("Please provide the name of an encoding in the iconv database which you want in the menu.")); if ( ret==NULL ) return; enc = FindOrMakeEncoding(ret); if ( enc==NULL ) ff_post_error(_("Invalid Encoding"),_("Invalid Encoding")); free(ret); } static void FVMenuLoadEncoding(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { LoadEncodingFile(); } static void FVMenuMakeFromFont(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); (void) MakeEncoding(fv->b.sf,fv->b.map); } static void FVMenuRemoveEncoding(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { RemoveEncoding(); } static void FVMenuMakeNamelist(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); char buffer[1025]; char *filename, *temp; FILE *file; snprintf(buffer, sizeof(buffer),"%s/%s.nam", getFontForgeUserDir(Config), fv->b.sf->fontname ); temp = def2utf8_copy(buffer); filename = gwwv_save_filename(_("Make Namelist"), temp,"*.nam"); free(temp); if ( filename==NULL ) return; temp = utf82def_copy(filename); file = fopen(temp,"w"); free(temp); if ( file==NULL ) { ff_post_error(_("Namelist creation failed"),_("Could not write %s"), filename); free(filename); return; } FVB_MakeNamelist((FontViewBase *) fv, file); fclose(file); } static void FVMenuLoadNamelist(GWindow UNUSED(gw), struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { /* Read in a name list and copy it into the prefs dir so that we'll find */ /* it in the future */ /* Be prepared to update what we've already got if names match */ char buffer[1025]; char *ret = gwwv_open_filename(_("Load Namelist"),NULL, "*.nam",NULL); char *temp, *pt; char *buts[3]; FILE *old, *new; int ch, ans; NameList *nl; if ( ret==NULL ) return; /* Cancelled */ temp = utf82def_copy(ret); pt = strrchr(temp,'/'); if ( pt==NULL ) pt = temp; else ++pt; snprintf(buffer,sizeof(buffer),"%s/%s", getFontForgeUserDir(Config), pt); if ( access(buffer,F_OK)==0 ) { buts[0] = _("_Replace"); buts[1] = _("_Cancel"); buts[2] = NULL; ans = gwwv_ask( _("Replace"),(const char **) buts,0,1,_("A name list with this name already exists. Replace it?")); if ( ans==1 ) { free(temp); free(ret); return; } } old = fopen( temp,"r"); if ( old==NULL ) { ff_post_error(_("No such file"),_("Could not read %s"), ret ); free(ret); free(temp); return; } if ( (nl = LoadNamelist(temp))==NULL ) { ff_post_error(_("Bad namelist file"),_("Could not parse %s"), ret ); free(ret); free(temp); fclose(old); return; } free(ret); free(temp); if ( nl->uses_unicode ) { if ( nl->a_utf8_name!=NULL ) ff_post_notice(_("Non-ASCII glyphnames"),_("This namelist contains at least one non-ASCII glyph name, namely: %s"), nl->a_utf8_name ); else ff_post_notice(_("Non-ASCII glyphnames"),_("This namelist is based on a namelist which contains non-ASCII glyph names")); } new = fopen( buffer,"w"); if ( new==NULL ) { ff_post_error(_("Create failed"),_("Could not write %s"), buffer ); fclose(old); return; } while ( (ch=getc(old))!=EOF ) putc(ch,new); fclose(old); fclose(new); } static void FVMenuRenameByNamelist(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); char **namelists = AllNamelistNames(); int i; int ret; NameList *nl; extern int allow_utf8_glyphnames; for ( i=0; namelists[i]!=NULL; ++i ); ret = gwwv_choose(_("Rename by NameList"),(const char **) namelists,i,0,_("Rename the glyphs in this font to the names found in the selected namelist")); if ( ret==-1 ) return; nl = NameListByName(namelists[ret]); if ( nl==NULL ) { IError("Couldn't find namelist"); return; } else if ( nl!=NULL && nl->uses_unicode && !allow_utf8_glyphnames) { ff_post_error(_("Namelist contains non-ASCII names"),_("Glyph names should be limited to characters in the ASCII character set, but there are names in this namelist which use characters outside that range.")); return; } SFRenameGlyphsToNamelist(fv->b.sf,nl); GDrawRequestExpose(fv->v,NULL,false); } static void FVMenuNameGlyphs(GWindow gw, struct gmenuitem *UNUSED(mi), GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); /* Read a file containing a list of names, and add an unencoded glyph for */ /* each name */ char buffer[33]; char *ret = gwwv_open_filename(_("Load glyph names"),NULL, "*",NULL); char *temp, *pt; FILE *file; int ch; SplineChar *sc; FontView *fvs; if ( ret==NULL ) return; /* Cancelled */ temp = utf82def_copy(ret); file = fopen( temp,"r"); if ( file==NULL ) { ff_post_error(_("No such file"),_("Could not read %s"), ret ); free(ret); free(temp); return; } pt = buffer; for (;;) { ch = getc(file); if ( ch!=EOF && !isspace(ch)) { if ( pt<buffer+sizeof(buffer)-1 ) *pt++ = ch; } else { if ( pt!=buffer ) { *pt = '\0'; sc = NULL; for ( fvs=(FontView *) (fv->b.sf->fv); fvs!=NULL; fvs=(FontView *) (fvs->b.nextsame) ) { EncMap *map = fvs->b.map; if ( map->enccount+1>=map->encmax ) map->map = realloc(map->map,(map->encmax += 20)*sizeof(int)); map->map[map->enccount] = -1; fvs->b.selected = realloc(fvs->b.selected,(map->enccount+1)); memset(fvs->b.selected+map->enccount,0,1); ++map->enccount; if ( sc==NULL ) { sc = SFMakeChar(fv->b.sf,map,map->enccount-1); free(sc->name); sc->name = copy(buffer); sc->comment = copy("."); /* Mark as something for sfd file */ } map->map[map->enccount-1] = sc->orig_pos; map->backmap[sc->orig_pos] = map->enccount-1; } pt = buffer; } if ( ch==EOF ) break; } } fclose(file); free(ret); free(temp); FontViewReformatAll(fv->b.sf); } static GMenuItem2 enlist[] = { { { (unichar_t *) N_("_Reencode"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'E' }, H_("Reencode|No Shortcut"), emptymenu, FVEncodingMenuBuild, NULL, MID_Reencode }, { { (unichar_t *) N_("_Compact"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'C' }, H_("Compact|No Shortcut"), NULL, NULL, FVMenuCompact, MID_Compact }, { { (unichar_t *) N_("_Force Encoding"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Force Encoding|No Shortcut"), emptymenu, FVForceEncodingMenuBuild, NULL, MID_ForceReencode }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Add Encoding Slots..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Add Encoding Slots...|No Shortcut"), NULL, NULL, FVMenuAddUnencoded, MID_AddUnencoded }, { { (unichar_t *) N_("Remove _Unused Slots"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Remove Unused Slots|No Shortcut"), NULL, NULL, FVMenuRemoveUnused, MID_RemoveUnused }, { { (unichar_t *) N_("_Detach Glyphs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Detach Glyphs|No Shortcut"), NULL, NULL, FVMenuDetachGlyphs, MID_DetachGlyphs }, { { (unichar_t *) N_("Detach & Remo_ve Glyphs..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Detach & Remove Glyphs...|No Shortcut"), NULL, NULL, FVMenuDetachAndRemoveGlyphs, MID_DetachAndRemoveGlyphs }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Add E_ncoding Name..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Add Encoding Name...|No Shortcut"), NULL, NULL, FVMenuAddEncodingName, 0 }, { { (unichar_t *) N_("_Load Encoding..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Load Encoding...|No Shortcut"), NULL, NULL, FVMenuLoadEncoding, MID_LoadEncoding }, { { (unichar_t *) N_("Ma_ke From Font..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Make From Font...|No Shortcut"), NULL, NULL, FVMenuMakeFromFont, MID_MakeFromFont }, { { (unichar_t *) N_("Remove En_coding..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Remove Encoding...|No Shortcut"), NULL, NULL, FVMenuRemoveEncoding, MID_RemoveEncoding }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Display By _Groups..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Display By Groups...|No Shortcut"), NULL, NULL, FVMenuDisplayByGroups, MID_DisplayByGroups }, { { (unichar_t *) N_("D_efine Groups..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Define Groups...|No Shortcut"), NULL, NULL, FVMenuDefineGroups, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Save Namelist of Font..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Save Namelist of Font...|No Shortcut"), NULL, NULL, FVMenuMakeNamelist, MID_SaveNamelist }, { { (unichar_t *) N_("L_oad Namelist..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Load Namelist...|No Shortcut"), NULL, NULL, FVMenuLoadNamelist, 0 }, { { (unichar_t *) N_("Rename Gl_yphs..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Rename Glyphs...|No Shortcut"), NULL, NULL, FVMenuRenameByNamelist, MID_RenameGlyphs }, { { (unichar_t *) N_("Cre_ate Named Glyphs..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Create Named Glyphs...|No Shortcut"), NULL, NULL, FVMenuNameGlyphs, MID_NameGlyphs }, GMENUITEM2_EMPTY }; static void enlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, gid; SplineFont *sf = fv->b.sf; EncMap *map = fv->b.map; int anyglyphs = false; for ( i=map->enccount-1; i>=0 ; --i ) if ( fv->b.selected[i] && (gid=map->map[i])!=-1 ) anyglyphs = true; for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Compact: mi->ti.checked = fv->b.normal!=NULL; break; case MID_HideNoGlyphSlots: break; case MID_Reencode: case MID_ForceReencode: mi->ti.disabled = fv->b.cidmaster!=NULL; break; case MID_DetachGlyphs: case MID_DetachAndRemoveGlyphs: mi->ti.disabled = !anyglyphs; break; case MID_RemoveUnused: gid = map->enccount>0 ? map->map[map->enccount-1] : -1; mi->ti.disabled = gid!=-1 && SCWorthOutputting(sf->glyphs[gid]); break; case MID_MakeFromFont: mi->ti.disabled = fv->b.cidmaster!=NULL || map->enccount>1024 || map->enc!=&custom; break; case MID_RemoveEncoding: break; case MID_DisplayByGroups: mi->ti.disabled = fv->b.cidmaster!=NULL || group_root==NULL; break; case MID_NameGlyphs: mi->ti.disabled = fv->b.normal!=NULL || fv->b.cidmaster!=NULL; break; case MID_RenameGlyphs: case MID_SaveNamelist: mi->ti.disabled = fv->b.cidmaster!=NULL; break; } } } static GMenuItem2 lylist[] = { { { (unichar_t *) N_("Layer|Foreground"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 1, 0, 1, 1, 0, 0, 1, 1, 0, '\0' }, NULL, NULL, NULL, FVMenuChangeLayer, ly_fore }, GMENUITEM2_EMPTY }; static void lylistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); SplineFont *sf = fv->b.sf; int ly; GMenuItem *sub; sub = calloc(sf->layer_cnt+1,sizeof(GMenuItem)); for ( ly=ly_fore; ly<sf->layer_cnt; ++ly ) { sub[ly-1].ti.text = utf82u_copy(sf->layers[ly].name); sub[ly-1].ti.checkable = true; sub[ly-1].ti.checked = ly == fv->b.active_layer; sub[ly-1].invoke = FVMenuChangeLayer; sub[ly-1].mid = ly; sub[ly-1].ti.fg = sub[ly-1].ti.bg = COLOR_DEFAULT; } GMenuItemArrayFree(mi->sub); mi->sub = sub; } static GMenuItem2 vwlist[] = { { { (unichar_t *) N_("_Next Glyph"), (GImage *) "viewnext.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'N' }, H_("Next Glyph|No Shortcut"), NULL, NULL, FVMenuChangeChar, MID_Next }, { { (unichar_t *) N_("_Prev Glyph"), (GImage *) "viewprev.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Prev Glyph|No Shortcut"), NULL, NULL, FVMenuChangeChar, MID_Prev }, { { (unichar_t *) N_("Next _Defined Glyph"), (GImage *) "viewnextdef.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'D' }, H_("Next Defined Glyph|No Shortcut"), NULL, NULL, FVMenuChangeChar, MID_NextDef }, { { (unichar_t *) N_("Prev Defined Gl_yph"), (GImage *) "viewprevdef.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'a' }, H_("Prev Defined Glyph|No Shortcut"), NULL, NULL, FVMenuChangeChar, MID_PrevDef }, { { (unichar_t *) N_("_Goto"), (GImage *) "viewgoto.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'G' }, H_("Goto|No Shortcut"), NULL, NULL, FVMenuGotoChar, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Layers"), (GImage *) "viewlayers.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Layers|No Shortcut"), lylist, lylistcheck, NULL, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Show ATT"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'S' }, H_("Show ATT|No Shortcut"), NULL, NULL, FVMenuShowAtt, 0 }, { { (unichar_t *) N_("Display S_ubstitutions..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'u' }, H_("Display Substitutions...|No Shortcut"), NULL, NULL, FVMenuDisplaySubs, MID_DisplaySubs }, { { (unichar_t *) N_("Com_binations"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'b' }, H_("Combinations|No Shortcut"), cblist, cblistcheck, NULL, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Label Gl_yph By"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'b' }, H_("Label Glyph By|No Shortcut"), gllist, gllistcheck, NULL, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("S_how H. Metrics..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Show H. Metrics...|No Shortcut"), NULL, NULL, FVMenuShowMetrics, MID_ShowHMetrics }, { { (unichar_t *) N_("Show _V. Metrics..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, H_("Show V. Metrics...|No Shortcut"), NULL, NULL, FVMenuShowMetrics, MID_ShowVMetrics }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("32x8 cell window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '2' }, H_("32x8 cell window|No Shortcut"), NULL, NULL, FVMenuWSize, MID_32x8 }, { { (unichar_t *) N_("_16x4 cell window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '3' }, H_("16x4 cell window|No Shortcut"), NULL, NULL, FVMenuWSize, MID_16x4 }, { { (unichar_t *) N_("_8x2 cell window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '3' }, H_("8x2 cell window|No Shortcut"), NULL, NULL, FVMenuWSize, MID_8x2 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_24 pixel outline"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '2' }, H_("24 pixel outline|No Shortcut"), NULL, NULL, FVMenuSize, MID_24 }, { { (unichar_t *) N_("_36 pixel outline"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '3' }, H_("36 pixel outline|No Shortcut"), NULL, NULL, FVMenuSize, MID_36 }, { { (unichar_t *) N_("_48 pixel outline"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '4' }, H_("48 pixel outline|No Shortcut"), NULL, NULL, FVMenuSize, MID_48 }, { { (unichar_t *) N_("_72 pixel outline"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '4' }, H_("72 pixel outline|No Shortcut"), NULL, NULL, FVMenuSize, MID_72 }, { { (unichar_t *) N_("_96 pixel outline"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '4' }, H_("96 pixel outline|No Shortcut"), NULL, NULL, FVMenuSize, MID_96 }, { { (unichar_t *) N_("_128 pixel outline"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, '4' }, H_("128 pixel outline|No Shortcut"), NULL, NULL, FVMenuSize, MID_128 }, { { (unichar_t *) N_("_Anti Alias"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'A' }, H_("Anti Alias|No Shortcut"), NULL, NULL, FVMenuSize, MID_AntiAlias }, { { (unichar_t *) N_("_Fit to font bounding box"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'F' }, H_("Fit to font bounding box|No Shortcut"), NULL, NULL, FVMenuSize, MID_FitToBbox }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Bitmap _Magnification..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 1, 0, 0, 0, 1, 1, 0, 'F' }, H_("Bitmap Magnification...|No Shortcut"), NULL, NULL, FVMenuMagnify, MID_BitmapMag }, GMENUITEM2_EMPTY, /* Some extra room to show bitmaps */ GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY }; static void vwlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); int i, base; BDFFont *bdf; char buffer[50]; int pos; SplineFont *sf = fv->b.sf; SplineFont *master = sf->cidmaster ? sf->cidmaster : sf; EncMap *map = fv->b.map; OTLookup *otl; for ( i=0; vwlist[i].ti.text==NULL || strcmp((char *) vwlist[i].ti.text, _("Bitmap _Magnification..."))!=0; ++i ); base = i+1; for ( i=base; vwlist[i].ti.text!=NULL; ++i ) { free( vwlist[i].ti.text); vwlist[i].ti.text = NULL; } vwlist[base-1].ti.disabled = true; if ( master->bitmaps!=NULL ) { for ( bdf = master->bitmaps, i=base; i<sizeof(vwlist)/sizeof(vwlist[0])-1 && bdf!=NULL; ++i, bdf = bdf->next ) { if ( BDFDepth(bdf)==1 ) sprintf( buffer, _("%d pixel bitmap"), bdf->pixelsize ); else sprintf( buffer, _("%d@%d pixel bitmap"), bdf->pixelsize, BDFDepth(bdf) ); vwlist[i].ti.text = (unichar_t *) utf82u_copy(buffer); vwlist[i].ti.checkable = true; vwlist[i].ti.checked = bdf==fv->show; vwlist[i].ti.userdata = bdf; vwlist[i].invoke = FVMenuShowBitmap; vwlist[i].ti.fg = vwlist[i].ti.bg = COLOR_DEFAULT; if ( bdf==fv->show ) vwlist[base-1].ti.disabled = false; } } GMenuItemArrayFree(mi->sub); mi->sub = GMenuItem2ArrayCopy(vwlist,NULL); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Next: case MID_Prev: mi->ti.disabled = anychars<0; break; case MID_NextDef: pos = anychars+1; if ( anychars<0 ) pos = map->enccount; for ( ; pos<map->enccount && (map->map[pos]==-1 || !SCWorthOutputting(sf->glyphs[map->map[pos]])); ++pos ); mi->ti.disabled = pos==map->enccount; break; case MID_PrevDef: for ( pos = anychars-1; pos>=0 && (map->map[pos]==-1 || !SCWorthOutputting(sf->glyphs[map->map[pos]])); --pos ); mi->ti.disabled = pos<0; break; case MID_DisplaySubs: { SplineFont *_sf = sf; mi->ti.checked = fv->cur_subtable!=NULL; if ( _sf->cidmaster ) _sf = _sf->cidmaster; for ( otl=_sf->gsub_lookups; otl!=NULL; otl=otl->next ) if ( otl->lookup_type == gsub_single && otl->subtables!=NULL ) break; mi->ti.disabled = otl==NULL; } break; case MID_ShowHMetrics: break; case MID_ShowVMetrics: mi->ti.disabled = !sf->hasvmetrics; break; case MID_32x8: mi->ti.checked = (fv->rowcnt==8 && fv->colcnt==32); mi->ti.disabled = fv->b.container!=NULL; break; case MID_16x4: mi->ti.checked = (fv->rowcnt==4 && fv->colcnt==16); mi->ti.disabled = fv->b.container!=NULL; break; case MID_8x2: mi->ti.checked = (fv->rowcnt==2 && fv->colcnt==8); mi->ti.disabled = fv->b.container!=NULL; break; case MID_24: mi->ti.checked = (fv->show!=NULL && fv->show==fv->filled && fv->show->pixelsize==24); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_36: mi->ti.checked = (fv->show!=NULL && fv->show==fv->filled && fv->show->pixelsize==36); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_48: mi->ti.checked = (fv->show!=NULL && fv->show==fv->filled && fv->show->pixelsize==48); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_72: mi->ti.checked = (fv->show!=NULL && fv->show==fv->filled && fv->show->pixelsize==72); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_96: mi->ti.checked = (fv->show!=NULL && fv->show==fv->filled && fv->show->pixelsize==96); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_128: mi->ti.checked = (fv->show!=NULL && fv->show==fv->filled && fv->show->pixelsize==128); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_AntiAlias: mi->ti.checked = (fv->show!=NULL && fv->show->clut!=NULL); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_FitToBbox: mi->ti.checked = (fv->show!=NULL && fv->show->bbsized); mi->ti.disabled = sf->onlybitmaps && fv->show!=fv->filled; break; case MID_Layers: mi->ti.disabled = sf->layer_cnt<=2 || sf->multilayer; break; } } } static GMenuItem2 histlist[] = { { { (unichar_t *) N_("_HStem"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("HStem|No Shortcut"), NULL, NULL, FVMenuHistograms, MID_HStemHist }, { { (unichar_t *) N_("_VStem"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, H_("VStem|No Shortcut"), NULL, NULL, FVMenuHistograms, MID_VStemHist }, { { (unichar_t *) N_("BlueValues"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("BlueValues|No Shortcut"), NULL, NULL, FVMenuHistograms, MID_BlueValuesHist }, GMENUITEM2_EMPTY }; static GMenuItem2 htlist[] = { { { (unichar_t *) N_("Auto_Hint"), (GImage *) "hintsautohint.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("AutoHint|No Shortcut"), NULL, NULL, FVMenuAutoHint, MID_AutoHint }, { { (unichar_t *) N_("Hint _Substitution Pts"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Hint Substitution Pts|No Shortcut"), NULL, NULL, FVMenuAutoHintSubs, MID_HintSubsPt }, { { (unichar_t *) N_("Auto _Counter Hint"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Auto Counter Hint|No Shortcut"), NULL, NULL, FVMenuAutoCounter, MID_AutoCounter }, { { (unichar_t *) N_("_Don't AutoHint"), (GImage *) "hintsdontautohint.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Don't AutoHint|No Shortcut"), NULL, NULL, FVMenuDontAutoHint, MID_DontAutoHint }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Auto_Instr"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("AutoInstr|No Shortcut"), NULL, NULL, FVMenuAutoInstr, MID_AutoInstr }, { { (unichar_t *) N_("_Edit Instructions..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Edit Instructions...|No Shortcut"), NULL, NULL, FVMenuEditInstrs, MID_EditInstructions }, { { (unichar_t *) N_("Edit 'fpgm'..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Edit 'fpgm'...|No Shortcut"), NULL, NULL, FVMenuEditTable, MID_Editfpgm }, { { (unichar_t *) N_("Edit 'prep'..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Edit 'prep'...|No Shortcut"), NULL, NULL, FVMenuEditTable, MID_Editprep }, { { (unichar_t *) N_("Edit 'maxp'..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Edit 'maxp'...|No Shortcut"), NULL, NULL, FVMenuEditTable, MID_Editmaxp }, { { (unichar_t *) N_("Edit 'cvt '..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Edit 'cvt '...|No Shortcut"), NULL, NULL, FVMenuEditTable, MID_Editcvt }, { { (unichar_t *) N_("Remove Instr Tables"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Remove Instr Tables|No Shortcut"), NULL, NULL, FVMenuRmInstrTables, MID_RmInstrTables }, { { (unichar_t *) N_("S_uggest Deltas..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Suggest Deltas...|No Shortcut"), NULL, NULL, FVMenuDeltas, MID_Deltas }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Clear Hints"), (GImage *) "hintsclearvstems.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Clear Hints|No Shortcut"), NULL, NULL, FVMenuClearHints, MID_ClearHints }, { { (unichar_t *) N_("Clear Instructions"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Clear Instructions|No Shortcut"), NULL, NULL, FVMenuClearInstrs, MID_ClearInstrs }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Histograms"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("Histograms|No Shortcut"), histlist, NULL, NULL, 0 }, GMENUITEM2_EMPTY }; static GMenuItem2 mtlist[] = { { { (unichar_t *) N_("New _Metrics Window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("New Metrics Window|No Shortcut"), NULL, NULL, FVMenuOpenMetrics, MID_OpenMetrics }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Center in Width"), (GImage *) "metricscenter.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Center in Width|No Shortcut"), NULL, NULL, FVMenuCenter, MID_Center }, { { (unichar_t *) N_("_Thirds in Width"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, H_("Thirds in Width|No Shortcut"), NULL, NULL, FVMenuCenter, MID_Thirds }, { { (unichar_t *) N_("Set _Width..."), (GImage *) "metricssetwidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'W' }, H_("Set Width...|No Shortcut"), NULL, NULL, FVMenuSetWidth, MID_SetWidth }, { { (unichar_t *) N_("Set _LBearing..."), (GImage *) "metricssetlbearing.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'L' }, H_("Set LBearing...|No Shortcut"), NULL, NULL, FVMenuSetWidth, MID_SetLBearing }, { { (unichar_t *) N_("Set _RBearing..."), (GImage *) "metricssetrbearing.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Set RBearing...|No Shortcut"), NULL, NULL, FVMenuSetWidth, MID_SetRBearing }, { { (unichar_t *) N_("Set Both Bearings..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Set Both Bearings...|No Shortcut"), NULL, NULL, FVMenuSetWidth, MID_SetBearings }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Set _Vertical Advance..."), (GImage *) "metricssetvwidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, H_("Set Vertical Advance...|No Shortcut"), NULL, NULL, FVMenuSetWidth, MID_SetVWidth }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Auto Width..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'A' }, H_("Auto Width...|No Shortcut"), NULL, NULL, FVMenuAutoWidth, 0 }, { { (unichar_t *) N_("Ker_n By Classes..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'K' }, H_("Kern By Classes...|No Shortcut"), NULL, NULL, FVMenuKernByClasses, 0 }, { { (unichar_t *) N_("Remove All Kern _Pairs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Remove All Kern Pairs|No Shortcut"), NULL, NULL, FVMenuRemoveKern, MID_RmHKern }, { { (unichar_t *) N_("Kern Pair Closeup..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Kern Pair Closeup...|No Shortcut"), NULL, NULL, FVMenuKPCloseup, 0 }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("VKern By Classes..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'K' }, H_("VKern By Classes...|No Shortcut"), NULL, NULL, FVMenuVKernByClasses, MID_VKernByClass }, { { (unichar_t *) N_("VKern From HKern"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("VKern From HKern|No Shortcut"), NULL, NULL, FVMenuVKernFromHKern, MID_VKernFromH }, { { (unichar_t *) N_("Remove All VKern Pairs"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, H_("Remove All VKern Pairs|No Shortcut"), NULL, NULL, FVMenuRemoveVKern, MID_RmVKern }, GMENUITEM2_EMPTY }; static GMenuItem2 cdlist[] = { { { (unichar_t *) N_("_Convert to CID"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Convert to CID|No Shortcut"), NULL, NULL, FVMenuConvert2CID, MID_Convert2CID }, { { (unichar_t *) N_("Convert By C_Map"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("Convert By CMap|No Shortcut"), NULL, NULL, FVMenuConvertByCMap, MID_ConvertByCMap }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Flatten"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("Flatten|No Shortcut"), NULL, NULL, FVMenuFlatten, MID_Flatten }, { { (unichar_t *) N_("Fl_attenByCMap"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("FlattenByCMap|No Shortcut"), NULL, NULL, FVMenuFlattenByCMap, MID_FlattenByCMap }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Insert F_ont..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, H_("Insert Font...|No Shortcut"), NULL, NULL, FVMenuInsertFont, MID_InsertFont }, { { (unichar_t *) N_("Insert _Blank"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("Insert Blank|No Shortcut"), NULL, NULL, FVMenuInsertBlank, MID_InsertBlank }, { { (unichar_t *) N_("_Remove Font"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'R' }, H_("Remove Font|No Shortcut"), NULL, NULL, FVMenuRemoveFontFromCID, MID_RemoveFromCID }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Change Supplement..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Change Supplement...|No Shortcut"), NULL, NULL, FVMenuChangeSupplement, MID_ChangeSupplement }, { { (unichar_t *) N_("C_ID Font Info..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("CID Font Info...|No Shortcut"), NULL, NULL, FVMenuCIDFontInfo, MID_CIDFontInfo }, GMENUITEM2_EMPTY, /* Extra room to show sub-font names */ GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY, GMENUITEM2_EMPTY }; static void cdlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, base, j; SplineFont *sub, *cidmaster = fv->b.cidmaster; for ( i=0; cdlist[i].mid!=MID_CIDFontInfo; ++i ); base = i+2; for ( i=base; cdlist[i].ti.text!=NULL; ++i ) { free( cdlist[i].ti.text); cdlist[i].ti.text = NULL; } cdlist[base-1].ti.fg = cdlist[base-1].ti.bg = COLOR_DEFAULT; if ( cidmaster==NULL ) { cdlist[base-1].ti.line = false; } else { cdlist[base-1].ti.line = true; for ( j = 0, i=base; i<sizeof(cdlist)/sizeof(cdlist[0])-1 && j<cidmaster->subfontcnt; ++i, ++j ) { sub = cidmaster->subfonts[j]; cdlist[i].ti.text = uc_copy(sub->fontname); cdlist[i].ti.checkable = true; cdlist[i].ti.checked = sub==fv->b.sf; cdlist[i].ti.userdata = sub; cdlist[i].invoke = FVMenuShowSubFont; cdlist[i].ti.fg = cdlist[i].ti.bg = COLOR_DEFAULT; } } GMenuItemArrayFree(mi->sub); mi->sub = GMenuItem2ArrayCopy(cdlist,NULL); for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_Convert2CID: case MID_ConvertByCMap: mi->ti.disabled = cidmaster!=NULL || fv->b.sf->mm!=NULL; break; case MID_InsertFont: case MID_InsertBlank: /* OpenType allows at most 255 subfonts (PS allows more, but why go to the effort to make safe font check that? */ mi->ti.disabled = cidmaster==NULL || cidmaster->subfontcnt>=255; break; case MID_RemoveFromCID: mi->ti.disabled = cidmaster==NULL || cidmaster->subfontcnt<=1; break; case MID_Flatten: case MID_FlattenByCMap: case MID_CIDFontInfo: case MID_ChangeSupplement: mi->ti.disabled = cidmaster==NULL; break; } } } static GMenuItem2 mmlist[] = { /* GT: Here (and following) MM means "MultiMaster" */ { { (unichar_t *) N_("_Create MM..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Create MM...|No Shortcut"), NULL, NULL, FVMenuCreateMM, MID_CreateMM }, { { (unichar_t *) N_("MM _Validity Check"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("MM Validity Check|No Shortcut"), NULL, NULL, FVMenuMMValid, MID_MMValid }, { { (unichar_t *) N_("MM _Info..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("MM Info...|No Shortcut"), NULL, NULL, FVMenuMMInfo, MID_MMInfo }, { { (unichar_t *) N_("_Blend to New Font..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Blend to New Font...|No Shortcut"), NULL, NULL, FVMenuBlendToNew, MID_BlendToNew }, { { (unichar_t *) N_("MM Change Default _Weights..."), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("MM Change Default Weights...|No Shortcut"), NULL, NULL, FVMenuChangeMMBlend, MID_ChangeMMBlend }, GMENUITEM2_EMPTY, /* Extra room to show sub-font names */ }; static void mmlistcheck(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)) { FontView *fv = (FontView *) GDrawGetUserData(gw); int i, base, j; MMSet *mm = fv->b.sf->mm; SplineFont *sub; GMenuItem2 *mml; for ( i=0; mmlist[i].mid!=MID_ChangeMMBlend; ++i ); base = i+2; if ( mm==NULL ) mml = mmlist; else { mml = calloc(base+mm->instance_count+2,sizeof(GMenuItem2)); memcpy(mml,mmlist,sizeof(mmlist)); mml[base-1].ti.fg = mml[base-1].ti.bg = COLOR_DEFAULT; mml[base-1].ti.line = true; for ( j = 0, i=base; j<mm->instance_count+1; ++i, ++j ) { if ( j==0 ) sub = mm->normal; else sub = mm->instances[j-1]; mml[i].ti.text = uc_copy(sub->fontname); mml[i].ti.checkable = true; mml[i].ti.checked = sub==fv->b.sf; mml[i].ti.userdata = sub; mml[i].invoke = FVMenuShowSubFont; mml[i].ti.fg = mml[i].ti.bg = COLOR_DEFAULT; } } GMenuItemArrayFree(mi->sub); mi->sub = GMenuItem2ArrayCopy(mml,NULL); if ( mml!=mmlist ) { for ( i=base; mml[i].ti.text!=NULL; ++i ) free( mml[i].ti.text); free(mml); } for ( mi = mi->sub; mi->ti.text!=NULL || mi->ti.line ; ++mi ) { switch ( mi->mid ) { case MID_CreateMM: mi->ti.disabled = false; break; case MID_MMInfo: case MID_MMValid: case MID_BlendToNew: mi->ti.disabled = mm==NULL; break; case MID_ChangeMMBlend: mi->ti.disabled = mm==NULL || mm->apple; break; } } } static GMenuItem2 wnmenu[] = { { { (unichar_t *) N_("New O_utline Window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'u' }, H_("New Outline Window|No Shortcut"), NULL, NULL, FVMenuOpenOutline, MID_OpenOutline }, { { (unichar_t *) N_("New _Bitmap Window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'B' }, H_("New Bitmap Window|No Shortcut"), NULL, NULL, FVMenuOpenBitmap, MID_OpenBitmap }, { { (unichar_t *) N_("New _Metrics Window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("New Metrics Window|No Shortcut"), NULL, NULL, FVMenuOpenMetrics, MID_OpenMetrics }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Warnings"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("Warnings|No Shortcut"), NULL, NULL, _MenuWarnings, MID_Warnings }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, NULL, NULL, NULL, NULL, 0 }, /* line */ GMENUITEM2_EMPTY }; static void FVWindowMenuBuild(GWindow gw, struct gmenuitem *mi, GEvent *e) { FontView *fv = (FontView *) GDrawGetUserData(gw); int anychars = FVAnyCharSelected(fv); struct gmenuitem *wmi; int in_modal = (fv->b.container!=NULL && fv->b.container->funcs->is_modal); WindowMenuBuild(gw,mi,e); for ( wmi = mi->sub; wmi->ti.text!=NULL || wmi->ti.line ; ++wmi ) { switch ( wmi->mid ) { case MID_OpenOutline: wmi->ti.disabled = anychars==-1 || in_modal; break; case MID_OpenBitmap: wmi->ti.disabled = anychars==-1 || fv->b.sf->bitmaps==NULL || in_modal; break; case MID_OpenMetrics: wmi->ti.disabled = in_modal; break; case MID_Warnings: wmi->ti.disabled = ErrorWindowExists(); break; } } } GMenuItem2 helplist[] = { { { (unichar_t *) N_("_Help"), (GImage *) "helphelp.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Help|F1"), NULL, NULL, FVMenuContextualHelp, 0 }, { { (unichar_t *) N_("_Overview"), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Overview|Shft+F1"), NULL, NULL, MenuHelp, 0 }, { { (unichar_t *) N_("_Index"), (GImage *) "helpindex.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, H_("Index|No Shortcut"), NULL, NULL, MenuIndex, 0 }, { { (unichar_t *) N_("_About..."), (GImage *) "helpabout.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'A' }, H_("About...|No Shortcut"), NULL, NULL, MenuAbout, 0 }, { { (unichar_t *) N_("_License..."), (GImage *) "menuempty.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'A' }, H_("License...|No Shortcut"), NULL, NULL, MenuLicense, 0 }, GMENUITEM2_EMPTY }; GMenuItem fvpopupmenu[] = { { { (unichar_t *) N_("New O_utline Window"), 0, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'u' }, '\0', ksm_control, NULL, NULL, FVMenuOpenOutline, MID_OpenOutline }, GMENUITEM_LINE, { { (unichar_t *) N_("Cu_t"), (GImage *) "editcut.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 't' }, '\0', ksm_control, NULL, NULL, FVMenuCut, MID_Cut }, { { (unichar_t *) N_("_Copy"), (GImage *) "editcopy.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, '\0', ksm_control, NULL, NULL, FVMenuCopy, MID_Copy }, { { (unichar_t *) N_("C_opy Reference"), (GImage *) "editcopyref.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'o' }, '\0', ksm_control, NULL, NULL, FVMenuCopyRef, MID_CopyRef }, { { (unichar_t *) N_("Copy _Width"), (GImage *) "editcopywidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'W' }, '\0', ksm_control, NULL, NULL, FVMenuCopyWidth, MID_CopyWidth }, { { (unichar_t *) N_("_Paste"), (GImage *) "editpaste.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'P' }, '\0', ksm_control, NULL, NULL, FVMenuPaste, MID_Paste }, { { (unichar_t *) N_("C_lear"), (GImage *) "editclear.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, 0, 0, NULL, NULL, FVMenuClear, MID_Clear }, { { (unichar_t *) N_("Copy _Fg To Bg"), (GImage *) "editcopyfg2bg.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuCopyFgBg, MID_CopyFgToBg }, { { (unichar_t *) N_("U_nlink Reference"), (GImage *) "editunlink.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'U' }, '\0', ksm_control, NULL, NULL, FVMenuUnlinkRef, MID_UnlinkRef }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, '\0', 0, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Glyph _Info..."), (GImage *) "elementglyphinfo.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, '\0', ksm_control, NULL, NULL, FVMenuCharInfo, MID_CharInfo }, { { (unichar_t *) N_("_Transform..."), (GImage *) "elementtransform.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'T' }, '\0', ksm_control, NULL, NULL, FVMenuTransform, MID_Transform }, { { (unichar_t *) N_("_Expand Stroke..."), (GImage *) "elementexpandstroke.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'E' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuStroke, MID_Stroke }, { { (unichar_t *) N_("To _Int"), (GImage *) "elementround.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'I' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuRound2Int, MID_Round }, { { (unichar_t *) N_("_Correct Direction"), (GImage *) "elementcorrectdir.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'D' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuCorrectDir, MID_Correct }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, '\0', 0, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("Auto_Hint"), (GImage *) "hintsautohint.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuAutoHint, MID_AutoHint }, { { NULL, NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 1, 0, 0, 0, '\0' }, '\0', 0, NULL, NULL, NULL, 0 }, /* line */ { { (unichar_t *) N_("_Center in Width"), (GImage *) "metricscenter.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, '\0', ksm_control, NULL, NULL, FVMenuCenter, MID_Center }, { { (unichar_t *) N_("Set _Width..."), (GImage *) "metricssetwidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'W' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuSetWidth, MID_SetWidth }, { { (unichar_t *) N_("Set _Vertical Advance..."), (GImage *) "metricssetvwidth.png", COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, '\0', ksm_control|ksm_shift, NULL, NULL, FVMenuSetWidth, MID_SetVWidth }, GMENUITEM_EMPTY }; static GMenuItem2 mblist[] = { { { (unichar_t *) N_("_File"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'F' }, H_("File|No Shortcut"), fllist, fllistcheck, NULL, 0 }, { { (unichar_t *) N_("_Edit"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'E' }, H_("Edit|No Shortcut"), edlist, edlistcheck, NULL, 0 }, { { (unichar_t *) N_("E_lement"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Element|No Shortcut"), ellist, ellistcheck, NULL, 0 }, #ifndef _NO_PYTHON { { (unichar_t *) N_("_Tools"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 1, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Tools|No Shortcut"), NULL, fvpy_tllistcheck, NULL, 0 }, #endif #ifdef NATIVE_CALLBACKS { { (unichar_t *) N_("Tools_2"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 1, 1, 0, 0, 0, 0, 1, 1, 0, 'l' }, H_("Tools2|No Shortcut"), NULL, fv_tl2listcheck, NULL, 0 }, #endif { { (unichar_t *) N_("H_ints"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'i' }, H_("Hints|No Shortcut"), htlist, htlistcheck, NULL, 0 }, { { (unichar_t *) N_("E_ncoding"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, H_("Encoding|No Shortcut"), enlist, enlistcheck, NULL, 0 }, { { (unichar_t *) N_("_View"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'V' }, H_("View|No Shortcut"), vwlist, vwlistcheck, NULL, 0 }, { { (unichar_t *) N_("_Metrics"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'M' }, H_("Metrics|No Shortcut"), mtlist, mtlistcheck, NULL, 0 }, { { (unichar_t *) N_("_CID"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'C' }, H_("CID|No Shortcut"), cdlist, cdlistcheck, NULL, 0 }, /* GT: Here (and following) MM means "MultiMaster" */ { { (unichar_t *) N_("MM"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, '\0' }, H_("MM|No Shortcut"), mmlist, mmlistcheck, NULL, 0 }, { { (unichar_t *) N_("_Window"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'W' }, H_("Window|No Shortcut"), wnmenu, FVWindowMenuBuild, NULL, 0 }, { { (unichar_t *) N_("_Help"), NULL, COLOR_DEFAULT, COLOR_DEFAULT, NULL, NULL, 0, 1, 0, 0, 0, 0, 1, 1, 0, 'H' }, H_("Help|No Shortcut"), helplist, NULL, NULL, 0 }, GMENUITEM2_EMPTY }; void FVRefreshChar(FontView *fv,int gid) { BDFChar *bdfc; int i, j, enc; MetricsView *mv; /* Can happen in scripts */ /* Can happen if we do an AutoHint when generating a tiny font for freetype context */ if ( fv->v==NULL || fv->colcnt==0 || fv->b.sf->glyphs[gid]== NULL ) return; for ( fv=(FontView *) (fv->b.sf->fv); fv!=NULL; fv = (FontView *) (fv->b.nextsame) ) { if( !fv->colcnt ) continue; for ( mv=fv->b.sf->metrics; mv!=NULL; mv=mv->next ) MVRefreshChar(mv,fv->b.sf->glyphs[gid]); if ( fv->show==fv->filled ) bdfc = BDFPieceMealCheck(fv->show,gid); else bdfc = fv->show->glyphs[gid]; if ( bdfc==NULL ) bdfc = BDFPieceMeal(fv->show,gid); /* A glyph may be encoded in several places, all need updating */ for ( enc = 0; enc<fv->b.map->enccount; ++enc ) if ( fv->b.map->map[enc]==gid ) { i = enc / fv->colcnt; j = enc - i*fv->colcnt; i -= fv->rowoff; if ( i>=0 && i<fv->rowcnt ) FVDrawGlyph(fv->v,fv,enc,true); } } } void FVRegenChar(FontView *fv,SplineChar *sc) { struct splinecharlist *dlist; MetricsView *mv; if ( fv->v==NULL ) /* Can happen in scripts */ return; if ( sc->orig_pos<fv->filled->glyphcnt ) { BDFCharFree(fv->filled->glyphs[sc->orig_pos]); fv->filled->glyphs[sc->orig_pos] = NULL; } /* FVRefreshChar does NOT do this for us */ for ( mv=fv->b.sf->metrics; mv!=NULL; mv=mv->next ) MVRegenChar(mv,sc); FVRefreshChar(fv,sc->orig_pos); #if HANYANG if ( sc->compositionunit && fv->b.sf->rules!=NULL ) Disp_RefreshChar(fv->b.sf,sc); #endif for ( dlist=sc->dependents; dlist!=NULL; dlist=dlist->next ) FVRegenChar(fv,dlist->sc); } static void AddSubPST(SplineChar *sc,struct lookup_subtable *sub,char *variant) { PST *pst; pst = chunkalloc(sizeof(PST)); pst->type = pst_substitution; pst->subtable = sub; pst->u.alt.components = copy(variant); pst->next = sc->possub; sc->possub = pst; } SplineChar *FVMakeChar(FontView *fv,int enc) { SplineFont *sf = fv->b.sf; SplineChar *base_sc = SFMakeChar(sf,fv->b.map,enc), *feat_sc = NULL; int feat_gid = FeatureTrans(fv,enc); if ( fv->cur_subtable==NULL ) return( base_sc ); if ( feat_gid==-1 ) { int uni = -1; FeatureScriptLangList *fl = fv->cur_subtable->lookup->features; if ( base_sc->unicodeenc>=0x600 && base_sc->unicodeenc<=0x6ff && fl!=NULL && (fl->featuretag == CHR('i','n','i','t') || fl->featuretag == CHR('m','e','d','i') || fl->featuretag == CHR('f','i','n','a') || fl->featuretag == CHR('i','s','o','l')) ) { uni = fl->featuretag == CHR('i','n','i','t') ? ArabicForms[base_sc->unicodeenc-0x600].initial : fl->featuretag == CHR('m','e','d','i') ? ArabicForms[base_sc->unicodeenc-0x600].medial : fl->featuretag == CHR('f','i','n','a') ? ArabicForms[base_sc->unicodeenc-0x600].final : fl->featuretag == CHR('i','s','o','l') ? ArabicForms[base_sc->unicodeenc-0x600].isolated : -1; feat_sc = SFGetChar(sf,uni,NULL); if ( feat_sc!=NULL ) return( feat_sc ); } feat_sc = SFSplineCharCreate(sf); feat_sc->unicodeenc = uni; if ( uni!=-1 ) { feat_sc->name = malloc(8); feat_sc->unicodeenc = uni; sprintf( feat_sc->name,"uni%04X", uni ); } else if ( fv->cur_subtable->suffix!=NULL ) { feat_sc->name = malloc(strlen(base_sc->name)+strlen(fv->cur_subtable->suffix)+2); sprintf( feat_sc->name, "%s.%s", base_sc->name, fv->cur_subtable->suffix ); } else if ( fl==NULL ) { feat_sc->name = strconcat(base_sc->name,".unknown"); } else if ( fl->ismac ) { /* mac feature/setting */ feat_sc->name = malloc(strlen(base_sc->name)+14); sprintf( feat_sc->name,"%s.m%d_%d", base_sc->name, (int) (fl->featuretag>>16), (int) ((fl->featuretag)&0xffff) ); } else { /* OpenType feature tag */ feat_sc->name = malloc(strlen(base_sc->name)+6); sprintf( feat_sc->name,"%s.%c%c%c%c", base_sc->name, (int) (fl->featuretag>>24), (int) ((fl->featuretag>>16)&0xff), (int) ((fl->featuretag>>8)&0xff), (int) ((fl->featuretag)&0xff) ); } SFAddGlyphAndEncode(sf,feat_sc,fv->b.map,fv->b.map->enccount); AddSubPST(base_sc,fv->cur_subtable,feat_sc->name); return( feat_sc ); } else return( base_sc ); } /* we style some glyph names differently, see FVExpose() */ #define _uni_italic 0x2 #define _uni_vertical (1<<2) #define _uni_fontmax (2<<2) static GFont *FVCheckFont(FontView *fv,int type) { FontRequest rq; if ( fv->fontset[type]==NULL ) { memset(&rq,0,sizeof(rq)); rq.utf8_family_name = fv_fontnames; rq.point_size = fv_fontsize; rq.weight = 400; rq.style = 0; if (type&_uni_italic) rq.style |= fs_italic; if (type&_uni_vertical) rq.style |= fs_vertical; fv->fontset[type] = GDrawInstanciateFont(fv->v,&rq); } return( fv->fontset[type] ); } extern unichar_t adobes_pua_alts[0x200][3]; static void do_Adobe_Pua(unichar_t *buf,int sob,int uni) { int i, j; for ( i=j=0; j<sob-1 && i<3; ++i ) { int ch = adobes_pua_alts[uni-0xf600][i]; if ( ch==0 ) break; if ( ch>=0xf600 && ch<=0xf7ff && adobes_pua_alts[ch-0xf600]!=0 ) { do_Adobe_Pua(buf+j,sob-j,ch); while ( buf[j]!=0 ) ++j; } else buf[j++] = ch; } buf[j] = 0; } static void FVExpose(FontView *fv,GWindow pixmap, GEvent *event) { int i, j, y, width, gid; int changed; GRect old, old2, r; GClut clut; struct _GImage base; GImage gi; SplineChar dummy; int styles, laststyles=0; Color bg, def_fg; int fgxor; def_fg = GDrawGetDefaultForeground(NULL); memset(&gi,'\0',sizeof(gi)); memset(&base,'\0',sizeof(base)); if ( fv->show->clut!=NULL ) { gi.u.image = &base; base.image_type = it_index; base.clut = fv->show->clut; GDrawSetDither(NULL, false); base.trans = -1; } else { memset(&clut,'\0',sizeof(clut)); gi.u.image = &base; base.image_type = it_mono; base.clut = &clut; clut.clut_len = 2; clut.clut[0] = view_bgcol; } GDrawSetFont(pixmap,fv->fontset[0]); GDrawSetLineWidth(pixmap,0); GDrawPushClip(pixmap,&event->u.expose.rect,&old); GDrawFillRect(pixmap,NULL,view_bgcol); for ( i=0; i<=fv->rowcnt; ++i ) { GDrawDrawLine(pixmap,0,i*fv->cbh,fv->width,i*fv->cbh,def_fg); GDrawDrawLine(pixmap,0,i*fv->cbh+fv->lab_height,fv->width,i*fv->cbh+fv->lab_height,0x808080); } for ( i=0; i<=fv->colcnt; ++i ) GDrawDrawLine(pixmap,i*fv->cbw,0,i*fv->cbw,fv->height,def_fg); for ( i=event->u.expose.rect.y/fv->cbh; i<=fv->rowcnt && (event->u.expose.rect.y+event->u.expose.rect.height+fv->cbh-1)/fv->cbh; ++i ) for ( j=0; j<fv->colcnt; ++j ) { int index = (i+fv->rowoff)*fv->colcnt+j; SplineChar *sc; styles = 0; if ( index < fv->b.map->enccount && index!=-1 ) { unichar_t buf[60]; char cbuf[8]; char utf8_buf[8]; int use_utf8 = false; Color fg; int uni; struct cidmap *cidmap = NULL; sc = (gid=fv->b.map->map[index])!=-1 ? fv->b.sf->glyphs[gid]: NULL; if ( fv->b.cidmaster!=NULL ) cidmap = FindCidMap(fv->b.cidmaster->cidregistry,fv->b.cidmaster->ordering,fv->b.cidmaster->supplement,fv->b.cidmaster); if ( ( fv->b.map->enc==&custom && index<256 ) || ( fv->b.map->enc!=&custom && index<fv->b.map->enc->char_cnt ) || ( cidmap!=NULL && index<MaxCID(cidmap) )) fg = def_fg; else fg = 0x505050; if ( sc==NULL ) sc = SCBuildDummy(&dummy,fv->b.sf,fv->b.map,index); uni = sc->unicodeenc; buf[0] = buf[1] = 0; if ( fv->b.sf->uni_interp==ui_ams && uni>=0xe000 && uni<=0xf8ff && amspua[uni-0xe000]!=0 ) uni = amspua[uni-0xe000]; switch ( fv->glyphlabel ) { case gl_name: uc_strncpy(buf,sc->name,sizeof(buf)/sizeof(buf[0])); break; case gl_unicode: if ( sc->unicodeenc!=-1 ) { sprintf(cbuf,"%04x",sc->unicodeenc); uc_strcpy(buf,cbuf); } else uc_strcpy(buf,"?"); break; case gl_encoding: if ( fv->b.map->enc->only_1byte || (fv->b.map->enc->has_1byte && index<256)) sprintf(cbuf,"%02x",index); else sprintf(cbuf,"%04x",index); uc_strcpy(buf,cbuf); break; case gl_glyph: if ( uni==0xad ) buf[0] = '-'; else if ( fv->b.sf->uni_interp==ui_adobe && uni>=0xf600 && uni<=0xf7ff && adobes_pua_alts[uni-0xf600]!=0 ) { use_utf8 = false; do_Adobe_Pua(buf,sizeof(buf),uni); } else if ( uni>=0xe0020 && uni<=0xe007e ) { buf[0] = uni-0xe0000; /* A map of Ascii for language names */ #if HANYANG } else if ( sc->compositionunit ) { if ( sc->jamo<19 ) buf[0] = 0x1100+sc->jamo; else if ( sc->jamo<19+21 ) buf[0] = 0x1161 + sc->jamo-19; else /* Leave a hole for the blank char */ buf[0] = 0x11a8 + sc->jamo-(19+21+1); #endif } else if ( uni>0 && uni<unicode4_size ) { char *pt = utf8_buf; use_utf8 = true; *pt = '\0'; // We terminate the string in case the appendage (?) fails. pt = utf8_idpb(pt,uni,0); if (pt) *pt = '\0'; else fprintf(stderr, "Invalid Unicode alert.\n"); } else { char *pt = strchr(sc->name,'.'); buf[0] = '?'; fg = 0xff0000; if ( pt!=NULL ) { int i, n = pt-sc->name; char *end; SplineFont *cm = fv->b.sf->cidmaster; if ( n==7 && sc->name[0]=='u' && sc->name[1]=='n' && sc->name[2]=='i' && (i=strtol(sc->name+3,&end,16), end-sc->name==7)) buf[0] = i; else if ( n>=5 && n<=7 && sc->name[0]=='u' && (i=strtol(sc->name+1,&end,16), end-sc->name==n)) buf[0] = i; else if ( cm!=NULL && (i=CIDFromName(sc->name,cm))!=-1 ) { int uni; uni = CID2Uni(FindCidMap(cm->cidregistry,cm->ordering,cm->supplement,cm), i); if ( uni!=-1 ) buf[0] = uni; } else { int uni; *pt = '\0'; uni = UniFromName(sc->name,fv->b.sf->uni_interp,fv->b.map->enc); if ( uni!=-1 ) buf[0] = uni; *pt = '.'; } if ( strstr(pt,".vert")!=NULL ) styles = _uni_vertical; if ( buf[0]!='?' ) { fg = def_fg; if ( strstr(pt,".italic")!=NULL ) styles = _uni_italic; } } else if ( strncmp(sc->name,"hwuni",5)==0 ) { int uni=-1; sscanf(sc->name,"hwuni%x", (unsigned *) &uni ); if ( uni!=-1 ) buf[0] = uni; } else if ( strncmp(sc->name,"italicuni",9)==0 ) { int uni=-1; sscanf(sc->name,"italicuni%x", (unsigned *) &uni ); if ( uni!=-1 ) { buf[0] = uni; styles=_uni_italic; } fg = def_fg; } else if ( strncmp(sc->name,"vertcid_",8)==0 || strncmp(sc->name,"vertuni",7)==0 ) { styles = _uni_vertical; } } break; } r.x = j*fv->cbw+1; r.width = fv->cbw-1; r.y = i*fv->cbh+1; r.height = fv->lab_height-1; bg = view_bgcol; fgxor = 0x000000; changed = sc->changed; if ( fv->b.sf->onlybitmaps && gid<fv->show->glyphcnt ) changed = gid==-1 || fv->show->glyphs[gid]==NULL? false : fv->show->glyphs[gid]->changed; if ( changed || sc->layers[ly_back].splines!=NULL || sc->layers[ly_back].images!=NULL || sc->color!=COLOR_DEFAULT ) { if ( sc->layers[ly_back].splines!=NULL || sc->layers[ly_back].images!=NULL || sc->color!=COLOR_DEFAULT ) bg = sc->color!=COLOR_DEFAULT?sc->color:0x808080; if ( sc->changed ) { fgxor = bg ^ fvchangedcol; bg = fvchangedcol; } GDrawFillRect(pixmap,&r,bg); } if ( (!fv->b.sf->layers[fv->b.active_layer].order2 && sc->changedsincelasthinted ) || ( fv->b.sf->layers[fv->b.active_layer].order2 && sc->layers[fv->b.active_layer].splines!=NULL && sc->ttf_instrs_len<=0 ) || ( fv->b.sf->layers[fv->b.active_layer].order2 && sc->instructions_out_of_date ) ) { Color hintcol = fvhintingneededcol; if ( fv->b.sf->layers[fv->b.active_layer].order2 && sc->instructions_out_of_date && sc->ttf_instrs_len>0 ) hintcol = 0xff0000; GDrawDrawLine(pixmap,r.x,r.y,r.x,r.y+r.height-1,hintcol); GDrawDrawLine(pixmap,r.x+1,r.y,r.x+1,r.y+r.height-1,hintcol); GDrawDrawLine(pixmap,r.x+2,r.y,r.x+2,r.y+r.height-1,hintcol); GDrawDrawLine(pixmap,r.x+r.width-1,r.y,r.x+r.width-1,r.y+r.height-1,hintcol); GDrawDrawLine(pixmap,r.x+r.width-2,r.y,r.x+r.width-2,r.y+r.height-1,hintcol); GDrawDrawLine(pixmap,r.x+r.width-3,r.y,r.x+r.width-3,r.y+r.height-1,hintcol); } if ( use_utf8 && sc->unicodeenc!=-1 && /* Pango complains if we try to draw non characters */ /* These two are guaranteed "NOT A UNICODE CHARACTER" in all planes */ ((sc->unicodeenc&0xffff)==0xfffe || (sc->unicodeenc&0xffff)==0xffff || (sc->unicodeenc>=0xfdd0 && sc->unicodeenc<=0xfdef) || /* noncharacters */ (sc->unicodeenc>=0xfe00 && sc->unicodeenc<=0xfe0f) || /* variation selectors */ (sc->unicodeenc>=0xe0110 && sc->unicodeenc<=0xe01ff) || /* variation selectors */ /* The surrogates in BMP aren't valid either */ (sc->unicodeenc>=0xd800 && sc->unicodeenc<=0xdfff))) { /* surrogates */ GDrawDrawLine(pixmap,r.x,r.y,r.x+r.width-1,r.y+r.height-1,0x000000); GDrawDrawLine(pixmap,r.x,r.y+r.height-1,r.x+r.width-1,r.y,0x000000); } else if ( use_utf8 ) { GTextBounds size; if ( styles!=laststyles ) GDrawSetFont(pixmap,FVCheckFont(fv,styles)); width = GDrawGetText8Bounds(pixmap,utf8_buf,-1,&size); if ( size.lbearing==0 && size.rbearing==0 ) { utf8_buf[0] = 0xe0 | (0xfffd>>12); utf8_buf[1] = 0x80 | ((0xfffd>>6)&0x3f); utf8_buf[2] = 0x80 | (0xfffd&0x3f); utf8_buf[3] = 0; width = GDrawGetText8Bounds(pixmap,utf8_buf,-1,&size); } width = size.rbearing - size.lbearing+1; if ( width >= fv->cbw-1 ) { GDrawPushClip(pixmap,&r,&old2); width = fv->cbw-1; } if ( sc->unicodeenc<0x80 || sc->unicodeenc>=0xa0 ) { y = i*fv->cbh+fv->lab_as+1; /* move rotated glyph up a bit to center it */ if (styles&_uni_vertical) y -= fv->lab_as/2; GDrawDrawText8(pixmap,j*fv->cbw+(fv->cbw-1-width)/2-size.lbearing,y,utf8_buf,-1,fg^fgxor); } if ( width >= fv->cbw-1 ) GDrawPopClip(pixmap,&old2); laststyles = styles; } else { if ( styles!=laststyles ) GDrawSetFont(pixmap,FVCheckFont(fv,styles)); width = GDrawGetTextWidth(pixmap,buf,-1); if ( width >= fv->cbw-1 ) { GDrawPushClip(pixmap,&r,&old2); width = fv->cbw-1; } if ( sc->unicodeenc<0x80 || sc->unicodeenc>=0xa0 ) { y = i*fv->cbh+fv->lab_as+1; /* move rotated glyph up a bit to center it */ if (styles&_uni_vertical) y -= fv->lab_as/2; GDrawDrawText(pixmap,j*fv->cbw+(fv->cbw-1-width)/2,y,buf,-1,fg^fgxor); } if ( width >= fv->cbw-1 ) GDrawPopClip(pixmap,&old2); laststyles = styles; } } FVDrawGlyph(pixmap,fv,index,false); } if ( fv->showhmetrics&fvm_baseline ) { for ( i=0; i<=fv->rowcnt; ++i ) GDrawDrawLine(pixmap,0,i*fv->cbh+fv->lab_height+fv->magnify*fv->show->ascent+1,fv->width,i*fv->cbh+fv->lab_height+fv->magnify*fv->show->ascent+1,METRICS_BASELINE); } GDrawPopClip(pixmap,&old); GDrawSetDither(NULL, true); } void FVDrawInfo(FontView *fv,GWindow pixmap, GEvent *event) { GRect old, r; Color bg = GDrawGetDefaultBackground(GDrawGetDisplayOfWindow(pixmap)); Color fg = fvglyphinfocol; SplineChar *sc, dummy; SplineFont *sf = fv->b.sf; EncMap *map = fv->b.map; int gid, uni, localenc; GString *output = g_string_new( "" ); gchar *uniname = NULL; if ( event->u.expose.rect.y+event->u.expose.rect.height<=fv->mbh ) { g_string_free( output, TRUE ); output = NULL; return; } GDrawSetFont(pixmap,fv->fontset[0]); GDrawPushClip(pixmap,&event->u.expose.rect,&old); r.x = 0; r.width = fv->width; r.y = fv->mbh; r.height = fv->infoh; GDrawFillRect(pixmap,&r,bg); if ( fv->end_pos>=map->enccount || fv->pressed_pos>=map->enccount || fv->end_pos<0 || fv->pressed_pos<0 ) fv->end_pos = fv->pressed_pos = -1; /* Can happen after reencoding */ if ( fv->end_pos == -1 ) { g_string_free( output, TRUE ); output = NULL; GDrawPopClip(pixmap,&old); return; } localenc = fv->end_pos; if ( map->remap!=NULL ) { struct remap *remap = map->remap; while ( remap->infont!=-1 ) { if ( localenc>=remap->infont && localenc<=remap->infont+(remap->lastenc-remap->firstenc) ) { localenc += remap->firstenc-remap->infont; break; } ++remap; } } g_string_printf( output, "%d (0x%x) ", localenc, localenc ); sc = (gid=fv->b.map->map[fv->end_pos])!=-1 ? sf->glyphs[gid] : NULL; if ( fv->b.cidmaster==NULL || fv->b.normal==NULL || sc==NULL ) SCBuildDummy(&dummy,sf,fv->b.map,fv->end_pos); else dummy = *sc; if ( sc==NULL ) sc = &dummy; uni = dummy.unicodeenc!=-1 ? dummy.unicodeenc : sc->unicodeenc; /* last resort at guessing unicode code point from partial name */ if ( uni == -1 ) { char *pt = strchr( sc->name, '.' ); if( pt != NULL ) { gchar *buf = g_strndup( (const gchar *) sc->name, pt - sc->name ); uni = UniFromName( (char *) buf, fv->b.sf->uni_interp, map->enc ); g_free( buf ); } } if ( uni != -1 ) g_string_append_printf( output, "U+%04X", uni ); else { output = g_string_append( output, "U+????" ); } /* postscript name */ g_string_append_printf( output, " \"%s\" ", sc->name ); /* code point name or range name */ if( uni != -1 ) { uniname = (gchar *) unicode_name( uni ); if ( uniname == NULL ) { uniname = g_strdup( UnicodeRange( uni ) ); } } if ( uniname != NULL ) { output = g_string_append( output, uniname ); g_free( uniname ); } GDrawDrawText8( pixmap, 10, fv->mbh+fv->lab_as, output->str, -1, fg ); g_string_free( output, TRUE ); output = NULL; GDrawPopClip( pixmap, &old ); return; } static void FVShowInfo(FontView *fv) { GRect r; if ( fv->v==NULL ) /* Can happen in scripts */ return; r.x = 0; r.width = fv->width; r.y = fv->mbh; r.height = fv->infoh; GDrawRequestExpose(fv->gw,&r,false); } void FVChar(FontView *fv, GEvent *event) { int i,pos, cnt, gid; extern int navigation_mask; #if MyMemory if ( event->u.chr.keysym == GK_F2 ) { fprintf( stderr, "Malloc debug on\n" ); __malloc_debug(5); } else if ( event->u.chr.keysym == GK_F3 ) { fprintf( stderr, "Malloc debug off\n" ); __malloc_debug(0); } #endif if ( event->u.chr.keysym=='s' && (event->u.chr.state&ksm_control) && (event->u.chr.state&ksm_meta) ) MenuSaveAll(NULL,NULL,NULL); else if ( event->u.chr.keysym=='q' && (event->u.chr.state&ksm_control) && (event->u.chr.state&ksm_meta) ) MenuExit(NULL,NULL,NULL); else if ( event->u.chr.keysym=='I' && (event->u.chr.state&ksm_shift) && (event->u.chr.state&ksm_meta) ) FVMenuCharInfo(fv->gw,NULL,NULL); else if ( (event->u.chr.keysym=='[' || event->u.chr.keysym==']') && (event->u.chr.state&ksm_control) ) { _FVMenuChangeChar(fv,event->u.chr.keysym=='['?MID_Prev:MID_Next); } else if ( (event->u.chr.keysym=='{' || event->u.chr.keysym=='}') && (event->u.chr.state&ksm_control) ) { _FVMenuChangeChar(fv,event->u.chr.keysym=='{'?MID_PrevDef:MID_NextDef); } else if ( event->u.chr.keysym=='\\' && (event->u.chr.state&ksm_control) ) { /* European keyboards need a funky modifier to get \ */ FVDoTransform(fv); #if !defined(_NO_FFSCRIPT) || !defined(_NO_PYTHON) } else if ( isdigit(event->u.chr.keysym) && (event->u.chr.state&ksm_control) && (event->u.chr.state&ksm_meta) ) { /* The Script menu isn't always up to date, so we might get one of */ /* the shortcuts here */ int index = event->u.chr.keysym-'1'; if ( index<0 ) index = 9; if ( script_filenames[index]!=NULL ) ExecuteScriptFile((FontViewBase *) fv,NULL,script_filenames[index]); #endif } else if ( event->u.chr.keysym == GK_Left || event->u.chr.keysym == GK_Tab || event->u.chr.keysym == GK_BackTab || event->u.chr.keysym == GK_Up || event->u.chr.keysym == GK_Right || event->u.chr.keysym == GK_Down || event->u.chr.keysym == GK_KP_Left || event->u.chr.keysym == GK_KP_Up || event->u.chr.keysym == GK_KP_Right || event->u.chr.keysym == GK_KP_Down || event->u.chr.keysym == GK_Home || event->u.chr.keysym == GK_KP_Home || event->u.chr.keysym == GK_End || event->u.chr.keysym == GK_KP_End || event->u.chr.keysym == GK_Page_Up || event->u.chr.keysym == GK_KP_Page_Up || event->u.chr.keysym == GK_Prior || event->u.chr.keysym == GK_Page_Down || event->u.chr.keysym == GK_KP_Page_Down || event->u.chr.keysym == GK_Next ) { int end_pos = fv->end_pos; /* We move the currently selected char. If there is none, then pick */ /* something on the screen */ if ( end_pos==-1 ) end_pos = (fv->rowoff+fv->rowcnt/2)*fv->colcnt; switch ( event->u.chr.keysym ) { case GK_Tab: pos = end_pos; do { if ( event->u.chr.state&ksm_shift ) --pos; else ++pos; if ( pos>=fv->b.map->enccount ) pos = 0; else if ( pos<0 ) pos = fv->b.map->enccount-1; } while ( pos!=end_pos && ((gid=fv->b.map->map[pos])==-1 || !SCWorthOutputting(fv->b.sf->glyphs[gid]))); if ( pos==end_pos ) ++pos; if ( pos>=fv->b.map->enccount ) pos = 0; break; #if GK_Tab!=GK_BackTab case GK_BackTab: pos = end_pos; do { --pos; if ( pos<0 ) pos = fv->b.map->enccount-1; } while ( pos!=end_pos && ((gid=fv->b.map->map[pos])==-1 || !SCWorthOutputting(fv->b.sf->glyphs[gid]))); if ( pos==end_pos ) --pos; if ( pos<0 ) pos = 0; break; #endif case GK_Left: case GK_KP_Left: pos = end_pos-1; break; case GK_Right: case GK_KP_Right: pos = end_pos+1; break; case GK_Up: case GK_KP_Up: pos = end_pos-fv->colcnt; break; case GK_Down: case GK_KP_Down: pos = end_pos+fv->colcnt; break; case GK_End: case GK_KP_End: pos = fv->b.map->enccount; break; case GK_Home: case GK_KP_Home: pos = 0; if ( fv->b.sf->top_enc!=-1 && fv->b.sf->top_enc<fv->b.map->enccount ) pos = fv->b.sf->top_enc; else { pos = SFFindSlot(fv->b.sf,fv->b.map,home_char,NULL); if ( pos==-1 ) pos = 0; } break; case GK_Page_Up: case GK_KP_Page_Up: #if GK_Prior!=GK_Page_Up case GK_Prior: #endif pos = (fv->rowoff-fv->rowcnt+1)*fv->colcnt; break; case GK_Page_Down: case GK_KP_Page_Down: #if GK_Next!=GK_Page_Down case GK_Next: #endif pos = (fv->rowoff+fv->rowcnt+1)*fv->colcnt; break; } if ( pos<0 ) pos = 0; if ( pos>=fv->b.map->enccount ) pos = fv->b.map->enccount-1; if ( event->u.chr.state&ksm_shift && event->u.chr.keysym!=GK_Tab && event->u.chr.keysym!=GK_BackTab ) { FVReselect(fv,pos); } else { FVDeselectAll(fv); fv->b.selected[pos] = true; FVToggleCharSelected(fv,pos); fv->pressed_pos = pos; fv->sel_index = 1; } fv->end_pos = pos; FVShowInfo(fv); FVScrollToChar(fv,pos); } else if ( event->u.chr.keysym == GK_Help ) { MenuHelp(NULL,NULL,NULL); /* Menu does F1 */ } else if ( event->u.chr.keysym == GK_Escape ) { FVDeselectAll(fv); } else if ( event->u.chr.chars[0]=='\r' || event->u.chr.chars[0]=='\n' ) { if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; for ( i=cnt=0; i<fv->b.map->enccount && cnt<10; ++i ) if ( fv->b.selected[i] ) { SplineChar *sc = SFMakeChar(fv->b.sf,fv->b.map,i); if ( fv->show==fv->filled ) { CharViewCreate(sc,fv,i); } else { BDFFont *bdf = fv->show; BitmapViewCreate(BDFMakeGID(bdf,sc->orig_pos),bdf,fv,i); } ++cnt; } } else if ( (event->u.chr.state&((GMenuMask()|navigation_mask)&~(ksm_shift|ksm_capslock)))==navigation_mask && event->type == et_char && event->u.chr.keysym!=0 && (event->u.chr.keysym<GK_Special/* || event->u.chr.keysym>=0x10000*/)) { SplineFont *sf = fv->b.sf; int enc = EncFromUni(event->u.chr.keysym,fv->b.map->enc); if ( enc==-1 ) { for ( i=0; i<sf->glyphcnt; ++i ) { if ( sf->glyphs[i]!=NULL ) if ( sf->glyphs[i]->unicodeenc==event->u.chr.keysym ) break; } if ( i!=-1 ) enc = fv->b.map->backmap[i]; } if ( enc<fv->b.map->enccount && enc!=-1 ) FVChangeChar(fv,enc); } } static void utf82u_annot_strncat(unichar_t *to, const char *from, int len) { register unichar_t ch; to += u_strlen(to); while ( (ch = utf8_ildb(&from)) != '\0' && --len>=0 ) { if ( ch=='\t' ) { *(to++) = ' '; ch = ' '; } *(to++) = ch; } *to = 0; } void SCPreparePopup(GWindow gw,SplineChar *sc,struct remap *remap, int localenc, int actualuni) { /* This is for the popup which appears when you hover mouse over a character on main window */ int upos=-1; char *msg, *msg_old; /* If a glyph is multiply mapped then the inbuild unicode enc may not be */ /* the actual one used to access the glyph */ if ( remap!=NULL ) { while ( remap->infont!=-1 ) { if ( localenc>=remap->infont && localenc<=remap->infont+(remap->lastenc-remap->firstenc) ) { localenc += remap->firstenc-remap->infont; break; } ++remap; } } if ( actualuni!=-1 ) upos = actualuni; else if ( sc->unicodeenc!=-1 ) upos = sc->unicodeenc; #if HANYANG else if ( sc->compositionunit ) { if ( sc->jamo<19 ) upos = 0x1100+sc->jamo; else if ( sc->jamo<19+21 ) upos = 0x1161 + sc->jamo-19; else /* Leave a hole for the blank char */ upos = 0x11a8 + sc->jamo-(19+21+1); } #endif if ( upos == -1 ) { msg = smprintf( "%u 0x%x U+???? \"%.25s\" ", localenc, localenc, (sc->name == NULL) ? "" : sc->name ); } else { /* unicode name or range name */ char *uniname = unicode_name( upos ); if( uniname == NULL ) uniname = strdup( UnicodeRange( upos ) ); msg = smprintf ( "%u 0x%x U+%04X \"%.25s\" %.100s", localenc, localenc, upos, (sc->name == NULL) ? "" : sc->name, uniname ); if ( uniname != NULL ) free( uniname ); uniname = NULL; /* annotation */ char *uniannot = unicode_annot( upos ); if( uniannot != NULL ) { msg_old = msg; msg = smprintf("%s\n%s", msg_old, uniannot); free(msg_old); free( uniannot ); } } /* user comments */ if ( sc->comment!=NULL ) { msg_old = msg; msg = smprintf("%s\n%s", msg_old, sc->comment); free(msg_old); } GGadgetPreparePopup8( gw, msg ); free(msg); } static void noop(void *UNUSED(_fv)) { } static void *ddgencharlist(void *_fv,int32 *len) { int i,j,cnt, gid; FontView *fv = (FontView *) _fv; SplineFont *sf = fv->b.sf; EncMap *map = fv->b.map; char *data; for ( i=cnt=0; i<map->enccount; ++i ) if ( fv->b.selected[i] && (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL ) cnt += strlen(sf->glyphs[gid]->name)+1; data = malloc(cnt+1); data[0] = '\0'; for ( cnt=0, j=1 ; j<=fv->sel_index; ++j ) { for ( i=cnt=0; i<map->enccount; ++i ) if ( fv->b.selected[i] && (gid=map->map[i])!=-1 && sf->glyphs[gid]!=NULL ) { strcpy(data+cnt,sf->glyphs[gid]->name); cnt += strlen(sf->glyphs[gid]->name); strcpy(data+cnt++," "); } } if ( cnt>0 ) data[--cnt] = '\0'; *len = cnt; return( data ); } static void FVMouse(FontView *fv, GEvent *event) { int pos = (event->u.mouse.y/fv->cbh + fv->rowoff)*fv->colcnt + event->u.mouse.x/fv->cbw; int gid; int realpos = pos; SplineChar *sc, dummy; int dopopup = true; if ( event->type==et_mousedown ) CVPaletteDeactivate(); if ( pos<0 ) { pos = 0; dopopup = false; } else if ( pos>=fv->b.map->enccount ) { pos = fv->b.map->enccount-1; if ( pos<0 ) /* No glyph slots in font */ return; dopopup = false; } sc = (gid=fv->b.map->map[pos])!=-1 ? fv->b.sf->glyphs[gid] : NULL; if ( sc==NULL ) sc = SCBuildDummy(&dummy,fv->b.sf,fv->b.map,pos); if ( event->type == et_mouseup && event->u.mouse.clicks==2 ) { if ( fv->pressed ) { GDrawCancelTimer(fv->pressed); fv->pressed = NULL; } if ( fv->b.container!=NULL && fv->b.container->funcs->is_modal ) return; if ( fv->cur_subtable!=NULL ) { sc = FVMakeChar(fv,pos); pos = fv->b.map->backmap[sc->orig_pos]; } if ( sc==&dummy ) { sc = SFMakeChar(fv->b.sf,fv->b.map,pos); gid = fv->b.map->map[pos]; } if ( fv->show==fv->filled ) { SplineFont *sf = fv->b.sf; gid = -1; if ( !OpenCharsInNewWindow ) for ( gid=sf->glyphcnt-1; gid>=0; --gid ) if ( sf->glyphs[gid]!=NULL && sf->glyphs[gid]->views!=NULL ) break; if ( gid!=-1 ) { CharView *cv = (CharView *) (sf->glyphs[gid]->views); // printf("calling CVChangeSC() sc:%p %s\n", sc, sc->name ); CVChangeSC(cv,sc); GDrawSetVisible(cv->gw,true); GDrawRaise(cv->gw); } else CharViewCreate(sc,fv,pos); } else { BDFFont *bdf = fv->show; BDFChar *bc =BDFMakeGID(bdf,gid); gid = -1; if ( !OpenCharsInNewWindow ) for ( gid=bdf->glyphcnt-1; gid>=0; --gid ) if ( bdf->glyphs[gid]!=NULL && bdf->glyphs[gid]->views!=NULL ) break; if ( gid!=-1 ) { BitmapView *bv = bdf->glyphs[gid]->views; BVChangeBC(bv,bc,true); GDrawSetVisible(bv->gw,true); GDrawRaise(bv->gw); } else BitmapViewCreate(bc,bdf,fv,pos); } } else if ( event->type == et_mousemove ) { if ( dopopup ) SCPreparePopup(fv->v,sc,fv->b.map->remap,pos,sc==&dummy?dummy.unicodeenc: UniFromEnc(pos,fv->b.map->enc)); } if ( event->type == et_mousedown ) { if ( fv->drag_and_drop ) { GDrawSetCursor(fv->v,ct_mypointer); fv->any_dd_events_sent = fv->drag_and_drop = false; } if ( !(event->u.mouse.state&ksm_shift) && event->u.mouse.clicks<=1 ) { if ( !fv->b.selected[pos] ) FVDeselectAll(fv); else if ( event->u.mouse.button!=3 ) { fv->drag_and_drop = fv->has_dd_no_cursor = true; fv->any_dd_events_sent = false; GDrawSetCursor(fv->v,ct_prohibition); GDrawGrabSelection(fv->v,sn_drag_and_drop); GDrawAddSelectionType(fv->v,sn_drag_and_drop,"STRING",fv,0,sizeof(char), ddgencharlist,noop); } } fv->pressed_pos = fv->end_pos = pos; FVShowInfo(fv); if ( !fv->drag_and_drop ) { if ( !(event->u.mouse.state&ksm_shift)) fv->sel_index = 1; else if ( fv->sel_index<255 ) ++fv->sel_index; if ( fv->pressed!=NULL ) { GDrawCancelTimer(fv->pressed); fv->pressed = NULL; } else if ( event->u.mouse.state&ksm_shift ) { fv->b.selected[pos] = fv->b.selected[pos] ? 0 : fv->sel_index; FVToggleCharSelected(fv,pos); } else if ( !fv->b.selected[pos] ) { fv->b.selected[pos] = fv->sel_index; FVToggleCharSelected(fv,pos); } if ( event->u.mouse.button==3 ) GMenuCreatePopupMenuWithName(fv->v,event, "Popup", fvpopupmenu); else fv->pressed = GDrawRequestTimer(fv->v,200,100,NULL); } } else if ( fv->drag_and_drop ) { GWindow othergw = GDrawGetPointerWindow(fv->v); if ( othergw==fv->v || othergw==fv->gw || othergw==NULL ) { if ( !fv->has_dd_no_cursor ) { fv->has_dd_no_cursor = true; GDrawSetCursor(fv->v,ct_prohibition); } } else { if ( fv->has_dd_no_cursor ) { fv->has_dd_no_cursor = false; GDrawSetCursor(fv->v,ct_ddcursor); } } if ( event->type==et_mouseup ) { if ( pos!=fv->pressed_pos ) { GDrawPostDragEvent(fv->v,event,event->type==et_mouseup?et_drop:et_drag); fv->any_dd_events_sent = true; } fv->drag_and_drop = fv->has_dd_no_cursor = false; GDrawSetCursor(fv->v,ct_mypointer); if ( !fv->any_dd_events_sent ) FVDeselectAll(fv); fv->any_dd_events_sent = false; } } else if ( fv->pressed!=NULL ) { int showit = realpos!=fv->end_pos; FVReselect(fv,realpos); if ( showit ) FVShowInfo(fv); if ( event->type==et_mouseup ) { GDrawCancelTimer(fv->pressed); fv->pressed = NULL; } } if ( event->type==et_mouseup && dopopup ) SCPreparePopup(fv->v,sc,fv->b.map->remap,pos,sc==&dummy?dummy.unicodeenc: UniFromEnc(pos,fv->b.map->enc)); if ( event->type==et_mouseup ) SVAttachFV(fv,2); } static void FVResize(FontView *fv, GEvent *event) { extern int default_fv_row_count, default_fv_col_count; GRect pos,screensize; int topchar; if ( fv->colcnt!=0 ) topchar = fv->rowoff*fv->colcnt; else if ( fv->b.sf->top_enc!=-1 && fv->b.sf->top_enc<fv->b.map->enccount ) topchar = fv->b.sf->top_enc; else { /* Position on 'A' (or whatever they ask for) if it exists */ topchar = SFFindSlot(fv->b.sf,fv->b.map,home_char,NULL); if ( topchar==-1 ) { for ( topchar=0; topchar<fv->b.map->enccount; ++topchar ) if ( fv->b.map->map[topchar]!=-1 && fv->b.sf->glyphs[fv->b.map->map[topchar]]!=NULL ) break; if ( topchar==fv->b.map->enccount ) topchar = 0; } } if ( !event->u.resize.sized ) /* WM isn't responding to my resize requests, so no point in trying */; else if ( (event->u.resize.size.width- GDrawPointsToPixels(fv->gw,_GScrollBar_Width)-1)%fv->cbw!=0 || (event->u.resize.size.height-fv->mbh-fv->infoh-1)%fv->cbh!=0 ) { int cc = (event->u.resize.size.width+fv->cbw/2- GDrawPointsToPixels(fv->gw,_GScrollBar_Width)-1)/fv->cbw; int rc = (event->u.resize.size.height-fv->mbh-fv->infoh-1)/fv->cbh; if ( cc<=0 ) cc = 1; if ( rc<=0 ) rc = 1; GDrawGetSize(GDrawGetRoot(NULL),&screensize); if ( cc*fv->cbw+GDrawPointsToPixels(fv->gw,_GScrollBar_Width)>screensize.width ) --cc; if ( rc*fv->cbh+fv->mbh+fv->infoh+10>screensize.height ) --rc; GDrawResize(fv->gw, cc*fv->cbw+1+GDrawPointsToPixels(fv->gw,_GScrollBar_Width), rc*fv->cbh+1+fv->mbh+fv->infoh); /* somehow KDE loses this event of mine so to get even the vague effect */ /* we can't just return */ /*return;*/ } pos.width = GDrawPointsToPixels(fv->gw,_GScrollBar_Width); pos.height = event->u.resize.size.height-fv->mbh-fv->infoh; pos.x = event->u.resize.size.width-pos.width; pos.y = fv->mbh+fv->infoh; GGadgetResize(fv->vsb,pos.width,pos.height); GGadgetMove(fv->vsb,pos.x,pos.y); pos.width = pos.x; pos.x = 0; GDrawResize(fv->v,pos.width,pos.height); fv->width = pos.width; fv->height = pos.height; fv->colcnt = (fv->width-1)/fv->cbw; if ( fv->colcnt<1 ) fv->colcnt = 1; fv->rowcnt = (fv->height-1)/fv->cbh; if ( fv->rowcnt<1 ) fv->rowcnt = 1; fv->rowltot = (fv->b.map->enccount+fv->colcnt-1)/fv->colcnt; GScrollBarSetBounds(fv->vsb,0,fv->rowltot,fv->rowcnt); fv->rowoff = topchar/fv->colcnt; if ( fv->rowoff>=fv->rowltot-fv->rowcnt ) fv->rowoff = fv->rowltot-fv->rowcnt; if ( fv->rowoff<0 ) fv->rowoff =0; GScrollBarSetPos(fv->vsb,fv->rowoff); GDrawRequestExpose(fv->gw,NULL,true); GDrawRequestExpose(fv->v,NULL,true); if ( fv->rowcnt!=fv->b.sf->desired_row_cnt || fv->colcnt!=fv->b.sf->desired_col_cnt ) { default_fv_row_count = fv->rowcnt; default_fv_col_count = fv->colcnt; fv->b.sf->desired_row_cnt = fv->rowcnt; fv->b.sf->desired_col_cnt = fv->colcnt; SavePrefs(true); } } static void FVTimer(FontView *fv, GEvent *event) { if ( event->u.timer.timer==fv->pressed ) { GEvent e; GDrawGetPointerPosition(fv->v,&e); if ( e.u.mouse.y<0 || e.u.mouse.y >= fv->height ) { real dy = 0; if ( e.u.mouse.y<0 ) dy = -1; else if ( e.u.mouse.y>=fv->height ) dy = 1; if ( fv->rowoff+dy<0 ) dy = 0; else if ( fv->rowoff+dy+fv->rowcnt > fv->rowltot ) dy = 0; fv->rowoff += dy; if ( dy!=0 ) { GScrollBarSetPos(fv->vsb,fv->rowoff); GDrawScroll(fv->v,NULL,0,dy*fv->cbh); } } } else if ( event->u.timer.timer==fv->resize ) { /* It's a delayed resize event (for kde which sends continuous resizes) */ fv->resize = NULL; FVResize(fv,(GEvent *) (event->u.timer.userdata)); } else if ( event->u.timer.userdata!=NULL ) { /* It's a delayed function call */ void (*func)(FontView *) = (void (*)(FontView *)) (event->u.timer.userdata); func(fv); } } void FVDelay(FontView *fv,void (*func)(FontView *)) { GDrawRequestTimer(fv->v,100,0,(void *) func); } static int FVScroll(GGadget *g, GEvent *e) { FontView *fv = GGadgetGetUserData(g); int newpos = fv->rowoff; struct sbevent *sb = &e->u.control.u.sb; switch( sb->type ) { case et_sb_top: newpos = 0; break; case et_sb_uppage: newpos -= fv->rowcnt; break; case et_sb_up: --newpos; break; case et_sb_down: ++newpos; break; case et_sb_downpage: newpos += fv->rowcnt; break; case et_sb_bottom: newpos = fv->rowltot-fv->rowcnt; break; case et_sb_thumb: case et_sb_thumbrelease: newpos = sb->pos; break; } if ( newpos>fv->rowltot-fv->rowcnt ) newpos = fv->rowltot-fv->rowcnt; if ( newpos<0 ) newpos =0; if ( newpos!=fv->rowoff ) { int diff = newpos-fv->rowoff; fv->rowoff = newpos; GScrollBarSetPos(fv->vsb,fv->rowoff); GDrawScroll(fv->v,NULL,0,diff*fv->cbh); } return( true ); } static int v_e_h(GWindow gw, GEvent *event) { FontView *fv = (FontView *) GDrawGetUserData(gw); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(fv->vsb,event)); } GGadgetPopupExternalEvent(event); switch ( event->type ) { case et_expose: GDrawSetLineWidth(gw,0); FVExpose(fv,gw,event); break; case et_char: if ( fv->b.container!=NULL ) (fv->b.container->funcs->charEvent)(fv->b.container,event); else FVChar(fv,event); break; case et_mousemove: case et_mousedown: case et_mouseup: if ( event->type==et_mousedown ) GDrawSetGIC(gw,fv->gic,0,20); if ( fv->notactive && event->type==et_mousedown ) (fv->b.container->funcs->activateMe)(fv->b.container,&fv->b); FVMouse(fv,event); break; case et_timer: FVTimer(fv,event); break; case et_focus: // printf("fv.et_focus\n"); if ( event->u.focus.gained_focus ) GDrawSetGIC(gw,fv->gic,0,20); break; } return( true ); } static void FontView_ReformatOne(FontView *fv) { FontView *fvs; if ( fv->v==NULL || fv->colcnt==0 ) /* Can happen in scripts */ return; GDrawSetCursor(fv->v,ct_watch); fv->rowltot = (fv->b.map->enccount+fv->colcnt-1)/fv->colcnt; GScrollBarSetBounds(fv->vsb,0,fv->rowltot,fv->rowcnt); if ( fv->rowoff>fv->rowltot-fv->rowcnt ) { fv->rowoff = fv->rowltot-fv->rowcnt; if ( fv->rowoff<0 ) fv->rowoff =0; GScrollBarSetPos(fv->vsb,fv->rowoff); } for ( fvs=(FontView *) (fv->b.sf->fv); fvs!=NULL; fvs=(FontView *) (fvs->b.nextsame) ) if ( fvs!=fv && fvs->b.sf==fv->b.sf ) break; GDrawRequestExpose(fv->v,NULL,false); GDrawSetCursor(fv->v,ct_pointer); } static void FontView_ReformatAll(SplineFont *sf) { BDFFont *new, *old, *bdf; FontView *fv; MetricsView *mvs; extern int use_freetype_to_rasterize_fv; if ( sf->fv==NULL || ((FontView *) (sf->fv))->v==NULL || ((FontView *) (sf->fv))->colcnt==0 ) /* Can happen in scripts */ return; for ( fv=(FontView *) (sf->fv); fv!=NULL; fv=(FontView *) (fv->b.nextsame) ) { GDrawSetCursor(fv->v,ct_watch); old = fv->filled; /* In CID fonts fv->b.sf may not be same as sf */ new = SplineFontPieceMeal(fv->b.sf,fv->b.active_layer,fv->filled->pixelsize,72, (fv->antialias?pf_antialias:0)|(fv->bbsized?pf_bbsized:0)| (use_freetype_to_rasterize_fv && !sf->strokedfont && !sf->multilayer?pf_ft_nohints:0), NULL); fv->filled = new; if ( fv->show==old ) fv->show = new; else { for ( bdf=sf->bitmaps; bdf != NULL && ( bdf->pixelsize != fv->show->pixelsize || BDFDepth( bdf ) != BDFDepth( fv->show )); bdf=bdf->next ); if ( bdf != NULL ) fv->show = bdf; else fv->show = new; } BDFFontFree(old); fv->rowltot = (fv->b.map->enccount+fv->colcnt-1)/fv->colcnt; GScrollBarSetBounds(fv->vsb,0,fv->rowltot,fv->rowcnt); if ( fv->rowoff>fv->rowltot-fv->rowcnt ) { fv->rowoff = fv->rowltot-fv->rowcnt; if ( fv->rowoff<0 ) fv->rowoff =0; GScrollBarSetPos(fv->vsb,fv->rowoff); } GDrawRequestExpose(fv->v,NULL,false); GDrawSetCursor(fv->v,ct_pointer); } for ( mvs=sf->metrics; mvs!=NULL; mvs=mvs->next ) if ( mvs->bdf==NULL ) { BDFFontFree(mvs->show); mvs->show = SplineFontPieceMeal(sf,mvs->layer,mvs->ptsize,mvs->dpi, mvs->antialias?(pf_antialias|pf_ft_recontext):pf_ft_recontext,NULL); GDrawRequestExpose(mvs->gw,NULL,false); } } void FontViewRemove(FontView *fv) { if ( fv_list==fv ) fv_list = (FontView *) (fv->b.next); else { FontView *n; for ( n=fv_list; n->b.next!=&fv->b; n=(FontView *) (n->b.next) ); n->b.next = fv->b.next; } FontViewFree(&fv->b); } /** * In some cases fontview gets an et_selclear event when using copy * and paste on the OSX. So this guard lets us quietly ignore that * event when we have just done command+c or command+x. */ extern int osx_fontview_copy_cut_counter; static FontView* ActiveFontView = 0; static int fv_e_h(GWindow gw, GEvent *event) { FontView *fv = (FontView *) GDrawGetUserData(gw); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(fv->vsb,event)); } switch ( event->type ) { case et_focus: if ( event->u.focus.gained_focus ) { ActiveFontView = fv; } else { } break; case et_selclear: #ifdef __Mac // For some reason command + c and command + x wants // to send a clear to us, even if that key was pressed // on a charview. if( osx_fontview_copy_cut_counter ) { osx_fontview_copy_cut_counter--; break; } // printf("fontview et_selclear\n"); #endif ClipboardClear(); break; case et_expose: GDrawSetLineWidth(gw,0); FVDrawInfo(fv,gw,event); break; case et_resize: /* KDE sends a continuous stream of resize events, and gets very */ /* confused if I start resizing the window myself, try to wait for */ /* the user to finish before responding to resizes */ if ( event->u.resize.sized || fv->resize_expected ) { if ( fv->resize ) GDrawCancelTimer(fv->resize); fv->resize_event = *event; fv->resize = GDrawRequestTimer(fv->v,300,0,(void *) &fv->resize_event); fv->resize_expected = false; } break; case et_char: if ( fv->b.container!=NULL ) (fv->b.container->funcs->charEvent)(fv->b.container,event); else FVChar(fv,event); break; case et_mousedown: GDrawSetGIC(gw,fv->gwgic,0,20); if ( fv->notactive ) (fv->b.container->funcs->activateMe)(fv->b.container,&fv->b); break; case et_close: FVMenuClose(gw,NULL,NULL); break; case et_create: fv->b.next = (FontViewBase *) fv_list; fv_list = fv; break; case et_destroy: if ( fv->qg!=NULL ) QGRmFontView(fv->qg,fv); FontViewRemove(fv); break; } return( true ); } static void FontViewOpenKids(FontView *fv) { int k, i; SplineFont *sf = fv->b.sf, *_sf; #if defined(__Mac) int cnt= 0; #endif if ( sf->cidmaster!=NULL ) sf = sf->cidmaster; k=0; do { _sf = sf->subfontcnt==0 ? sf : sf->subfonts[k]; for ( i=0; i<_sf->glyphcnt; ++i ) if ( _sf->glyphs[i]!=NULL && _sf->glyphs[i]->wasopen ) { _sf->glyphs[i]->wasopen = false; #if defined(__Mac) /* If we open a bunch of charviews all at once on the mac, X11*/ /* crashes */ /* But opening one seems ok */ if ( ++cnt==1 ) #endif CharViewCreate(_sf->glyphs[i],fv,-1); } ++k; } while ( k<sf->subfontcnt ); } static FontView *__FontViewCreate(SplineFont *sf) { FontView *fv = calloc(1,sizeof(FontView)); int i; int ps = sf->display_size<0 ? -sf->display_size : sf->display_size==0 ? default_fv_font_size : sf->display_size; if ( ps>200 ) ps = 128; /* Filename != NULL if we opened an sfd file. Sfd files know whether */ /* the font is compact or not and should not depend on a global flag */ /* If a font is new, then compaction will make it vanish completely */ if ( sf->fv==NULL && compact_font_on_open && sf->filename==NULL && !sf->new ) { sf->compacted = true; for ( i=0; i<sf->subfontcnt; ++i ) sf->subfonts[i]->compacted = true; } fv->b.nextsame = sf->fv; fv->b.active_layer = sf->display_layer; sf->fv = (FontViewBase *) fv; if ( sf->mm!=NULL ) { sf->mm->normal->fv = (FontViewBase *) fv; for ( i = 0; i<sf->mm->instance_count; ++i ) sf->mm->instances[i]->fv = (FontViewBase *) fv; } if ( sf->subfontcnt==0 ) { fv->b.sf = sf; if ( fv->b.nextsame!=NULL ) { fv->b.map = EncMapCopy(fv->b.nextsame->map); fv->b.normal = fv->b.nextsame->normal==NULL ? NULL : EncMapCopy(fv->b.nextsame->normal); } else if ( sf->compacted ) { fv->b.normal = sf->map; fv->b.map = CompactEncMap(EncMapCopy(sf->map),sf); sf->map = fv->b.map; } else { fv->b.map = sf->map; fv->b.normal = NULL; } } else { fv->b.cidmaster = sf; for ( i=0; i<sf->subfontcnt; ++i ) sf->subfonts[i]->fv = (FontViewBase *) fv; for ( i=0; i<sf->subfontcnt; ++i ) /* Search for a subfont that contains more than ".notdef" (most significant in .gai fonts) */ if ( sf->subfonts[i]->glyphcnt>1 ) { fv->b.sf = sf->subfonts[i]; break; } if ( fv->b.sf==NULL ) fv->b.sf = sf->subfonts[0]; sf = fv->b.sf; if ( fv->b.nextsame==NULL ) { EncMapFree(sf->map); sf->map = NULL; } fv->b.map = EncMap1to1(sf->glyphcnt); if ( fv->b.nextsame==NULL ) { sf->map = fv->b.map; } if ( sf->compacted ) { fv->b.normal = fv->b.map; fv->b.map = CompactEncMap(EncMapCopy(fv->b.map),sf); if ( fv->b.nextsame==NULL ) { sf->map = fv->b.map; } } } fv->b.selected = calloc((fv->b.map ? fv->b.map->enccount : 0), sizeof(char)); fv->user_requested_magnify = -1; fv->magnify = (ps<=9)? 3 : (ps<20) ? 2 : 1; fv->cbw = (ps*fv->magnify)+1; fv->cbh = (ps*fv->magnify)+1+fv->lab_height+1; fv->antialias = sf->display_antialias; fv->bbsized = sf->display_bbsized; fv->glyphlabel = default_fv_glyphlabel; fv->end_pos = -1; #ifndef _NO_PYTHON PyFF_InitFontHook((FontViewBase *)fv); #endif fv->pid_webfontserver = 0; return( fv ); } static int fontview_ready = false; static void FontViewFinish() { if (!fontview_ready) return; mb2FreeGetText(mblist); mbFreeGetText(fvpopupmenu); } void FontViewFinishNonStatic() { FontViewFinish(); } static void FontViewInit(void) { // static int done = false; // superseded by fontview_ready. if ( fontview_ready ) return; fontview_ready = true; mb2DoGetText(mblist); mbDoGetText(fvpopupmenu); atexit(&FontViewFinishNonStatic); } static struct resed fontview_re[] = { {N_("Glyph Info Color"), "GlyphInfoColor", rt_color, &fvglyphinfocol, N_("Color of the font used to display glyph information in the fontview"), NULL, { 0 }, 0, 0 }, {N_("Empty Slot FG Color"), "EmptySlotFgColor", rt_color, &fvemtpyslotfgcol, N_("Color used to draw the foreground of empty slots"), NULL, { 0 }, 0, 0 }, {N_("Selected BG Color"), "SelectedColor", rt_color, &fvselcol, N_("Color used to draw the background of selected glyphs"), NULL, { 0 }, 0, 0 }, {N_("Selected FG Color"), "SelectedFgColor", rt_color, &fvselfgcol, N_("Color used to draw the foreground of selected glyphs"), NULL, { 0 }, 0, 0 }, {N_("Changed Color"), "ChangedColor", rt_color, &fvchangedcol, N_("Color used to mark a changed glyph"), NULL, { 0 }, 0, 0 }, {N_("Hinting Needed Color"), "HintingNeededColor", rt_color, &fvhintingneededcol, N_("Color used to mark glyphs that need hinting"), NULL, { 0 }, 0, 0 }, {N_("Font Size"), "FontSize", rt_int, &fv_fontsize, N_("Size (in points) of the font used to display information and glyph labels in the fontview"), NULL, { 0 }, 0, 0 }, {N_("Font Family"), "FontFamily", rt_stringlong, &fv_fontnames, N_("A comma separated list of font family names used to display small example images of glyphs over the user designed glyphs"), NULL, { 0 }, 0, 0 }, RESED_EMPTY }; static void FVCreateInnards(FontView *fv,GRect *pos) { GWindow gw = fv->gw; GWindowAttrs wattrs; GGadgetData gd; FontRequest rq; BDFFont *bdf; int as,ds,ld; extern int use_freetype_to_rasterize_fv; SplineFont *sf = fv->b.sf; fv->lab_height = FV_LAB_HEIGHT-13+GDrawPointsToPixels(NULL,fv_fontsize); memset(&gd,0,sizeof(gd)); gd.pos.y = pos->y; gd.pos.height = pos->height; gd.pos.width = GDrawPointsToPixels(gw,_GScrollBar_Width); gd.pos.x = pos->width; gd.u.sbinit = NULL; gd.flags = gg_visible|gg_enabled|gg_pos_in_pixels|gg_sb_vert; gd.handle_controlevent = FVScroll; fv->vsb = GScrollBarCreate(gw,&gd,fv); memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_backcol; wattrs.event_masks = ~(1<<et_charup); wattrs.cursor = ct_pointer; wattrs.background_color = view_bgcol; fv->v = GWidgetCreateSubWindow(gw,pos,v_e_h,fv,&wattrs); GDrawSetVisible(fv->v,true); GDrawSetWindowTypeName(fv->v, "FontView"); fv->gic = GDrawCreateInputContext(fv->v,gic_root|gic_orlesser); fv->gwgic = GDrawCreateInputContext(fv->gw,gic_root|gic_orlesser); GDrawSetGIC(fv->v,fv->gic,0,20); GDrawSetGIC(fv->gw,fv->gic,0,20); fv->fontset = calloc(_uni_fontmax,sizeof(GFont *)); memset(&rq,0,sizeof(rq)); rq.utf8_family_name = fv_fontnames; rq.point_size = fv_fontsize; rq.weight = 400; fv->fontset[0] = GDrawInstanciateFont(gw,&rq); GDrawSetFont(fv->v,fv->fontset[0]); GDrawWindowFontMetrics(fv->v,fv->fontset[0],&as,&ds,&ld); fv->lab_as = as; fv->showhmetrics = default_fv_showhmetrics; fv->showvmetrics = default_fv_showvmetrics && sf->hasvmetrics; bdf = SplineFontPieceMeal(fv->b.sf,fv->b.active_layer,sf->display_size<0?-sf->display_size:default_fv_font_size,72, (fv->antialias?pf_antialias:0)|(fv->bbsized?pf_bbsized:0)| (use_freetype_to_rasterize_fv && !sf->strokedfont && !sf->multilayer?pf_ft_nohints:0), NULL); fv->filled = bdf; if ( sf->display_size>0 ) { for ( bdf=sf->bitmaps; bdf!=NULL && bdf->pixelsize!=sf->display_size ; bdf=bdf->next ); if ( bdf==NULL ) bdf = fv->filled; } if ( sf->onlybitmaps && bdf==fv->filled && sf->bitmaps!=NULL ) bdf = sf->bitmaps; fv->cbw = -1; FVChangeDisplayFont(fv,bdf); } static FontView *FontView_Create(SplineFont *sf, int hide) { FontView *fv = (FontView *) __FontViewCreate(sf); GRect pos; GWindow gw; GWindowAttrs wattrs; GGadgetData gd; GRect gsize; static GWindow icon = NULL; static int nexty=0; GRect size; FontViewInit(); if ( icon==NULL ) { #ifdef BIGICONS icon = GDrawCreateBitmap(NULL,fontview_width,fontview_height,fontview_bits); #else icon = GDrawCreateBitmap(NULL,fontview2_width,fontview2_height,fontview2_bits); #endif } GDrawGetSize(GDrawGetRoot(NULL),&size); memset(&wattrs,0,sizeof(wattrs)); wattrs.mask = wam_events|wam_cursor|wam_icon; wattrs.event_masks = ~(1<<et_charup); wattrs.cursor = ct_pointer; wattrs.icon = icon; pos.width = sf->desired_col_cnt*fv->cbw+1; pos.height = sf->desired_row_cnt*fv->cbh+1; pos.x = size.width-pos.width-30; pos.y = nexty; nexty += 2*fv->cbh+50; if ( nexty+pos.height > size.height ) nexty = 0; fv->gw = gw = GDrawCreateTopWindow(NULL,&pos,fv_e_h,fv,&wattrs); FontViewSetTitle(fv); GDrawSetWindowTypeName(fv->gw, "FontView"); if ( !fv_fs_init ) { GResEditFind( fontview_re, "FontView."); view_bgcol = GResourceFindColor("View.Background",GDrawGetDefaultBackground(NULL)); fv_fs_init = true; } memset(&gd,0,sizeof(gd)); gd.flags = gg_visible | gg_enabled; helplist[0].invoke = FVMenuContextualHelp; #ifndef _NO_PYTHON if ( fvpy_menu!=NULL ) mblist[3].ti.disabled = false; mblist[3].sub = fvpy_menu; #define CALLBACKS_INDEX 4 /* FIXME: There has to be a better way than this. */ #else #define CALLBACKS_INDEX 3 /* FIXME: There has to be a better way than this. */ #endif /* _NO_PYTHON */ #ifdef NATIVE_CALLBACKS if ( fv_menu!=NULL ) mblist[CALLBACKS_INDEX].ti.disabled = false; mblist[CALLBACKS_INDEX].sub = fv_menu; #endif /* NATIVE_CALLBACKS */ gd.u.menu2 = mblist; fv->mb = GMenu2BarCreate( gw, &gd, NULL); GGadgetGetSize(fv->mb,&gsize); fv->mbh = gsize.height; fv->infoh = 1+GDrawPointsToPixels(NULL,fv_fontsize); pos.x = 0; pos.y = fv->mbh+fv->infoh; FVCreateInnards(fv,&pos); if ( !hide ) { GDrawSetVisible(gw,true); FontViewOpenKids(fv); } return( fv ); } static FontView *FontView_Append(FontView *fv) { /* Normally fontviews get added to the fv list when their windows are */ /* created. but we don't create any windows here, so... */ FontView *test; if ( fv_list==NULL ) fv_list = fv; else { for ( test = fv_list; test->b.next!=NULL; test=(FontView *) test->b.next ); test->b.next = (FontViewBase *) fv; } return( fv ); } FontView *FontNew(void) { return( FontView_Create(SplineFontNew(),false)); } static void FontView_Free(FontView *fv) { int i; FontView *prev; FontView *fvs; if ( fv->b.sf == NULL ) /* Happens when usurping a font to put it into an MM */ BDFFontFree(fv->filled); else if ( fv->b.nextsame==NULL && fv->b.sf->fv==&fv->b ) { EncMapFree(fv->b.map); if (fv->b.sf != NULL && fv->b.map == fv->b.sf->map) { fv->b.sf->map = NULL; } SplineFontFree(fv->b.cidmaster?fv->b.cidmaster:fv->b.sf); BDFFontFree(fv->filled); } else { EncMapFree(fv->b.map); if (fv->b.sf != NULL && fv->b.map == fv->b.sf->map) { fv->b.sf->map = NULL; } fv->b.map = NULL; for ( fvs=(FontView *) (fv->b.sf->fv), i=0 ; fvs!=NULL; fvs = (FontView *) (fvs->b.nextsame) ) if ( fvs->filled==fv->filled ) ++i; if ( i==1 ) BDFFontFree(fv->filled); if ( fv->b.sf->fv==&fv->b ) { if ( fv->b.cidmaster==NULL ) fv->b.sf->fv = fv->b.nextsame; else { fv->b.cidmaster->fv = fv->b.nextsame; for ( i=0; i<fv->b.cidmaster->subfontcnt; ++i ) fv->b.cidmaster->subfonts[i]->fv = fv->b.nextsame; } } else { for ( prev = (FontView *) (fv->b.sf->fv); prev->b.nextsame!=&fv->b; prev=(FontView *) (prev->b.nextsame) ); prev->b.nextsame = fv->b.nextsame; } } #ifndef _NO_FFSCRIPT DictionaryFree(fv->b.fontvars); free(fv->b.fontvars); #endif free(fv->b.selected); free(fv->fontset); #ifndef _NO_PYTHON PyFF_FreeFV(&fv->b); #endif free(fv); } static int FontViewWinInfo(FontView *fv, int *cc, int *rc) { if ( fv==NULL || fv->colcnt==0 || fv->rowcnt==0 ) { *cc = 16; *rc = 4; return( -1 ); } *cc = fv->colcnt; *rc = fv->rowcnt; return( fv->rowoff*fv->colcnt ); } static FontViewBase *FVAny(void) { return (FontViewBase *) fv_list; } static int FontIsActive(SplineFont *sf) { FontView *fv; for ( fv=fv_list; fv!=NULL; fv=(FontView *) (fv->b.next) ) if ( fv->b.sf == sf ) return( true ); return( false ); } static SplineFont *FontOfFilename(const char *filename) { char buffer[1025]; FontView *fv; GFileGetAbsoluteName((char *) filename,buffer,sizeof(buffer)); for ( fv=fv_list; fv!=NULL ; fv=(FontView *) (fv->b.next) ) { if ( fv->b.sf->filename!=NULL && strcmp(fv->b.sf->filename,buffer)==0 ) return( fv->b.sf ); else if ( fv->b.sf->origname!=NULL && strcmp(fv->b.sf->origname,buffer)==0 ) return( fv->b.sf ); } return( NULL ); } static void FVExtraEncSlots(FontView *fv, int encmax) { if ( fv->colcnt!=0 ) { /* Ie. scripting vs. UI */ fv->rowltot = (encmax+1+fv->colcnt-1)/fv->colcnt; GScrollBarSetBounds(fv->vsb,0,fv->rowltot,fv->rowcnt); } } static void FV_BiggerGlyphCache(FontView *fv, int gidcnt) { if ( fv->filled!=NULL ) BDFOrigFixup(fv->filled,gidcnt,fv->b.sf); } static void FontView_Close(FontView *fv) { if ( fv->gw!=NULL ) GDrawDestroyWindow(fv->gw); else FontViewRemove(fv); } struct fv_interface gdraw_fv_interface = { (FontViewBase *(*)(SplineFont *, int)) FontView_Create, (FontViewBase *(*)(SplineFont *)) __FontViewCreate, (void (*)(FontViewBase *)) FontView_Close, (void (*)(FontViewBase *)) FontView_Free, (void (*)(FontViewBase *)) FontViewSetTitle, FontViewSetTitles, FontViewRefreshAll, (void (*)(FontViewBase *)) FontView_ReformatOne, FontView_ReformatAll, (void (*)(FontViewBase *)) FV_LayerChanged, FV_ToggleCharChanged, (int (*)(FontViewBase *, int *, int *)) FontViewWinInfo, FontIsActive, FVAny, (FontViewBase *(*)(FontViewBase *)) FontView_Append, FontOfFilename, (void (*)(FontViewBase *,int)) FVExtraEncSlots, (void (*)(FontViewBase *,int)) FV_BiggerGlyphCache, (void (*)(FontViewBase *,BDFFont *)) FV_ChangeDisplayBitmap, (void (*)(FontViewBase *)) FV_ShowFilled, FV_ReattachCVs, (void (*)(FontViewBase *)) FVDeselectAll, (void (*)(FontViewBase *,int )) FVScrollToGID, (void (*)(FontViewBase *,int )) FVScrollToChar, (void (*)(FontViewBase *,int )) FV_ChangeGID, SF_CloseAllInstrs }; extern GResInfo charview_ri; static struct resed view_re[] = { {N_("Color|Background"), "Background", rt_color, &view_bgcol, N_("Background color for the drawing area of all views"), NULL, { 0 }, 0, 0 }, RESED_EMPTY }; GResInfo view_ri = { NULL, NULL,NULL, NULL, NULL, NULL, NULL, view_re, N_("View"), N_("This is an abstract class which defines common features of the\nFontView, CharView, BitmapView and MetricsView"), "View", "fontforge", false, 0, NULL, GBOX_EMPTY, NULL, NULL, NULL }; GResInfo fontview_ri = { &charview_ri, NULL,NULL, NULL, NULL, NULL, NULL, fontview_re, N_("FontView"), N_("This is the main fontforge window displaying a font"), "FontView", "fontforge", false, 0, NULL, GBOX_EMPTY, NULL, NULL, NULL }; /* ************************************************************************** */ /* ***************************** Embedded FontViews ************************* */ /* ************************************************************************** */ static void FVCopyInnards(FontView *fv,GRect *pos,int infoh, FontView *fvorig,GWindow dw, int def_layer, struct fvcontainer *kf) { fv->notactive = true; fv->gw = dw; fv->infoh = infoh; fv->b.container = kf; fv->rowcnt = 4; fv->colcnt = 16; fv->b.active_layer = def_layer; FVCreateInnards(fv,pos); memcpy(fv->b.selected,fvorig->b.selected,fv->b.map->enccount); fv->rowoff = (fvorig->rowoff*fvorig->colcnt)/fv->colcnt; } void KFFontViewInits(struct kf_dlg *kf,GGadget *drawable) { GGadgetData gd; GRect pos, gsize, sbsize; GWindow dw = GDrawableGetWindow(drawable); int infoh; int ps; FontView *fvorig = (FontView *) kf->sf->fv; FontViewInit(); kf->dw = dw; memset(&gd,0,sizeof(gd)); gd.flags = gg_visible | gg_enabled; helplist[0].invoke = FVMenuContextualHelp; gd.u.menu2 = mblist; kf->mb = GMenu2BarCreate( dw, &gd, NULL); GGadgetGetSize(kf->mb,&gsize); kf->mbh = gsize.height; kf->guts = drawable; ps = kf->sf->display_size; kf->sf->display_size = -24; kf->first_fv = __FontViewCreate(kf->sf); kf->first_fv->b.container = (struct fvcontainer *) kf; kf->second_fv = __FontViewCreate(kf->sf); kf->second_fv->b.container = (struct fvcontainer *) kf; kf->infoh = infoh = 1+GDrawPointsToPixels(NULL,fv_fontsize); kf->first_fv->mbh = kf->mbh; pos.x = 0; pos.y = kf->mbh+infoh+kf->fh+4; pos.width = 16*kf->first_fv->cbw+1; pos.height = 4*kf->first_fv->cbh+1; GDrawSetUserData(dw,kf->first_fv); FVCopyInnards(kf->first_fv,&pos,infoh,fvorig,dw,kf->def_layer,(struct fvcontainer *) kf); pos.height = 4*kf->first_fv->cbh+1; /* We don't know the real fv->cbh until after creating the innards. The size of the last window is probably wrong, we'll fix later */ kf->second_fv->mbh = kf->mbh; kf->label2_y = pos.y + pos.height+2; pos.y = kf->label2_y + kf->fh + 2; GDrawSetUserData(dw,kf->second_fv); FVCopyInnards(kf->second_fv,&pos,infoh,fvorig,dw,kf->def_layer,(struct fvcontainer *) kf); kf->sf->display_size = ps; GGadgetGetSize(kf->second_fv->vsb,&sbsize); gsize.x = gsize.y = 0; gsize.width = pos.width + sbsize.width; gsize.height = pos.y+pos.height; GGadgetSetDesiredSize(drawable,NULL,&gsize); } /* ************************************************************************** */ /* ************************** Glyph Set from Selection ********************** */ /* ************************************************************************** */ struct gsd { struct fvcontainer base; FontView *fv; int done; int good; GWindow gw; }; static void gs_activateMe(struct fvcontainer *UNUSED(fvc), FontViewBase *UNUSED(fvb)) { /*struct gsd *gs = (struct gsd *) fvc;*/ } static void gs_charEvent(struct fvcontainer *fvc,void *event) { struct gsd *gs = (struct gsd *) fvc; FVChar(gs->fv,event); } static void gs_doClose(struct fvcontainer *fvc) { struct gsd *gs = (struct gsd *) fvc; gs->done = true; } #define CID_Guts 1000 #define CID_TopBox 1001 static void gs_doResize(struct fvcontainer *fvc, FontViewBase *UNUSED(fvb), int width, int height) { struct gsd *gs = (struct gsd *) fvc; /*FontView *fv = (FontView *) fvb;*/ GRect size; memset(&size,0,sizeof(size)); size.width = width; size.height = height; GGadgetSetDesiredSize(GWidgetGetControl(gs->gw,CID_Guts), NULL,&size); GHVBoxFitWindow(GWidgetGetControl(gs->gw,CID_TopBox)); } static struct fvcontainer_funcs glyphset_funcs = { fvc_glyphset, true, /* Modal dialog. No charviews, etc. */ gs_activateMe, gs_charEvent, gs_doClose, gs_doResize }; static int GS_OK(GGadget *g, GEvent *e) { if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { struct gsd *gs = GDrawGetUserData(GGadgetGetWindow(g)); gs->done = true; gs->good = true; } return( true ); } static int GS_Cancel(GGadget *g, GEvent *e) { struct gsd *gs; if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) { gs = GDrawGetUserData(GGadgetGetWindow(g)); gs->done = true; } return( true ); } static void gs_sizeSet(struct gsd *gs,GWindow dw) { GRect size, gsize; int width, height, y; int cc, rc, topchar; GRect subsize; FontView *fv = gs->fv; if ( gs->fv->vsb==NULL ) return; GDrawGetSize(dw,&size); GGadgetGetSize(gs->fv->vsb,&gsize); width = size.width - gsize.width; height = size.height - gs->fv->mbh - gs->fv->infoh; y = gs->fv->mbh + gs->fv->infoh; topchar = fv->rowoff*fv->colcnt; cc = (width-1) / fv->cbw; if ( cc<1 ) cc=1; rc = (height-1)/ fv->cbh; if ( rc<1 ) rc = 1; subsize.x = 0; subsize.y = 0; subsize.width = cc*fv->cbw + 1; subsize.height = rc*fv->cbh + 1; GDrawResize(fv->v,subsize.width,subsize.height); GDrawMove(fv->v,0,y); GGadgetMove(fv->vsb,subsize.width,y); GGadgetResize(fv->vsb,gsize.width,subsize.height); fv->colcnt = cc; fv->rowcnt = rc; fv->width = subsize.width; fv->height = subsize.height; fv->rowltot = (fv->b.map->enccount+fv->colcnt-1)/fv->colcnt; GScrollBarSetBounds(fv->vsb,0,fv->rowltot,fv->rowcnt); fv->rowoff = topchar/fv->colcnt; if ( fv->rowoff>=fv->rowltot-fv->rowcnt ) fv->rowoff = fv->rowltot-fv->rowcnt; if ( fv->rowoff<0 ) fv->rowoff =0; GScrollBarSetPos(fv->vsb,fv->rowoff); GDrawRequestExpose(fv->v,NULL,true); } static int gs_sub_e_h(GWindow pixmap, GEvent *event) { FontView *active_fv; struct gsd *gs; if ( event->type==et_destroy ) return( true ); active_fv = (FontView *) GDrawGetUserData(pixmap); gs = (struct gsd *) (active_fv->b.container); if (( event->type==et_mouseup || event->type==et_mousedown ) && (event->u.mouse.button>=4 && event->u.mouse.button<=7) ) { return( GGadgetDispatchEvent(active_fv->vsb,event)); } switch ( event->type ) { case et_expose: FVDrawInfo(active_fv,pixmap,event); break; case et_char: gs_charEvent(&gs->base,event); break; case et_mousedown: return(false); break; case et_mouseup: case et_mousemove: return(false); case et_resize: gs_sizeSet(gs,pixmap); break; } return( true ); } static int gs_e_h(GWindow gw, GEvent *event) { struct gsd *gs = GDrawGetUserData(gw); switch ( event->type ) { case et_close: gs->done = true; break; case et_char: FVChar(gs->fv,event); break; } return( true ); } char *GlyphSetFromSelection(SplineFont *sf,int def_layer,char *current) { struct gsd gs; GRect pos; GWindowAttrs wattrs; GGadgetCreateData gcd[5], boxes[3]; GGadgetCreateData *varray[21], *buttonarray[8]; GTextInfo label[5]; int i,j,k,guts_row,gid,enc,len; char *ret, *rpt; SplineChar *sc; GGadget *drawable; GWindow dw; GGadgetData gd; GRect gsize, sbsize; int infoh, mbh; int ps; FontView *fvorig = (FontView *) sf->fv; GGadget *mb; char *start, *pt; int ch; FontViewInit(); memset(&wattrs,0,sizeof(wattrs)); memset(&gcd,0,sizeof(gcd)); memset(&boxes,0,sizeof(boxes)); memset(&label,0,sizeof(label)); memset(&gs,0,sizeof(gs)); gs.base.funcs = &glyphset_funcs; wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict; wattrs.event_masks = ~(1<<et_charup); wattrs.restrict_input_to_me = true; wattrs.undercursor = 1; wattrs.cursor = ct_pointer; wattrs.utf8_window_title = _("Glyph Set by Selection") ; wattrs.is_dlg = true; pos.x = pos.y = 0; pos.width = 100; pos.height = 100; gs.gw = GDrawCreateTopWindow(NULL,&pos,gs_e_h,&gs,&wattrs); i = j = 0; guts_row = j/2; gcd[i].gd.flags = gg_enabled|gg_visible; gcd[i].gd.cid = CID_Guts; gcd[i].gd.u.drawable_e_h = gs_sub_e_h; gcd[i].creator = GDrawableCreate; varray[j++] = &gcd[i++]; varray[j++] = NULL; label[i].text = (unichar_t *) _("Select glyphs in the font view above.\nThe selected glyphs become your glyph class."); label[i].text_is_1byte = true; gcd[i].gd.label = &label[i]; gcd[i].gd.flags = gg_enabled|gg_visible; gcd[i].creator = GLabelCreate; varray[j++] = &gcd[i++]; varray[j++] = NULL; gcd[i].gd.flags = gg_visible | gg_enabled | gg_but_default; label[i].text = (unichar_t *) _("_OK"); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.label = &label[i]; gcd[i].gd.handle_controlevent = GS_OK; gcd[i++].creator = GButtonCreate; gcd[i].gd.flags = gg_visible | gg_enabled | gg_but_cancel; label[i].text = (unichar_t *) _("_Cancel"); label[i].text_is_1byte = true; label[i].text_in_resource = true; gcd[i].gd.label = &label[i]; gcd[i].gd.handle_controlevent = GS_Cancel; gcd[i++].creator = GButtonCreate; buttonarray[0] = GCD_Glue; buttonarray[1] = &gcd[i-2]; buttonarray[2] = GCD_Glue; buttonarray[3] = GCD_Glue; buttonarray[4] = &gcd[i-1]; buttonarray[5] = GCD_Glue; buttonarray[6] = NULL; boxes[2].gd.flags = gg_enabled|gg_visible; boxes[2].gd.u.boxelements = buttonarray; boxes[2].creator = GHBoxCreate; varray[j++] = &boxes[2]; varray[j++] = NULL; varray[j++] = NULL; boxes[0].gd.pos.x = boxes[0].gd.pos.y = 2; boxes[0].gd.flags = gg_enabled|gg_visible; boxes[0].gd.u.boxelements = varray; boxes[0].gd.cid = CID_TopBox; boxes[0].creator = GHVGroupCreate; GGadgetsCreate(gs.gw,boxes); GHVBoxSetExpandableRow(boxes[0].ret,guts_row); GHVBoxSetExpandableCol(boxes[2].ret,gb_expandgluesame); drawable = GWidgetGetControl(gs.gw,CID_Guts); dw = GDrawableGetWindow(drawable); memset(&gd,0,sizeof(gd)); gd.flags = gg_visible | gg_enabled; helplist[0].invoke = FVMenuContextualHelp; gd.u.menu2 = mblist; mb = GMenu2BarCreate( dw, &gd, NULL); GGadgetGetSize(mb,&gsize); mbh = gsize.height; ps = sf->display_size; sf->display_size = -24; gs.fv = __FontViewCreate(sf); infoh = 1+GDrawPointsToPixels(NULL,fv_fontsize); gs.fv->mbh = mbh; pos.x = 0; pos.y = mbh+infoh; pos.width = 16*gs.fv->cbw+1; pos.height = 4*gs.fv->cbh+1; GDrawSetUserData(dw,gs.fv); FVCopyInnards(gs.fv,&pos,infoh,fvorig,dw,def_layer,(struct fvcontainer *) &gs); pos.height = 4*gs.fv->cbh+1; /* We don't know the real fv->cbh until after creating the innards. The size of the last window is probably wrong, we'll fix later */ memset(gs.fv->b.selected,0,gs.fv->b.map->enccount); if ( current!=NULL && strcmp(current,_("{Everything Else}"))!=0 ) { int first = true; for ( start = current; *start==' '; ++start ); while ( *start ) { for ( pt=start; *pt!='\0' && *pt!=' '; ++pt ); ch = *pt; *pt='\0'; sc = SFGetChar(sf,-1,start); *pt = ch; if ( sc!=NULL && (enc = gs.fv->b.map->backmap[sc->orig_pos])!=-1 ) { gs.fv->b.selected[enc] = true; if ( first ) { first = false; gs.fv->rowoff = enc/gs.fv->colcnt; } } start = pt; while ( *start==' ' ) ++start; } } sf->display_size = ps; GGadgetGetSize(gs.fv->vsb,&sbsize); gsize.x = gsize.y = 0; gsize.width = pos.width + sbsize.width; gsize.height = pos.y+pos.height; GGadgetSetDesiredSize(drawable,NULL,&gsize); GHVBoxFitWindow(boxes[0].ret); GDrawSetVisible(gs.gw,true); while ( !gs.done ) GDrawProcessOneEvent(NULL); ret = rpt = NULL; if ( gs.good ) { for ( k=0; k<2; ++k ) { len = 0; for ( enc=0; enc<gs.fv->b.map->enccount; ++enc ) { if ( gs.fv->b.selected[enc] && (gid=gs.fv->b.map->map[enc])!=-1 && (sc = sf->glyphs[gid])!=NULL ) { char *repr = SCNameUniStr( sc ); if ( ret==NULL ) len += strlen(repr)+2; else { strcpy(rpt,repr); rpt += strlen( repr ); free(repr); *rpt++ = ' '; } } } if ( k==0 ) ret = rpt = malloc(len+1); else if ( rpt!=ret && rpt[-1]==' ' ) rpt[-1]='\0'; else *rpt='\0'; } } FontViewFree(&gs.fv->b); GDrawSetUserData(gs.gw,NULL); GDrawSetUserData(dw,NULL); GDrawDestroyWindow(gs.gw); return( ret ); } /* local variables: */ /* tab-width: 8 */ /* end: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_1050_1
crossvul-cpp_data_bad_2131_1
/* * HID driver for Kye/Genius devices not fully compliant with HID standard * * Copyright (c) 2009 Jiri Kosina * Copyright (c) 2009 Tomas Hanak * Copyright (c) 2012 Nikolai Kondrashov */ /* * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "hid-ids.h" /* * See EasyPen i405X description, device and HID report descriptors at * http://sf.net/apps/mediawiki/digimend/?title=KYE_EasyPen_i405X */ /* Original EasyPen i405X report descriptor size */ #define EASYPEN_I405X_RDESC_ORIG_SIZE 476 /* Fixed EasyPen i405X report descriptor */ static __u8 easypen_i405x_rdesc_fixed[] = { 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x01, /* Usage (01h), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x05, /* Report ID (5), */ 0x09, 0x01, /* Usage (01h), */ 0x15, 0x80, /* Logical Minimum (-128), */ 0x25, 0x7F, /* Logical Maximum (127), */ 0x75, 0x08, /* Report Size (8), */ 0x95, 0x07, /* Report Count (7), */ 0xB1, 0x02, /* Feature (Variable), */ 0xC0, /* End Collection, */ 0x05, 0x0D, /* Usage Page (Digitizer), */ 0x09, 0x02, /* Usage (Pen), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x10, /* Report ID (16), */ 0x09, 0x20, /* Usage (Stylus), */ 0xA0, /* Collection (Physical), */ 0x14, /* Logical Minimum (0), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x75, 0x01, /* Report Size (1), */ 0x09, 0x42, /* Usage (Tip Switch), */ 0x09, 0x44, /* Usage (Barrel Switch), */ 0x09, 0x46, /* Usage (Tablet Pick), */ 0x95, 0x03, /* Report Count (3), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x04, /* Report Count (4), */ 0x81, 0x03, /* Input (Constant, Variable), */ 0x09, 0x32, /* Usage (In Range), */ 0x95, 0x01, /* Report Count (1), */ 0x81, 0x02, /* Input (Variable), */ 0x75, 0x10, /* Report Size (16), */ 0x95, 0x01, /* Report Count (1), */ 0xA4, /* Push, */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x55, 0xFD, /* Unit Exponent (-3), */ 0x65, 0x13, /* Unit (Inch), */ 0x34, /* Physical Minimum (0), */ 0x09, 0x30, /* Usage (X), */ 0x46, 0x7C, 0x15, /* Physical Maximum (5500), */ 0x26, 0x00, 0x37, /* Logical Maximum (14080), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x31, /* Usage (Y), */ 0x46, 0xA0, 0x0F, /* Physical Maximum (4000), */ 0x26, 0x00, 0x28, /* Logical Maximum (10240), */ 0x81, 0x02, /* Input (Variable), */ 0xB4, /* Pop, */ 0x09, 0x30, /* Usage (Tip Pressure), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; /* * See MousePen i608X description, device and HID report descriptors at * http://sf.net/apps/mediawiki/digimend/?title=KYE_MousePen_i608X */ /* Original MousePen i608X report descriptor size */ #define MOUSEPEN_I608X_RDESC_ORIG_SIZE 476 /* Fixed MousePen i608X report descriptor */ static __u8 mousepen_i608x_rdesc_fixed[] = { 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x01, /* Usage (01h), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x05, /* Report ID (5), */ 0x09, 0x01, /* Usage (01h), */ 0x15, 0x80, /* Logical Minimum (-128), */ 0x25, 0x7F, /* Logical Maximum (127), */ 0x75, 0x08, /* Report Size (8), */ 0x95, 0x07, /* Report Count (7), */ 0xB1, 0x02, /* Feature (Variable), */ 0xC0, /* End Collection, */ 0x05, 0x0D, /* Usage Page (Digitizer), */ 0x09, 0x02, /* Usage (Pen), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x10, /* Report ID (16), */ 0x09, 0x20, /* Usage (Stylus), */ 0xA0, /* Collection (Physical), */ 0x14, /* Logical Minimum (0), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x75, 0x01, /* Report Size (1), */ 0x09, 0x42, /* Usage (Tip Switch), */ 0x09, 0x44, /* Usage (Barrel Switch), */ 0x09, 0x46, /* Usage (Tablet Pick), */ 0x95, 0x03, /* Report Count (3), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x04, /* Report Count (4), */ 0x81, 0x03, /* Input (Constant, Variable), */ 0x09, 0x32, /* Usage (In Range), */ 0x95, 0x01, /* Report Count (1), */ 0x81, 0x02, /* Input (Variable), */ 0x75, 0x10, /* Report Size (16), */ 0x95, 0x01, /* Report Count (1), */ 0xA4, /* Push, */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x55, 0xFD, /* Unit Exponent (-3), */ 0x65, 0x13, /* Unit (Inch), */ 0x34, /* Physical Minimum (0), */ 0x09, 0x30, /* Usage (X), */ 0x46, 0x40, 0x1F, /* Physical Maximum (8000), */ 0x26, 0x00, 0x50, /* Logical Maximum (20480), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x31, /* Usage (Y), */ 0x46, 0x70, 0x17, /* Physical Maximum (6000), */ 0x26, 0x00, 0x3C, /* Logical Maximum (15360), */ 0x81, 0x02, /* Input (Variable), */ 0xB4, /* Pop, */ 0x09, 0x30, /* Usage (Tip Pressure), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xC0, /* End Collection, */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x09, 0x02, /* Usage (Mouse), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x11, /* Report ID (17), */ 0x09, 0x01, /* Usage (Pointer), */ 0xA0, /* Collection (Physical), */ 0x14, /* Logical Minimum (0), */ 0xA4, /* Push, */ 0x05, 0x09, /* Usage Page (Button), */ 0x75, 0x01, /* Report Size (1), */ 0x19, 0x01, /* Usage Minimum (01h), */ 0x29, 0x03, /* Usage Maximum (03h), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x95, 0x03, /* Report Count (3), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x05, /* Report Count (5), */ 0x81, 0x01, /* Input (Constant), */ 0xB4, /* Pop, */ 0x95, 0x01, /* Report Count (1), */ 0xA4, /* Push, */ 0x55, 0xFD, /* Unit Exponent (-3), */ 0x65, 0x13, /* Unit (Inch), */ 0x34, /* Physical Minimum (0), */ 0x75, 0x10, /* Report Size (16), */ 0x09, 0x30, /* Usage (X), */ 0x46, 0x40, 0x1F, /* Physical Maximum (8000), */ 0x26, 0x00, 0x50, /* Logical Maximum (20480), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x31, /* Usage (Y), */ 0x46, 0x70, 0x17, /* Physical Maximum (6000), */ 0x26, 0x00, 0x3C, /* Logical Maximum (15360), */ 0x81, 0x02, /* Input (Variable), */ 0xB4, /* Pop, */ 0x75, 0x08, /* Report Size (8), */ 0x09, 0x38, /* Usage (Wheel), */ 0x15, 0xFF, /* Logical Minimum (-1), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x81, 0x06, /* Input (Variable, Relative), */ 0x81, 0x01, /* Input (Constant), */ 0xC0, /* End Collection, */ 0xC0 /* End Collection */ }; /* * See EasyPen M610X description, device and HID report descriptors at * http://sf.net/apps/mediawiki/digimend/?title=KYE_EasyPen_M610X */ /* Original EasyPen M610X report descriptor size */ #define EASYPEN_M610X_RDESC_ORIG_SIZE 476 /* Fixed EasyPen M610X report descriptor */ static __u8 easypen_m610x_rdesc_fixed[] = { 0x06, 0x00, 0xFF, /* Usage Page (FF00h), */ 0x09, 0x01, /* Usage (01h), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x05, /* Report ID (5), */ 0x09, 0x01, /* Usage (01h), */ 0x15, 0x80, /* Logical Minimum (-128), */ 0x25, 0x7F, /* Logical Maximum (127), */ 0x75, 0x08, /* Report Size (8), */ 0x95, 0x07, /* Report Count (7), */ 0xB1, 0x02, /* Feature (Variable), */ 0xC0, /* End Collection, */ 0x05, 0x0D, /* Usage Page (Digitizer), */ 0x09, 0x02, /* Usage (Pen), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x10, /* Report ID (16), */ 0x09, 0x20, /* Usage (Stylus), */ 0xA0, /* Collection (Physical), */ 0x14, /* Logical Minimum (0), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x75, 0x01, /* Report Size (1), */ 0x09, 0x42, /* Usage (Tip Switch), */ 0x09, 0x44, /* Usage (Barrel Switch), */ 0x09, 0x46, /* Usage (Tablet Pick), */ 0x95, 0x03, /* Report Count (3), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x04, /* Report Count (4), */ 0x81, 0x03, /* Input (Constant, Variable), */ 0x09, 0x32, /* Usage (In Range), */ 0x95, 0x01, /* Report Count (1), */ 0x81, 0x02, /* Input (Variable), */ 0x75, 0x10, /* Report Size (16), */ 0x95, 0x01, /* Report Count (1), */ 0xA4, /* Push, */ 0x05, 0x01, /* Usage Page (Desktop), */ 0x55, 0xFD, /* Unit Exponent (-3), */ 0x65, 0x13, /* Unit (Inch), */ 0x34, /* Physical Minimum (0), */ 0x09, 0x30, /* Usage (X), */ 0x46, 0x10, 0x27, /* Physical Maximum (10000), */ 0x27, 0x00, 0xA0, 0x00, 0x00, /* Logical Maximum (40960), */ 0x81, 0x02, /* Input (Variable), */ 0x09, 0x31, /* Usage (Y), */ 0x46, 0x6A, 0x18, /* Physical Maximum (6250), */ 0x26, 0x00, 0x64, /* Logical Maximum (25600), */ 0x81, 0x02, /* Input (Variable), */ 0xB4, /* Pop, */ 0x09, 0x30, /* Usage (Tip Pressure), */ 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */ 0x81, 0x02, /* Input (Variable), */ 0xC0, /* End Collection, */ 0xC0, /* End Collection, */ 0x05, 0x0C, /* Usage Page (Consumer), */ 0x09, 0x01, /* Usage (Consumer Control), */ 0xA1, 0x01, /* Collection (Application), */ 0x85, 0x12, /* Report ID (18), */ 0x14, /* Logical Minimum (0), */ 0x25, 0x01, /* Logical Maximum (1), */ 0x75, 0x01, /* Report Size (1), */ 0x95, 0x04, /* Report Count (4), */ 0x0A, 0x1A, 0x02, /* Usage (AC Undo), */ 0x0A, 0x79, 0x02, /* Usage (AC Redo Or Repeat), */ 0x0A, 0x2D, 0x02, /* Usage (AC Zoom In), */ 0x0A, 0x2E, 0x02, /* Usage (AC Zoom Out), */ 0x81, 0x02, /* Input (Variable), */ 0x95, 0x01, /* Report Count (1), */ 0x75, 0x14, /* Report Size (20), */ 0x81, 0x03, /* Input (Constant, Variable), */ 0x75, 0x20, /* Report Size (32), */ 0x81, 0x03, /* Input (Constant, Variable), */ 0xC0 /* End Collection */ }; static __u8 *kye_consumer_control_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize, int offset, const char *device_name) { /* * the fixup that need to be done: * - change Usage Maximum in the Comsumer Control * (report ID 3) to a reasonable value */ if (*rsize >= offset + 31 && /* Usage Page (Consumer Devices) */ rdesc[offset] == 0x05 && rdesc[offset + 1] == 0x0c && /* Usage (Consumer Control) */ rdesc[offset + 2] == 0x09 && rdesc[offset + 3] == 0x01 && /* Usage Maximum > 12287 */ rdesc[offset + 10] == 0x2a && rdesc[offset + 12] > 0x2f) { hid_info(hdev, "fixing up %s report descriptor\n", device_name); rdesc[offset + 12] = 0x2f; } return rdesc; } static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { switch (hdev->product) { case USB_DEVICE_ID_KYE_ERGO_525V: /* the fixups that need to be done: * - change led usage page to button for extra buttons * - report size 8 count 1 must be size 1 count 8 for button * bitfield * - change the button usage range to 4-7 for the extra * buttons */ if (*rsize >= 74 && rdesc[61] == 0x05 && rdesc[62] == 0x08 && rdesc[63] == 0x19 && rdesc[64] == 0x08 && rdesc[65] == 0x29 && rdesc[66] == 0x0f && rdesc[71] == 0x75 && rdesc[72] == 0x08 && rdesc[73] == 0x95 && rdesc[74] == 0x01) { hid_info(hdev, "fixing up Kye/Genius Ergo Mouse " "report descriptor\n"); rdesc[62] = 0x09; rdesc[64] = 0x04; rdesc[66] = 0x07; rdesc[72] = 0x01; rdesc[74] = 0x08; } break; case USB_DEVICE_ID_KYE_EASYPEN_I405X: if (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) { rdesc = easypen_i405x_rdesc_fixed; *rsize = sizeof(easypen_i405x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_MOUSEPEN_I608X: if (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) { rdesc = mousepen_i608x_rdesc_fixed; *rsize = sizeof(mousepen_i608x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_EASYPEN_M610X: if (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) { rdesc = easypen_m610x_rdesc_fixed; *rsize = sizeof(easypen_m610x_rdesc_fixed); } break; case USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Gila Gaming Mouse"); break; case USB_DEVICE_ID_GENIUS_GX_IMPERATOR: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83, "Genius Gx Imperator Keyboard"); break; case USB_DEVICE_ID_GENIUS_MANTICORE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Manticore Keyboard"); break; } return rdesc; } /** * Enable fully-functional tablet mode by setting a special feature report. * * @hdev: HID device * * The specific report ID and data were discovered by sniffing the * Windows driver traffic. */ static int kye_tablet_enable(struct hid_device *hdev) { struct list_head *list; struct list_head *head; struct hid_report *report; __s32 *value; list = &hdev->report_enum[HID_FEATURE_REPORT].report_list; list_for_each(head, list) { report = list_entry(head, struct hid_report, list); if (report->id == 5) break; } if (head == list) { hid_err(hdev, "tablet-enabling feature report not found\n"); return -ENODEV; } if (report->maxfield < 1 || report->field[0]->report_count < 7) { hid_err(hdev, "invalid tablet-enabling feature report\n"); return -ENODEV; } value = report->field[0]->value; value[0] = 0x12; value[1] = 0x10; value[2] = 0x11; value[3] = 0x12; value[4] = 0x00; value[5] = 0x00; value[6] = 0x00; hid_hw_request(hdev, report, HID_REQ_SET_REPORT); return 0; } static int kye_probe(struct hid_device *hdev, const struct hid_device_id *id) { int ret; ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); goto err; } ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); if (ret) { hid_err(hdev, "hw start failed\n"); goto err; } switch (id->product) { case USB_DEVICE_ID_KYE_EASYPEN_I405X: case USB_DEVICE_ID_KYE_MOUSEPEN_I608X: case USB_DEVICE_ID_KYE_EASYPEN_M610X: ret = kye_tablet_enable(hdev); if (ret) { hid_err(hdev, "tablet enabling failed\n"); goto enabling_err; } break; case USB_DEVICE_ID_GENIUS_MANTICORE: /* * The manticore keyboard needs to have all the interfaces * opened at least once to be fully functional. */ if (hid_hw_open(hdev)) hid_hw_close(hdev); break; } return 0; enabling_err: hid_hw_stop(hdev); err: return ret; } static const struct hid_device_id kye_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_ERGO_525V) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_I405X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_MOUSEPEN_I608X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M610X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_GX_IMPERATOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_MANTICORE) }, { } }; MODULE_DEVICE_TABLE(hid, kye_devices); static struct hid_driver kye_driver = { .name = "kye", .id_table = kye_devices, .probe = kye_probe, .report_fixup = kye_report_fixup, }; module_hid_driver(kye_driver); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2131_1
crossvul-cpp_data_good_2400_0
/* * Copyright (c) Ian F. Darwin 1986-1995. * Software written by Ian F. Darwin and others; * maintained 1995-present by Christos Zoulas and others. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * softmagic - interpret variable magic from MAGIC */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: softmagic.c,v 1.196 2014/11/07 15:24:14 christos Exp $") #endif /* lint */ #include "magic.h" #include <assert.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <time.h> private int match(struct magic_set *, struct magic *, uint32_t, const unsigned char *, size_t, size_t, int, int, int, int, int *, int *, int *); private int mget(struct magic_set *, const unsigned char *, struct magic *, size_t, size_t, unsigned int, int, int, int, int, int *, int *, int *); private int magiccheck(struct magic_set *, struct magic *); private int32_t mprint(struct magic_set *, struct magic *); private int32_t moffset(struct magic_set *, struct magic *); private void mdebug(uint32_t, const char *, size_t); private int mcopy(struct magic_set *, union VALUETYPE *, int, int, const unsigned char *, uint32_t, size_t, struct magic *); private int mconvert(struct magic_set *, struct magic *, int); private int print_sep(struct magic_set *, int); private int handle_annotation(struct magic_set *, struct magic *); private void cvt_8(union VALUETYPE *, const struct magic *); private void cvt_16(union VALUETYPE *, const struct magic *); private void cvt_32(union VALUETYPE *, const struct magic *); private void cvt_64(union VALUETYPE *, const struct magic *); #define OFFSET_OOB(n, o, i) ((n) < (o) || (i) > ((n) - (o))) /* * softmagic - lookup one file in parsed, in-memory copy of database * Passed the name and FILE * of one file to be typed. */ /*ARGSUSED1*/ /* nbytes passed for regularity, maybe need later */ protected int file_softmagic(struct magic_set *ms, const unsigned char *buf, size_t nbytes, size_t level, int mode, int text) { struct mlist *ml; int rv, printed_something = 0, need_separator = 0; for (ml = ms->mlist[0]->next; ml != ms->mlist[0]; ml = ml->next) if ((rv = match(ms, ml->magic, ml->nmagic, buf, nbytes, 0, mode, text, 0, level, &printed_something, &need_separator, NULL)) != 0) return rv; return 0; } #define FILE_FMTDEBUG #ifdef FILE_FMTDEBUG #define F(a, b, c) file_fmtcheck((a), (b), (c), __FILE__, __LINE__) private const char * __attribute__((__format_arg__(3))) file_fmtcheck(struct magic_set *ms, const struct magic *m, const char *def, const char *file, size_t line) { const char *ptr = fmtcheck(m->desc, def); if (ptr == def) file_magerror(ms, "%s, %" SIZE_T_FORMAT "u: format `%s' does not match" " with `%s'", file, line, m->desc, def); return ptr; } #else #define F(a, b, c) fmtcheck((b)->desc, (c)) #endif /* * Go through the whole list, stopping if you find a match. Process all * the continuations of that match before returning. * * We support multi-level continuations: * * At any time when processing a successful top-level match, there is a * current continuation level; it represents the level of the last * successfully matched continuation. * * Continuations above that level are skipped as, if we see one, it * means that the continuation that controls them - i.e, the * lower-level continuation preceding them - failed to match. * * Continuations below that level are processed as, if we see one, * it means we've finished processing or skipping higher-level * continuations under the control of a successful or unsuccessful * lower-level continuation, and are now seeing the next lower-level * continuation and should process it. The current continuation * level reverts to the level of the one we're seeing. * * Continuations at the current level are processed as, if we see * one, there's no lower-level continuation that may have failed. * * If a continuation matches, we bump the current continuation level * so that higher-level continuations are processed. */ private int match(struct magic_set *ms, struct magic *magic, uint32_t nmagic, const unsigned char *s, size_t nbytes, size_t offset, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t magindex = 0; unsigned int cont_level = 0; int returnvalv = 0, e; /* if a match is found it is set to 1*/ int firstline = 1; /* a flag to print X\n X\n- X */ int print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0; if (returnval == NULL) returnval = &returnvalv; if (file_check_mem(ms, cont_level) == -1) return -1; for (magindex = 0; magindex < nmagic; magindex++) { int flush = 0; struct magic *m = &magic[magindex]; if (m->type != FILE_NAME) if ((IS_STRING(m->type) && #define FLT (STRING_BINTEST | STRING_TEXTTEST) ((text && (m->str_flags & FLT) == STRING_BINTEST) || (!text && (m->str_flags & FLT) == STRING_TEXTTEST))) || (m->flag & mode) != mode) { /* Skip sub-tests */ while (magindex + 1 < nmagic && magic[magindex + 1].cont_level != 0 && ++magindex) continue; continue; /* Skip to next top-level test*/ } ms->offset = m->offset; ms->line = m->lineno; /* if main entry matches, print it... */ switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text, flip, recursion_level + 1, printed_something, need_separator, returnval)) { case -1: return -1; case 0: flush = m->reln != '!'; break; default: if (m->type == FILE_INDIRECT) *returnval = 1; switch (magiccheck(ms, m)) { case -1: return -1; case 0: flush++; break; default: flush = 0; break; } break; } if (flush) { /* * main entry didn't match, * flush its continuations */ while (magindex < nmagic - 1 && magic[magindex + 1].cont_level != 0) magindex++; continue; } if ((e = handle_annotation(ms, m)) != 0) { *need_separator = 1; *printed_something = 1; *returnval = 1; return e; } /* * If we are going to print something, we'll need to print * a blank before we print something else. */ if (*m->desc) { *need_separator = 1; *printed_something = 1; if (print_sep(ms, firstline) == -1) return -1; } if (print && mprint(ms, m) == -1) return -1; ms->c.li[cont_level].off = moffset(ms, m); /* and any continuations that match */ if (file_check_mem(ms, ++cont_level) == -1) return -1; while (magindex + 1 < nmagic && magic[magindex + 1].cont_level != 0) { m = &magic[++magindex]; ms->line = m->lineno; /* for messages */ if (cont_level < m->cont_level) continue; if (cont_level > m->cont_level) { /* * We're at the end of the level * "cont_level" continuations. */ cont_level = m->cont_level; } ms->offset = m->offset; if (m->flag & OFFADD) { ms->offset += ms->c.li[cont_level - 1].off; } #ifdef ENABLE_CONDITIONALS if (m->cond == COND_ELSE || m->cond == COND_ELIF) { if (ms->c.li[cont_level].last_match == 1) continue; } #endif switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text, flip, recursion_level + 1, printed_something, need_separator, returnval)) { case -1: return -1; case 0: if (m->reln != '!') continue; flush = 1; break; default: if (m->type == FILE_INDIRECT) *returnval = 1; flush = 0; break; } switch (flush ? 1 : magiccheck(ms, m)) { case -1: return -1; case 0: #ifdef ENABLE_CONDITIONALS ms->c.li[cont_level].last_match = 0; #endif break; default: #ifdef ENABLE_CONDITIONALS ms->c.li[cont_level].last_match = 1; #endif if (m->type == FILE_CLEAR) ms->c.li[cont_level].got_match = 0; else if (ms->c.li[cont_level].got_match) { if (m->type == FILE_DEFAULT) break; } else ms->c.li[cont_level].got_match = 1; if ((e = handle_annotation(ms, m)) != 0) { *need_separator = 1; *printed_something = 1; *returnval = 1; return e; } /* * If we are going to print something, * make sure that we have a separator first. */ if (*m->desc) { if (!*printed_something) { *printed_something = 1; if (print_sep(ms, firstline) == -1) return -1; } } /* * This continuation matched. Print * its message, with a blank before it * if the previous item printed and * this item isn't empty. */ /* space if previous printed */ if (*need_separator && ((m->flag & NOSPACE) == 0) && *m->desc) { if (print && file_printf(ms, " ") == -1) return -1; *need_separator = 0; } if (print && mprint(ms, m) == -1) return -1; ms->c.li[cont_level].off = moffset(ms, m); if (*m->desc) *need_separator = 1; /* * If we see any continuations * at a higher level, * process them. */ if (file_check_mem(ms, ++cont_level) == -1) return -1; break; } } if (*printed_something) { firstline = 0; if (print) *returnval = 1; } if ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) { return *returnval; /* don't keep searching */ } } return *returnval; /* This is hit if -k is set or there is no match */ } private int check_fmt(struct magic_set *ms, struct magic *m) { file_regex_t rx; int rc, rv = -1; if (strchr(m->desc, '%') == NULL) return 0; rc = file_regcomp(&rx, "%[-0-9\\.]*s", REG_EXTENDED|REG_NOSUB); if (rc) { file_regerror(&rx, rc, ms); } else { rc = file_regexec(&rx, m->desc, 0, 0, 0); rv = !rc; } file_regfree(&rx); return rv; } #ifndef HAVE_STRNDUP char * strndup(const char *, size_t); char * strndup(const char *str, size_t n) { size_t len; char *copy; for (len = 0; len < n && str[len]; len++) continue; if ((copy = malloc(len + 1)) == NULL) return NULL; (void)memcpy(copy, str, len); copy[len] = '\0'; return copy; } #endif /* HAVE_STRNDUP */ static char * printable(char *buf, size_t bufsiz, const char *str) { char *ptr, *eptr; const unsigned char *s = (const unsigned char *)str; for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) { if (isprint(*s)) { *ptr++ = *s; continue; } if (ptr >= eptr + 4) break; *ptr++ = '\\'; *ptr++ = ((*s >> 6) & 7) + '0'; *ptr++ = ((*s >> 3) & 7) + '0'; *ptr++ = ((*s >> 0) & 7) + '0'; } *ptr = '\0'; return buf; } private int32_t mprint(struct magic_set *ms, struct magic *m) { uint64_t v; float vf; double vd; int64_t t = 0; char buf[128], tbuf[26]; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = file_signextend(ms, m, (uint64_t)p->b); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%d", (unsigned char)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%d"), (unsigned char) v) == -1) return -1; break; } t = ms->offset + sizeof(char); break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = file_signextend(ms, m, (uint64_t)p->h); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%u", (unsigned short)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%u"), (unsigned short) v) == -1) return -1; break; } t = ms->offset + sizeof(short); break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: v = file_signextend(ms, m, (uint64_t)p->l); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%u", (uint32_t) v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%u"), (uint32_t) v) == -1) return -1; break; } t = ms->offset + sizeof(int32_t); break; case FILE_QUAD: case FILE_BEQUAD: case FILE_LEQUAD: v = file_signextend(ms, m, p->q); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%" INT64_T_FORMAT "u", (unsigned long long)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%" INT64_T_FORMAT "u"), (unsigned long long) v) == -1) return -1; break; } t = ms->offset + sizeof(int64_t); break; case FILE_STRING: case FILE_PSTRING: case FILE_BESTRING16: case FILE_LESTRING16: if (m->reln == '=' || m->reln == '!') { if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1) return -1; t = ms->offset + m->vallen; } else { char sbuf[512]; char *str = p->s; /* compute t before we mangle the string? */ t = ms->offset + strlen(str); if (*m->value.s == '\0') str[strcspn(str, "\n")] = '\0'; if (m->str_flags & STRING_TRIM) { char *last; while (isspace((unsigned char)*str)) str++; last = str; while (*last) last++; --last; while (isspace((unsigned char)*last)) last--; *++last = '\0'; } if (file_printf(ms, F(ms, m, "%s"), printable(sbuf, sizeof(sbuf), str)) == -1) return -1; if (m->type == FILE_PSTRING) t += file_pstring_length_size(m); } break; case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->l + m->num_mask, FILE_T_LOCAL, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint32_t); break; case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->l + m->num_mask, 0, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint32_t); break; case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q + m->num_mask, FILE_T_LOCAL, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q + m->num_mask, 0, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q + m->num_mask, FILE_T_WINDOWS, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: vf = p->f; switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%g", vf); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%g"), vf) == -1) return -1; break; } t = ms->offset + sizeof(float); break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: vd = p->d; switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%g", vd); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%g"), vd) == -1) return -1; break; } t = ms->offset + sizeof(double); break; case FILE_REGEX: { char *cp; int rval; cp = strndup((const char *)ms->search.s, ms->search.rm_len); if (cp == NULL) { file_oomem(ms, ms->search.rm_len); return -1; } rval = file_printf(ms, F(ms, m, "%s"), cp); free(cp); if (rval == -1) return -1; if ((m->str_flags & REGEX_OFFSET_START)) t = ms->search.offset; else t = ms->search.offset + ms->search.rm_len; break; } case FILE_SEARCH: if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1) return -1; if ((m->str_flags & REGEX_OFFSET_START)) t = ms->search.offset; else t = ms->search.offset + m->vallen; break; case FILE_DEFAULT: case FILE_CLEAR: if (file_printf(ms, "%s", m->desc) == -1) return -1; t = ms->offset; break; case FILE_INDIRECT: case FILE_USE: case FILE_NAME: t = ms->offset; break; default: file_magerror(ms, "invalid m->type (%d) in mprint()", m->type); return -1; } return (int32_t)t; } private int32_t moffset(struct magic_set *ms, struct magic *m) { switch (m->type) { case FILE_BYTE: return CAST(int32_t, (ms->offset + sizeof(char))); case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: return CAST(int32_t, (ms->offset + sizeof(short))); case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: return CAST(int32_t, (ms->offset + sizeof(int32_t))); case FILE_QUAD: case FILE_BEQUAD: case FILE_LEQUAD: return CAST(int32_t, (ms->offset + sizeof(int64_t))); case FILE_STRING: case FILE_PSTRING: case FILE_BESTRING16: case FILE_LESTRING16: if (m->reln == '=' || m->reln == '!') return ms->offset + m->vallen; else { union VALUETYPE *p = &ms->ms_value; uint32_t t; if (*m->value.s == '\0') p->s[strcspn(p->s, "\n")] = '\0'; t = CAST(uint32_t, (ms->offset + strlen(p->s))); if (m->type == FILE_PSTRING) t += (uint32_t)file_pstring_length_size(m); return t; } case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: return CAST(int32_t, (ms->offset + sizeof(uint32_t))); case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: return CAST(int32_t, (ms->offset + sizeof(uint32_t))); case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: return CAST(int32_t, (ms->offset + sizeof(uint64_t))); case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: return CAST(int32_t, (ms->offset + sizeof(uint64_t))); case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: return CAST(int32_t, (ms->offset + sizeof(float))); case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: return CAST(int32_t, (ms->offset + sizeof(double))); case FILE_REGEX: if ((m->str_flags & REGEX_OFFSET_START) != 0) return CAST(int32_t, ms->search.offset); else return CAST(int32_t, (ms->search.offset + ms->search.rm_len)); case FILE_SEARCH: if ((m->str_flags & REGEX_OFFSET_START) != 0) return CAST(int32_t, ms->search.offset); else return CAST(int32_t, (ms->search.offset + m->vallen)); case FILE_CLEAR: case FILE_DEFAULT: case FILE_INDIRECT: return ms->offset; default: return 0; } } private int cvt_flip(int type, int flip) { if (flip == 0) return type; switch (type) { case FILE_BESHORT: return FILE_LESHORT; case FILE_BELONG: return FILE_LELONG; case FILE_BEDATE: return FILE_LEDATE; case FILE_BELDATE: return FILE_LELDATE; case FILE_BEQUAD: return FILE_LEQUAD; case FILE_BEQDATE: return FILE_LEQDATE; case FILE_BEQLDATE: return FILE_LEQLDATE; case FILE_BEQWDATE: return FILE_LEQWDATE; case FILE_LESHORT: return FILE_BESHORT; case FILE_LELONG: return FILE_BELONG; case FILE_LEDATE: return FILE_BEDATE; case FILE_LELDATE: return FILE_BELDATE; case FILE_LEQUAD: return FILE_BEQUAD; case FILE_LEQDATE: return FILE_BEQDATE; case FILE_LEQLDATE: return FILE_BEQLDATE; case FILE_LEQWDATE: return FILE_BEQWDATE; case FILE_BEFLOAT: return FILE_LEFLOAT; case FILE_LEFLOAT: return FILE_BEFLOAT; case FILE_BEDOUBLE: return FILE_LEDOUBLE; case FILE_LEDOUBLE: return FILE_BEDOUBLE; default: return type; } } #define DO_CVT(fld, cast) \ if (m->num_mask) \ switch (m->mask_op & FILE_OPS_MASK) { \ case FILE_OPAND: \ p->fld &= cast m->num_mask; \ break; \ case FILE_OPOR: \ p->fld |= cast m->num_mask; \ break; \ case FILE_OPXOR: \ p->fld ^= cast m->num_mask; \ break; \ case FILE_OPADD: \ p->fld += cast m->num_mask; \ break; \ case FILE_OPMINUS: \ p->fld -= cast m->num_mask; \ break; \ case FILE_OPMULTIPLY: \ p->fld *= cast m->num_mask; \ break; \ case FILE_OPDIVIDE: \ p->fld /= cast m->num_mask; \ break; \ case FILE_OPMODULO: \ p->fld %= cast m->num_mask; \ break; \ } \ if (m->mask_op & FILE_OPINVERSE) \ p->fld = ~p->fld \ private void cvt_8(union VALUETYPE *p, const struct magic *m) { DO_CVT(b, (uint8_t)); } private void cvt_16(union VALUETYPE *p, const struct magic *m) { DO_CVT(h, (uint16_t)); } private void cvt_32(union VALUETYPE *p, const struct magic *m) { DO_CVT(l, (uint32_t)); } private void cvt_64(union VALUETYPE *p, const struct magic *m) { DO_CVT(q, (uint64_t)); } #define DO_CVT2(fld, cast) \ if (m->num_mask) \ switch (m->mask_op & FILE_OPS_MASK) { \ case FILE_OPADD: \ p->fld += cast m->num_mask; \ break; \ case FILE_OPMINUS: \ p->fld -= cast m->num_mask; \ break; \ case FILE_OPMULTIPLY: \ p->fld *= cast m->num_mask; \ break; \ case FILE_OPDIVIDE: \ p->fld /= cast m->num_mask; \ break; \ } \ private void cvt_float(union VALUETYPE *p, const struct magic *m) { DO_CVT2(f, (float)); } private void cvt_double(union VALUETYPE *p, const struct magic *m) { DO_CVT2(d, (double)); } /* * Convert the byte order of the data we are looking at * While we're here, let's apply the mask operation * (unless you have a better idea) */ private int mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { size_t sz = file_pstring_length_size(m); char *ptr1 = p->s, *ptr2 = ptr1 + sz; size_t len = file_pstring_get_length(m, ptr1); sz = sizeof(p->s) - sz; /* maximum length of string */ if (len >= sz) { /* * The size of the pascal string length (sz) * is 1, 2, or 4. We need at least 1 byte for NUL * termination, but we've already truncated the * string by p->s, so we need to deduct sz. * Because we can use one of the bytes of the length * after we shifted as NUL termination. */ len = sz; } while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } private void mdebug(uint32_t offset, const char *str, size_t len) { (void) fprintf(stderr, "mget/%" SIZE_T_FORMAT "u @%d: ", len, offset); file_showstr(stderr, str, len); (void) fputc('\n', stderr); (void) fputc('\n', stderr); } private int mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines, linecnt, bytecnt; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } if (m->str_flags & REGEX_LINE_COUNT) { linecnt = m->str_range; bytecnt = linecnt * 80; } else { linecnt = 0; bytecnt = m->str_range; } if (bytecnt == 0) bytecnt = 8192; if (bytecnt > nbytes) bytecnt = nbytes; buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + bytecnt; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\r' && b[1] == '\n') b++; } if (lines) last = RCAST(const char *, s) + bytecnt; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\0' : *(src + 1) != '\0') *dst = ' '; } } *edst = '\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\0', sizeof(*p) - nbytes); return 0; } private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t lhs; int rv, oneed_separator, in_type; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, m) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%" SIZE_T_FORMAT "u, " "nbytes=%" SIZE_T_FORMAT "u)\n", m->type, m->flag, offset, o, nbytes); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (in_type = cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[0] << 8) | p->hs[1]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[1] << 8) | p->hs[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[0] << 24) | (p->hl[1] << 16) | (p->hl[2] << 8) | p->hl[3]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[3] << 24) | (p->hl[2] << 16) | (p->hl[1] << 8) | p->hl[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[1] << 24) | (p->hl[0] << 16) | (p->hl[3] << 8) | p->hl[2]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; default: break; } switch (in_type) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (OFFSET_OOB(nbytes, offset, 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (OFFSET_OOB(nbytes, offset, 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (OFFSET_OOB(nbytes, offset, m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (offset == 0) return 0; if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, recursion_level, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, F(ms, m, "%u"), offset) == -1) { free(rbuf); return -1; } if (file_printf(ms, "%s", rbuf) == -1) { free(rbuf); return -1; } } free(rbuf); return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ case FILE_CLEAR: default: break; } if (!mconvert(ms, m, flip)) return 0; return 1; } private uint64_t file_strncmp(const char *s1, const char *s2, size_t len, uint32_t flags) { /* * Convert the source args to unsigned here so that (1) the * compare will be unsigned as it is in strncmp() and (2) so * the ctype functions will work correctly without extra * casting. */ const unsigned char *a = (const unsigned char *)s1; const unsigned char *b = (const unsigned char *)s2; uint64_t v; /* * What we want here is v = strncmp(s1, s2, len), * but ignoring any nulls. */ v = 0; if (0L == flags) { /* normal string: do it fast */ while (len-- > 0) if ((v = *b++ - *a++) != '\0') break; } else { /* combine the others */ while (len-- > 0) { if ((flags & STRING_IGNORE_LOWERCASE) && islower(*a)) { if ((v = tolower(*b++) - *a++) != '\0') break; } else if ((flags & STRING_IGNORE_UPPERCASE) && isupper(*a)) { if ((v = toupper(*b++) - *a++) != '\0') break; } else if ((flags & STRING_COMPACT_WHITESPACE) && isspace(*a)) { a++; if (isspace(*b++)) { if (!isspace(*a)) while (isspace(*b)) b++; } else { v = 1; break; } } else if ((flags & STRING_COMPACT_OPTIONAL_WHITESPACE) && isspace(*a)) { a++; while (isspace(*b)) b++; } else { if ((v = *b++ - *a++) != '\0') break; } } } return v; } private uint64_t file_strncmp16(const char *a, const char *b, size_t len, uint32_t flags) { /* * XXX - The 16-bit string compare probably needs to be done * differently, especially if the flags are to be supported. * At the moment, I am unsure. */ flags = 0; return file_strncmp(a, b, len, flags); } private int magiccheck(struct magic_set *ms, struct magic *m) { uint64_t l = m->value.q; uint64_t v; float fl, fv; double dl, dv; int matched; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = p->b; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = p->h; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: v = p->l; break; case FILE_QUAD: case FILE_LEQUAD: case FILE_BEQUAD: case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: v = p->q; break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: fl = m->value.f; fv = p->f; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = fv != fl; break; case '=': matched = fv == fl; break; case '>': matched = fv > fl; break; case '<': matched = fv < fl; break; default: file_magerror(ms, "cannot happen with float: invalid relation `%c'", m->reln); return -1; } return matched; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: dl = m->value.d; dv = p->d; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = dv != dl; break; case '=': matched = dv == dl; break; case '>': matched = dv > dl; break; case '<': matched = dv < dl; break; default: file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln); return -1; } return matched; case FILE_DEFAULT: case FILE_CLEAR: l = 0; v = 0; break; case FILE_STRING: case FILE_PSTRING: l = 0; v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_BESTRING16: case FILE_LESTRING16: l = 0; v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */ size_t slen; size_t idx; if (ms->search.s == NULL) return 0; slen = MIN(m->vallen, sizeof(m->value.s)); l = 0; v = 0; for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) { if (slen + idx > ms->search.s_len) break; v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags); if (v == 0) { /* found match */ ms->search.offset += idx; break; } } break; } case FILE_REGEX: { int rc; file_regex_t rx; const char *search; if (ms->search.s == NULL) return 0; l = 0; rc = file_regcomp(&rx, m->value.s, REG_EXTENDED|REG_NEWLINE| ((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0)); if (rc) { file_regerror(&rx, rc, ms); v = (uint64_t)-1; } else { regmatch_t pmatch[1]; size_t slen = ms->search.s_len; #ifndef REG_STARTEND #define REG_STARTEND 0 char *copy; if (slen != 0) { copy = malloc(slen); if (copy == NULL) { file_error(ms, errno, "can't allocate %" SIZE_T_FORMAT "u bytes", slen); return -1; } memcpy(copy, ms->search.s, slen); copy[--slen] = '\0'; search = copy; } else { search = ms->search.s; copy = NULL; } #else search = ms->search.s; pmatch[0].rm_so = 0; pmatch[0].rm_eo = slen; #endif rc = file_regexec(&rx, (const char *)search, 1, pmatch, REG_STARTEND); #if REG_STARTEND == 0 free(copy); #endif switch (rc) { case 0: ms->search.s += (int)pmatch[0].rm_so; ms->search.offset += (size_t)pmatch[0].rm_so; ms->search.rm_len = (size_t)(pmatch[0].rm_eo - pmatch[0].rm_so); v = 0; break; case REG_NOMATCH: v = 1; break; default: file_regerror(&rx, rc, ms); v = (uint64_t)-1; break; } } file_regfree(&rx); if (v == (uint64_t)-1) return -1; break; } case FILE_INDIRECT: case FILE_USE: case FILE_NAME: return 1; default: file_magerror(ms, "invalid type %d in magiccheck()", m->type); return -1; } v = file_signextend(ms, m, v); switch (m->reln) { case 'x': if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u == *any* = 1\n", (unsigned long long)v); matched = 1; break; case '!': matched = v != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u != %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); break; case '=': matched = v == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u == %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); break; case '>': if (m->flag & UNSIGNED) { matched = v > l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u > %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v > (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "d > %" INT64_T_FORMAT "d = %d\n", (long long)v, (long long)l, matched); } break; case '<': if (m->flag & UNSIGNED) { matched = v < l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u < %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v < (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "d < %" INT64_T_FORMAT "d = %d\n", (long long)v, (long long)l, matched); } break; case '&': matched = (v & l) == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %" INT64_T_FORMAT "x) == %" INT64_T_FORMAT "x) = %d\n", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; case '^': matched = (v & l) != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %" INT64_T_FORMAT "x) != %" INT64_T_FORMAT "x) = %d\n", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; default: file_magerror(ms, "cannot happen: invalid relation `%c'", m->reln); return -1; } return matched; } private int handle_annotation(struct magic_set *ms, struct magic *m) { if (ms->flags & MAGIC_APPLE) { if (file_printf(ms, "%.8s", m->apple) == -1) return -1; return 1; } if ((ms->flags & MAGIC_MIME_TYPE) && m->mimetype[0]) { if (file_printf(ms, "%s", m->mimetype) == -1) return -1; return 1; } return 0; } private int print_sep(struct magic_set *ms, int firstline) { if (ms->flags & MAGIC_MIME) return 0; if (firstline) return 0; /* * we found another match * put a newline and '-' to do some simple formatting */ return file_printf(ms, "\n- "); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2400_0
crossvul-cpp_data_good_5635_0
/* * host.c - ChipIdea USB host controller driver * * Copyright (c) 2012 Intel Corporation * * Author: Alexander Shishkin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/kernel.h> #include <linux/io.h> #include <linux/usb.h> #include <linux/usb/hcd.h> #include <linux/usb/chipidea.h> #include "../host/ehci.h" #include "ci.h" #include "bits.h" #include "host.h" static struct hc_driver __read_mostly ci_ehci_hc_driver; static irqreturn_t host_irq(struct ci13xxx *ci) { return usb_hcd_irq(ci->irq, ci->hcd); } static int host_start(struct ci13xxx *ci) { struct usb_hcd *hcd; struct ehci_hcd *ehci; int ret; if (usb_disabled()) return -ENODEV; hcd = usb_create_hcd(&ci_ehci_hc_driver, ci->dev, dev_name(ci->dev)); if (!hcd) return -ENOMEM; dev_set_drvdata(ci->dev, ci); hcd->rsrc_start = ci->hw_bank.phys; hcd->rsrc_len = ci->hw_bank.size; hcd->regs = ci->hw_bank.abs; hcd->has_tt = 1; hcd->power_budget = ci->platdata->power_budget; hcd->phy = ci->transceiver; ehci = hcd_to_ehci(hcd); ehci->caps = ci->hw_bank.cap; ehci->has_hostpc = ci->hw_bank.lpm; ret = usb_add_hcd(hcd, 0, 0); if (ret) usb_put_hcd(hcd); else ci->hcd = hcd; if (ci->platdata->flags & CI13XXX_DISABLE_STREAMING) hw_write(ci, OP_USBMODE, USBMODE_CI_SDIS, USBMODE_CI_SDIS); return ret; } static void host_stop(struct ci13xxx *ci) { struct usb_hcd *hcd = ci->hcd; usb_remove_hcd(hcd); usb_put_hcd(hcd); } int ci_hdrc_host_init(struct ci13xxx *ci) { struct ci_role_driver *rdrv; if (!hw_read(ci, CAP_DCCPARAMS, DCCPARAMS_HC)) return -ENXIO; rdrv = devm_kzalloc(ci->dev, sizeof(struct ci_role_driver), GFP_KERNEL); if (!rdrv) return -ENOMEM; rdrv->start = host_start; rdrv->stop = host_stop; rdrv->irq = host_irq; rdrv->name = "host"; ci->roles[CI_ROLE_HOST] = rdrv; ehci_init_driver(&ci_ehci_hc_driver, NULL); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5635_0
crossvul-cpp_data_bad_3109_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; break; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image, ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(option) == MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=MagickTrue; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length-16)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); SetPixelRGBO(q,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(indexes+x))); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels == 1 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelGreen(q,pixel); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels, const size_t row,const ssize_t type,const unsigned char *pixels, ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->matte=MagickTrue; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } (void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image* image,const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } 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 == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); 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 */ if (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+=WriteBlobMSBLong(image,mask->rows+mask->page.y); size+=WriteBlobMSBLong(image,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 : 16),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); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3109_0
crossvul-cpp_data_bad_4787_8
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC M M Y Y K K % % C MM MM Y Y K K % % C M M M Y KKK % % C M M Y K K % % CCCC M M Y K K % % % % % % Read/Write RAW CMYK Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colorspace.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" /* Forward declarations. */ static MagickBooleanType WriteCMYKImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCMYKImage() reads an image of raw CMYK or CMYKA samples and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadCMYKImage method is: % % Image *ReadCMYKImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadCMYKImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); SetImageColorspace(image,CMYKColorspace); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.cmyk[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=CMYKQuantum; if (LocaleCompare(image_info->magick,"CMYKA") == 0) { quantum_type=CMYKAQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; SetImageColorspace(image,CMYKColorspace); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: CMYKCMYKCMYKCMYKCMYKCMYK... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelBlack(indexes+x,GetPixelBlack( canvas_indexes+image->extract_info.x+x)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[5] = { CyanQuantum, MagentaQuantum, YellowQuantum, BlackQuantum, OpacityQuantum }; /* Line interlacing: CCC...MMM...YYY...KKK...CCC...MMM...YYY...KKK... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,CyanQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (image->matte != MagickFalse ? 5 : 4); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case CyanQuantum: { SetPixelCyan(q,GetPixelCyan(p)); break; } case MagentaQuantum: { SetPixelMagenta(q,GetPixelMagenta(p)); break; } case YellowQuantum: { SetPixelYellow(q,GetPixelYellow(p)); break; } case BlackQuantum: { SetPixelIndex(indexes+x,GetPixelIndex( canvas_indexes+image->extract_info.x+x)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: CCCCCC...MMMMMM...YYYYYY...KKKKKK... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,CyanQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,CyanQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,MagentaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,YellowQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlackQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,GetPixelIndex( canvas_indexes+image->extract_info.x+x)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: CCCCCC..., MMMMMM..., YYYYYY..., KKKKKK... */ AppendImageFormat("C",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,CyanQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,CyanQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("M",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,MagentaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,MagentaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,YellowQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,YellowQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("K",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,BlackQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const IndexPacket *restrict canvas_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlackQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; canvas_indexes=GetVirtualIndexQueue(canvas_image); indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,GetPixelIndex( canvas_indexes+image->extract_info.x+x)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,YellowQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* 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; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCMYKImage() adds attributes for the CMYK image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterCMYKImage method is: % % size_t RegisterCMYKImage(void) % */ ModuleExport size_t RegisterCMYKImage(void) { MagickInfo *entry; entry=SetMagickInfo("CMYK"); entry->decoder=(DecodeImageHandler *) ReadCMYKImage; entry->encoder=(EncodeImageHandler *) WriteCMYKImage; entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->description=ConstantString("Raw cyan, magenta, yellow, and black " "samples"); entry->module=ConstantString("CMYK"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("CMYKA"); entry->decoder=(DecodeImageHandler *) ReadCMYKImage; entry->encoder=(EncodeImageHandler *) WriteCMYKImage; entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->description=ConstantString("Raw cyan, magenta, yellow, black, and " "alpha samples"); entry->module=ConstantString("CMYK"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCMYKImage() removes format registrations made by the % CMYK module from the list of supported formats. % % The format of the UnregisterCMYKImage method is: % % UnregisterCMYKImage(void) % */ ModuleExport void UnregisterCMYKImage(void) { (void) UnregisterMagickInfo("CMYK"); (void) UnregisterMagickInfo("CMYKA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteCMYKImage() writes an image to a file in cyan, magenta, yellow, and % black,rasterfile format. % % The format of the WriteCMYKImage method is: % % MagickBooleanType WriteCMYKImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteCMYKImage(const ImageInfo *image_info, Image *image) { MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; ssize_t count, y; size_t length; unsigned char *pixels; /* Allocate memory for pixels. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image_info->interlace != PartitionInterlace) { /* Open output image file. */ status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); } quantum_type=CMYKQuantum; if (LocaleCompare(image_info->magick,"CMYKA") == 0) { quantum_type=CMYKAQuantum; image->matte=MagickTrue; } scene=0; do { /* Convert MIFF to CMYK raster pixels. */ if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); if ((LocaleCompare(image_info->magick,"CMYKA") == 0) && (image->matte == MagickFalse)) (void) SetImageAlphaChannel(image,ResetAlphaChannel); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: CMYKCMYKCMYKCMYKCMYKCMYK... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; 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,length,pixels); if (count != (ssize_t) length) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case LineInterlace: { /* Line interlacing: CCC...MMM...YYY...KKK...CCC...MMM...YYY...KKK... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,CyanQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,MagentaQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,YellowQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlackQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; if (quantum_type == CMYKAQuantum) { length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: CCCCCC...MMMMMM...YYYYYY...KKKKKK... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,CyanQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,MagentaQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,YellowQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,3,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlackQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,4,6); if (status == MagickFalse) break; } if (quantum_type == CMYKAQuantum) { for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,5,6); if (status == MagickFalse) break; } } if (image_info->interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: CCCCCC..., MMMMMM..., YYYYYY..., KKKKKK... */ AppendImageFormat("C",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,CyanQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,6); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("M",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,MagentaQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,6); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,YellowQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,3,6); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("K",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlackQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,4,6); if (status == MagickFalse) break; } if (quantum_type == CMYKAQuantum) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode : AppendBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,5,6); if (status == MagickFalse) break; } } (void) CloseBlob(image); (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,6,6); if (status == MagickFalse) break; } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4787_8
crossvul-cpp_data_bad_345_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_345_8
crossvul-cpp_data_bad_2192_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2014 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: The typical suspects | | Pollita <pollita@php.net> | | Marcus Boerger <helly@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* {{{ includes */ #include "php.h" #include "php_network.h" #if HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef PHP_WIN32 # include "win32/inet.h" # include <winsock2.h> # include <windows.h> # include <Ws2tcpip.h> #else /* This holds good for NetWare too, both for Winsock and Berkeley sockets */ #include <netinet/in.h> #if HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include <netdb.h> #ifdef _OSD_POSIX #undef STATUS #undef T_UNSPEC #endif #if HAVE_ARPA_NAMESER_H #ifdef DARWIN # define BIND_8_COMPAT 1 #endif #include <arpa/nameser.h> #endif #if HAVE_RESOLV_H #include <resolv.h> #endif #ifdef HAVE_DNS_H #include <dns.h> #endif #endif /* Borrowed from SYS/SOCKET.H */ #if defined(NETWARE) && defined(USE_WINSOCK) #define AF_INET 2 /* internetwork: UDP, TCP, etc. */ #endif #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 255 #endif /* For the local hostname obtained via gethostname which is different from the dns-related MAXHOSTNAMELEN constant above */ #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 255 #endif #include "php_dns.h" /* type compat */ #ifndef DNS_T_A #define DNS_T_A 1 #endif #ifndef DNS_T_NS #define DNS_T_NS 2 #endif #ifndef DNS_T_CNAME #define DNS_T_CNAME 5 #endif #ifndef DNS_T_SOA #define DNS_T_SOA 6 #endif #ifndef DNS_T_PTR #define DNS_T_PTR 12 #endif #ifndef DNS_T_HINFO #define DNS_T_HINFO 13 #endif #ifndef DNS_T_MINFO #define DNS_T_MINFO 14 #endif #ifndef DNS_T_MX #define DNS_T_MX 15 #endif #ifndef DNS_T_TXT #define DNS_T_TXT 16 #endif #ifndef DNS_T_AAAA #define DNS_T_AAAA 28 #endif #ifndef DNS_T_SRV #define DNS_T_SRV 33 #endif #ifndef DNS_T_NAPTR #define DNS_T_NAPTR 35 #endif #ifndef DNS_T_A6 #define DNS_T_A6 38 #endif #ifndef DNS_T_ANY #define DNS_T_ANY 255 #endif /* }}} */ static char *php_gethostbyaddr(char *ip); static char *php_gethostbyname(char *name); #ifdef HAVE_GETHOSTNAME /* {{{ proto string gethostname() Get the host name of the current machine */ PHP_FUNCTION(gethostname) { char buf[HOST_NAME_MAX]; if (zend_parse_parameters_none() == FAILURE) { return; } if (gethostname(buf, sizeof(buf) - 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to fetch host [%d]: %s", errno, strerror(errno)); RETURN_FALSE; } RETURN_STRING(buf, 1); } /* }}} */ #endif /* TODO: Reimplement the gethostby* functions using the new winxp+ API, in dns_win32.c, then we can have a dns.c, dns_unix.c and dns_win32.c instead of a messy dns.c full of #ifdef */ /* {{{ proto string gethostbyaddr(string ip_address) Get the Internet host name corresponding to a given IP address */ PHP_FUNCTION(gethostbyaddr) { char *addr; int addr_len; char *hostname; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &addr, &addr_len) == FAILURE) { return; } hostname = php_gethostbyaddr(addr); if (hostname == NULL) { #if HAVE_IPV6 && HAVE_INET_PTON php_error_docref(NULL TSRMLS_CC, E_WARNING, "Address is not a valid IPv4 or IPv6 address"); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Address is not in a.b.c.d form"); #endif RETVAL_FALSE; } else { RETVAL_STRING(hostname, 0); } } /* }}} */ /* {{{ php_gethostbyaddr */ static char *php_gethostbyaddr(char *ip) { #if HAVE_IPV6 && HAVE_INET_PTON struct in6_addr addr6; #endif struct in_addr addr; struct hostent *hp; #if HAVE_IPV6 && HAVE_INET_PTON if (inet_pton(AF_INET6, ip, &addr6)) { hp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6); } else if (inet_pton(AF_INET, ip, &addr)) { hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET); } else { return NULL; } #else addr.s_addr = inet_addr(ip); if (addr.s_addr == -1) { return NULL; } hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET); #endif if (!hp || hp->h_name == NULL || hp->h_name[0] == '\0') { return estrdup(ip); } return estrdup(hp->h_name); } /* }}} */ /* {{{ proto string gethostbyname(string hostname) Get the IP address corresponding to a given Internet host name */ PHP_FUNCTION(gethostbyname) { char *hostname; int hostname_len; char *addr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hostname, &hostname_len) == FAILURE) { return; } addr = php_gethostbyname(hostname); RETVAL_STRING(addr, 0); } /* }}} */ /* {{{ proto array gethostbynamel(string hostname) Return a list of IP addresses that a given hostname resolves to. */ PHP_FUNCTION(gethostbynamel) { char *hostname; int hostname_len; struct hostent *hp; struct in_addr in; int i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hostname, &hostname_len) == FAILURE) { return; } hp = gethostbyname(hostname); if (hp == NULL || hp->h_addr_list == NULL) { RETURN_FALSE; } array_init(return_value); for (i = 0 ; hp->h_addr_list[i] != 0 ; i++) { in = *(struct in_addr *) hp->h_addr_list[i]; add_next_index_string(return_value, inet_ntoa(in), 1); } } /* }}} */ /* {{{ php_gethostbyname */ static char *php_gethostbyname(char *name) { struct hostent *hp; struct in_addr in; hp = gethostbyname(name); if (!hp || !*(hp->h_addr_list)) { return estrdup(name); } memcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr)); return estrdup(inet_ntoa(in)); } /* }}} */ #if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) # define PHP_DNS_NUM_TYPES 12 /* Number of DNS Types Supported by PHP currently */ # define PHP_DNS_A 0x00000001 # define PHP_DNS_NS 0x00000002 # define PHP_DNS_CNAME 0x00000010 # define PHP_DNS_SOA 0x00000020 # define PHP_DNS_PTR 0x00000800 # define PHP_DNS_HINFO 0x00001000 # define PHP_DNS_MX 0x00004000 # define PHP_DNS_TXT 0x00008000 # define PHP_DNS_A6 0x01000000 # define PHP_DNS_SRV 0x02000000 # define PHP_DNS_NAPTR 0x04000000 # define PHP_DNS_AAAA 0x08000000 # define PHP_DNS_ANY 0x10000000 # define PHP_DNS_ALL (PHP_DNS_A|PHP_DNS_NS|PHP_DNS_CNAME|PHP_DNS_SOA|PHP_DNS_PTR|PHP_DNS_HINFO|PHP_DNS_MX|PHP_DNS_TXT|PHP_DNS_A6|PHP_DNS_SRV|PHP_DNS_NAPTR|PHP_DNS_AAAA) #endif /* HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) */ /* Note: These functions are defined in ext/standard/dns_win32.c for Windows! */ #if !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) #ifndef HFIXEDSZ #define HFIXEDSZ 12 /* fixed data in header <arpa/nameser.h> */ #endif /* HFIXEDSZ */ #ifndef QFIXEDSZ #define QFIXEDSZ 4 /* fixed data in query <arpa/nameser.h> */ #endif /* QFIXEDSZ */ #undef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 1024 #ifndef MAXRESOURCERECORDS #define MAXRESOURCERECORDS 64 #endif /* MAXRESOURCERECORDS */ typedef union { HEADER qb1; u_char qb2[65536]; } querybuf; /* just a hack to free resources allocated by glibc in __res_nsend() * See also: * res_thread_freeres() in glibc/resolv/res_init.c * __libc_res_nsend() in resolv/res_send.c * */ #if defined(__GLIBC__) && !defined(HAVE_DEPRECATED_DNS_FUNCS) #define php_dns_free_res(__res__) _php_dns_free_res(__res__) static void _php_dns_free_res(struct __res_state res) { /* {{{ */ int ns; for (ns = 0; ns < MAXNS; ns++) { if (res._u._ext.nsaddrs[ns] != NULL) { free (res._u._ext.nsaddrs[ns]); res._u._ext.nsaddrs[ns] = NULL; } } } /* }}} */ #else #define php_dns_free_res(__res__) #endif /* {{{ proto bool dns_check_record(string host [, string type]) Check DNS records corresponding to a given Internet host name or IP address */ PHP_FUNCTION(dns_check_record) { #ifndef MAXPACKET #define MAXPACKET 8192 /* max packet size used internally by BIND */ #endif u_char ans[MAXPACKET]; char *hostname, *rectype = NULL; int hostname_len, rectype_len = 0; int type = T_MX, i; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) { return; } if (hostname_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Host cannot be empty"); RETURN_FALSE; } if (rectype) { if (!strcasecmp("A", rectype)) type = T_A; else if (!strcasecmp("NS", rectype)) type = DNS_T_NS; else if (!strcasecmp("MX", rectype)) type = DNS_T_MX; else if (!strcasecmp("PTR", rectype)) type = DNS_T_PTR; else if (!strcasecmp("ANY", rectype)) type = DNS_T_ANY; else if (!strcasecmp("SOA", rectype)) type = DNS_T_SOA; else if (!strcasecmp("TXT", rectype)) type = DNS_T_TXT; else if (!strcasecmp("CNAME", rectype)) type = DNS_T_CNAME; else if (!strcasecmp("AAAA", rectype)) type = DNS_T_AAAA; else if (!strcasecmp("SRV", rectype)) type = DNS_T_SRV; else if (!strcasecmp("NAPTR", rectype)) type = DNS_T_NAPTR; else if (!strcasecmp("A6", rectype)) type = DNS_T_A6; else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%s' not supported", rectype); RETURN_FALSE; } } #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { RETURN_FALSE; } #else res_init(); #endif RETVAL_TRUE; i = php_dns_search(handle, hostname, C_IN, type, ans, sizeof(ans)); if (i < 0) { RETVAL_FALSE; } php_dns_free_handle(handle); } /* }}} */ #if HAVE_FULL_DNS_FUNCS /* {{{ php_parserr */ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) { u_short type, class, dlen; u_long ttl; long n, i; u_short s; u_char *tp, *p; char name[MAXHOSTNAMELEN]; int have_v6_break = 0, in_v6_break = 0; *subarray = NULL; n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2); if (n < 0) { return NULL; } cp += n; GETSHORT(type, cp); GETSHORT(class, cp); GETLONG(ttl, cp); GETSHORT(dlen, cp); if (type_to_fetch != T_ANY && type != type_to_fetch) { cp += dlen; return cp; } if (!store) { cp += dlen; return cp; } ALLOC_INIT_ZVAL(*subarray); array_init(*subarray); add_assoc_string(*subarray, "host", name, 1); add_assoc_string(*subarray, "class", "IN", 1); add_assoc_long(*subarray, "ttl", ttl); if (raw) { add_assoc_long(*subarray, "type", type); add_assoc_stringl(*subarray, "data", (char*) cp, (uint) dlen, 1); cp += dlen; return cp; } switch (type) { case DNS_T_A: add_assoc_string(*subarray, "type", "A", 1); snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); add_assoc_string(*subarray, "ip", name, 1); cp += dlen; break; case DNS_T_MX: add_assoc_string(*subarray, "type", "MX", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "pri", n); /* no break; */ case DNS_T_CNAME: if (type == DNS_T_CNAME) { add_assoc_string(*subarray, "type", "CNAME", 1); } /* no break; */ case DNS_T_NS: if (type == DNS_T_NS) { add_assoc_string(*subarray, "type", "NS", 1); } /* no break; */ case DNS_T_PTR: if (type == DNS_T_PTR) { add_assoc_string(*subarray, "type", "PTR", 1); } n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "target", name, 1); break; case DNS_T_HINFO: /* See RFC 1010 for values */ add_assoc_string(*subarray, "type", "HINFO", 1); n = *cp & 0xFF; cp++; add_assoc_stringl(*subarray, "cpu", (char*)cp, n, 1); cp += n; n = *cp & 0xFF; cp++; add_assoc_stringl(*subarray, "os", (char*)cp, n, 1); cp += n; break; case DNS_T_TXT: { int ll = 0; zval *entries = NULL; add_assoc_string(*subarray, "type", "TXT", 1); tp = emalloc(dlen + 1); MAKE_STD_ZVAL(entries); array_init(entries); while (ll < dlen) { n = cp[ll]; memcpy(tp + ll , cp + ll + 1, n); add_next_index_stringl(entries, cp + ll + 1, n, 1); ll = ll + n + 1; } tp[dlen] = '\0'; cp += dlen; add_assoc_stringl(*subarray, "txt", tp, (dlen>0)?dlen - 1:0, 0); add_assoc_zval(*subarray, "entries", entries); } break; case DNS_T_SOA: add_assoc_string(*subarray, "type", "SOA", 1); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "mname", name, 1); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "rname", name, 1); GETLONG(n, cp); add_assoc_long(*subarray, "serial", n); GETLONG(n, cp); add_assoc_long(*subarray, "refresh", n); GETLONG(n, cp); add_assoc_long(*subarray, "retry", n); GETLONG(n, cp); add_assoc_long(*subarray, "expire", n); GETLONG(n, cp); add_assoc_long(*subarray, "minimum-ttl", n); break; case DNS_T_AAAA: tp = (u_char*)name; for(i=0; i < 8; i++) { GETSHORT(s, cp); if (s != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } tp += sprintf((char*)tp,"%x",s); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } } if (have_v6_break && in_v6_break) { tp[0] = ':'; tp++; } tp[0] = '\0'; add_assoc_string(*subarray, "type", "AAAA", 1); add_assoc_string(*subarray, "ipv6", name, 1); break; case DNS_T_A6: p = cp; add_assoc_string(*subarray, "type", "A6", 1); n = ((int)cp[0]) & 0xFF; cp++; add_assoc_long(*subarray, "masklen", n); tp = (u_char*)name; if (n > 15) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } if (n % 16 > 8) { /* Partial short */ if (cp[0] != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } sprintf((char*)tp, "%x", cp[0] & 0xFF); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } cp++; } for (i = (n + 8) / 16; i < 8; i++) { GETSHORT(s, cp); if (s != 0) { if (tp > (u_char *)name) { in_v6_break = 0; tp[0] = ':'; tp++; } tp += sprintf((char*)tp,"%x",s); } else { if (!have_v6_break) { have_v6_break = 1; in_v6_break = 1; tp[0] = ':'; tp++; } else if (!in_v6_break) { tp[0] = ':'; tp++; tp[0] = '0'; tp++; } } } if (have_v6_break && in_v6_break) { tp[0] = ':'; tp++; } tp[0] = '\0'; add_assoc_string(*subarray, "ipv6", name, 1); if (cp < p + dlen) { n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "chain", name, 1); } break; case DNS_T_SRV: add_assoc_string(*subarray, "type", "SRV", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "pri", n); GETSHORT(n, cp); add_assoc_long(*subarray, "weight", n); GETSHORT(n, cp); add_assoc_long(*subarray, "port", n); n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "target", name, 1); break; case DNS_T_NAPTR: add_assoc_string(*subarray, "type", "NAPTR", 1); GETSHORT(n, cp); add_assoc_long(*subarray, "order", n); GETSHORT(n, cp); add_assoc_long(*subarray, "pref", n); n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "flags", (char*)++cp, n, 1); cp += n; n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "services", (char*)++cp, n, 1); cp += n; n = (cp[0] & 0xFF); add_assoc_stringl(*subarray, "regex", (char*)++cp, n, 1); cp += n; n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); if (n < 0) { return NULL; } cp += n; add_assoc_string(*subarray, "replacement", name, 1); break; default: zval_ptr_dtor(subarray); *subarray = NULL; cp += dlen; break; } return cp; } /* }}} */ /* {{{ proto array|false dns_get_record(string hostname [, int type[, array authns, array addtl]]) Get any Resource Record corresponding to a given Internet host name */ PHP_FUNCTION(dns_get_record) { char *hostname; int hostname_len; long type_param = PHP_DNS_ANY; zval *authns = NULL, *addtl = NULL; int type_to_fetch; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif HEADER *hp; querybuf answer; u_char *cp = NULL, *end = NULL; int n, qd, an, ns = 0, ar = 0; int type, first_query = 1, store_results = 1; zend_bool raw = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz!z!b", &hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) { return; } if (authns) { zval_dtor(authns); array_init(authns); } if (addtl) { zval_dtor(addtl); array_init(addtl); } if (!raw) { if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%ld' not supported", type_param); RETURN_FALSE; } } else { if ((type_param < 1) || (type_param > 0xFFFF)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Numeric DNS record type must be between 1 and 65535, '%ld' given", type_param); RETURN_FALSE; } } /* Initialize the return array */ array_init(return_value); /* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 ) * If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 ) * store_results is used to skip storing the results retrieved in step * NUMTYPES+1 when results were already fetched. * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 ) * - In case of raw mode, we query only the requestd type instead of looping type by type * before going with the additional info stuff. */ if (raw) { type = -1; } else if (type_param == PHP_DNS_ANY) { type = PHP_DNS_NUM_TYPES + 1; } else { type = 0; } for ( ; type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query; type++ ) { first_query = 0; switch (type) { case -1: /* raw */ type_to_fetch = type_param; /* skip over the rest and go directly to additional records */ type = PHP_DNS_NUM_TYPES - 1; break; case 0: type_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0; break; case 1: type_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0; break; case 2: type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0; break; case 3: type_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0; break; case 4: type_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0; break; case 5: type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0; break; case 6: type_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0; break; case 7: type_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0; break; case 8: type_to_fetch = type_param&PHP_DNS_AAAA ? DNS_T_AAAA : 0; break; case 9: type_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0; break; case 10: type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0; break; case 11: type_to_fetch = type_param&PHP_DNS_A6 ? DNS_T_A6 : 0; break; case PHP_DNS_NUM_TYPES: store_results = 0; continue; default: case (PHP_DNS_NUM_TYPES + 1): type_to_fetch = DNS_T_ANY; break; } if (type_to_fetch) { #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { zval_dtor(return_value); RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { zval_dtor(return_value); RETURN_FALSE; } #else res_init(); #endif n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer); if (n < 0) { php_dns_free_handle(handle); continue; } cp = answer.qb2 + HFIXEDSZ; end = answer.qb2 + n; hp = (HEADER *)&answer; qd = ntohs(hp->qdcount); an = ntohs(hp->ancount); ns = ntohs(hp->nscount); ar = ntohs(hp->arcount); /* Skip QD entries, they're only used by dn_expand later on */ while (qd-- > 0) { n = dn_skipname(cp, end); if (n < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse DNS data received"); zval_dtor(return_value); php_dns_free_handle(handle); RETURN_FALSE; } cp += n + QFIXEDSZ; } /* YAY! Our real answers! */ while (an-- && cp && cp < end) { zval *retval; cp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval); if (retval != NULL && store_results) { add_next_index_zval(return_value, retval); } } if (authns || addtl) { /* List of Authoritative Name Servers * Process when only requesting addtl so that we can skip through the section */ while (ns-- > 0 && cp && cp < end) { zval *retval = NULL; cp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval); if (retval != NULL) { add_next_index_zval(authns, retval); } } } if (addtl) { /* Additional records associated with authoritative name servers */ while (ar-- > 0 && cp && cp < end) { zval *retval = NULL; cp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval); if (retval != NULL) { add_next_index_zval(addtl, retval); } } } php_dns_free_handle(handle); } } } /* }}} */ /* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight]) Get MX records corresponding to a given Internet host name */ PHP_FUNCTION(dns_get_mx) { char *hostname; int hostname_len; zval *mx_list, *weight_list = NULL; int count, qdc; u_short type, weight; u_char ans[MAXPACKET]; char buf[MAXHOSTNAMELEN]; HEADER *hp; u_char *cp, *end; int i; #if defined(HAVE_DNS_SEARCH) struct sockaddr_storage from; uint32_t fromsize = sizeof(from); dns_handle_t handle; #elif defined(HAVE_RES_NSEARCH) struct __res_state state; struct __res_state *handle = &state; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) { return; } zval_dtor(mx_list); array_init(mx_list); if (weight_list) { zval_dtor(weight_list); array_init(weight_list); } #if defined(HAVE_DNS_SEARCH) handle = dns_open(NULL); if (handle == NULL) { RETURN_FALSE; } #elif defined(HAVE_RES_NSEARCH) memset(&state, 0, sizeof(state)); if (res_ninit(handle)) { RETURN_FALSE; } #else res_init(); #endif i = php_dns_search(handle, hostname, C_IN, DNS_T_MX, (u_char *)&ans, sizeof(ans)); if (i < 0) { RETURN_FALSE; } if (i > (int)sizeof(ans)) { i = sizeof(ans); } hp = (HEADER *)&ans; cp = (u_char *)&ans + HFIXEDSZ; end = (u_char *)&ans +i; for (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) { if ((i = dn_skipname(cp, end)) < 0 ) { php_dns_free_handle(handle); RETURN_FALSE; } } count = ntohs((unsigned short)hp->ancount); while (--count >= 0 && cp < end) { if ((i = dn_skipname(cp, end)) < 0 ) { php_dns_free_handle(handle); RETURN_FALSE; } cp += i; GETSHORT(type, cp); cp += INT16SZ + INT32SZ; GETSHORT(i, cp); if (type != DNS_T_MX) { cp += i; continue; } GETSHORT(weight, cp); if ((i = dn_expand(ans, end, cp, buf, sizeof(buf)-1)) < 0) { php_dns_free_handle(handle); RETURN_FALSE; } cp += i; add_next_index_string(mx_list, buf, 1); if (weight_list) { add_next_index_long(weight_list, weight); } } php_dns_free_handle(handle); RETURN_TRUE; } /* }}} */ #endif /* HAVE_FULL_DNS_FUNCS */ #endif /* !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */ #if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) PHP_MINIT_FUNCTION(dns) { REGISTER_LONG_CONSTANT("DNS_A", PHP_DNS_A, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_NS", PHP_DNS_NS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_CNAME", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_SOA", PHP_DNS_SOA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_PTR", PHP_DNS_PTR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_HINFO", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_MX", PHP_DNS_MX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_TXT", PHP_DNS_TXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_SRV", PHP_DNS_SRV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_NAPTR", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_AAAA", PHP_DNS_AAAA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_A6", PHP_DNS_A6, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_ANY", PHP_DNS_ANY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DNS_ALL", PHP_DNS_ALL, CONST_CS | CONST_PERSISTENT); return SUCCESS; } #endif /* HAVE_FULL_DNS_FUNCS */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2192_0
crossvul-cpp_data_bad_342_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_0
crossvul-cpp_data_bad_346_5
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Initially written by David Mattes <david.mattes@boeing.com> */ /* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #define MANU_ID "Gemplus" #define APPLET_NAME "GemSAFE V1" #define DRIVER_SERIAL_NUMBER "v0.9" #define GEMSAFE_APP_PATH "3F001600" #define GEMSAFE_PATH "3F0016000004" /* Apparently, the Applet max read "quanta" is 248 bytes * Gemalto ClassicClient reads files in chunks of 238 bytes */ #define GEMSAFE_READ_QUANTUM 248 #define GEMSAFE_MAX_OBJLEN 28672 int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *); static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags); static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags); static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags); typedef struct cdata_st { char *label; int authority; const char *path; size_t index; size_t count; const char *id; int obj_flags; } cdata; const unsigned int gemsafe_cert_max = 12; cdata gemsafe_cert[] = { {"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE}, }; typedef struct pdata_st { const u8 atr[SC_MAX_ATR_SIZE]; const size_t atr_len; const char *id; const char *label; const char *path; const int ref; const int type; const unsigned int maxlen; const unsigned int minlen; const int flags; const int tries_left; const char pad_char; const int obj_flags; } pindata; const unsigned int gemsafe_pin_max = 2; const pindata gemsafe_pin[] = { /* ATR-specific PIN policies, first match found is used: */ { {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65, 0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC, 8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }, /* default PIN policy comes last: */ { { 0 }, 0, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD, 16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE } }; typedef struct prdata_st { const char *id; char *label; unsigned int modulus_len; int usage; const char *path; int ref; const char *auth_id; int obj_flags; } prdata; #define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION #define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP #define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP | \ SC_PKCS15_PRKEY_USAGE_SIGN prdata gemsafe_prkeys[] = { { "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE}, }; static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } static int gemsafe_detect_card( sc_pkcs15_card_t *p15card) { if (strcmp(p15card->card->name, "GemSAFE V1")) return SC_ERROR_WRONG_CARD; return SC_SUCCESS; } static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card) { int r; unsigned int i; struct sc_path path; struct sc_file *file = NULL; struct sc_card *card = p15card->card; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_log(p15card->card->ctx, "Setting pkcs15 parameters"); if (p15card->tokeninfo->label) free(p15card->tokeninfo->label); p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1); if (!p15card->tokeninfo->label) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->label, APPLET_NAME); if (p15card->tokeninfo->serial_number) free(p15card->tokeninfo->serial_number); p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1); if (!p15card->tokeninfo->serial_number) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER); /* the GemSAFE applet version number */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); /* Manual says Le=0x05, but should be 0x08 to return full version number */ apdu.le = 0x08; apdu.lc = 0; apdu.datalen = 0; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* the manufacturer ID, in this case GemPlus */ if (p15card->tokeninfo->manufacturer_id) free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1); if (!p15card->tokeninfo->manufacturer_id) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID); /* determine allocated key containers and length of certificates */ r = gemsafe_get_cert_len(card); if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* set certs */ sc_log(p15card->card->ctx, "Setting certificates"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; if (gemsafe_cert[i].label == NULL) continue; sc_format_path(gemsafe_cert[i].path, &path); sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id); path.index = gemsafe_cert[i].index; path.count = gemsafe_cert[i].count; sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, gemsafe_cert[i].authority, &path, &p15Id, gemsafe_cert[i].label, gemsafe_cert[i].obj_flags); } /* set gemsafe_pin */ sc_log(p15card->card->ctx, "Setting PIN"); for (i=0; i < gemsafe_pin_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id); sc_format_path(gemsafe_pin[i].path, &path); if (gemsafe_pin[i].atr_len == 0 || (gemsafe_pin[i].atr_len == p15card->card->atr.len && memcmp(p15card->card->atr.value, gemsafe_pin[i].atr, p15card->card->atr.len) == 0)) { sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label, &path, gemsafe_pin[i].ref, gemsafe_pin[i].type, gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen, gemsafe_pin[i].flags, gemsafe_pin[i].tries_left, gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags); break; } }; /* set private keys */ sc_log(p15card->card->ctx, "Setting private keys"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id, authId, *pauthId; struct sc_path path; int key_ref = 0x03; if (gemsafe_prkeys[i].label == NULL) continue; sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id); if (gemsafe_prkeys[i].auth_id) { sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId); pauthId = &authId; } else pauthId = NULL; sc_format_path(gemsafe_prkeys[i].path, &path); /* * The key ref may be different for different sites; * by adding flags=n where the low order 4 bits can be * the key ref we can force it. */ if ( p15card->card->flags & 0x0F) { key_ref = p15card->card->flags & 0x0F; sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Overriding key_ref %d with %d\n", gemsafe_prkeys[i].ref, key_ref); } else key_ref = gemsafe_prkeys[i].ref; sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label, SC_PKCS15_TYPE_PRKEY_RSA, gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage, &path, key_ref, pauthId, gemsafe_prkeys[i].obj_flags); } /* select the application DF */ sc_log(p15card->card->ctx, "Selecting application DF"); sc_format_path(GEMSAFE_APP_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* set the application DF */ if (p15card->file_app) free(p15card->file_app); p15card->file_app = file; return SC_SUCCESS; } int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_gemsafeV1_init(p15card); else { int r = gemsafe_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_gemsafeV1_init(p15card); } } static sc_pkcs15_df_t * sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type) { sc_pkcs15_df_t *df; sc_file_t *file; int created = 0; while (1) { for (df = p15card->df_list; df; df = df->next) { if (df->type == type) { if (created) df->enumerated = 1; return df; } } assert(created == 0); file = sc_file_new(); if (!file) return NULL; sc_format_path("11001101", &file->path); sc_pkcs15_add_df(p15card, type, &file->path); sc_file_free(file); created++; } } static int sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type, const char *label, void *data, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_object_t *obj; int df_type; obj = calloc(1, sizeof(*obj)); obj->type = type; obj->data = data; if (label) strncpy(obj->label, label, sizeof(obj->label)-1); obj->flags = obj_flags; if (auth_id) obj->auth_id = *auth_id; switch (type & SC_PKCS15_TYPE_CLASS_MASK) { case SC_PKCS15_TYPE_AUTH: df_type = SC_PKCS15_AODF; break; case SC_PKCS15_TYPE_PRKEY: df_type = SC_PKCS15_PRKDF; break; case SC_PKCS15_TYPE_PUBKEY: df_type = SC_PKCS15_PUKDF; break; case SC_PKCS15_TYPE_CERT: df_type = SC_PKCS15_CDF; break; default: sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type); free(obj); return SC_ERROR_INVALID_ARGUMENTS; } obj->df = sc_pkcs15emu_get_df(p15card, df_type); sc_pkcs15_add_object(p15card, obj); return 0; } static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags) { sc_pkcs15_auth_info_t *info; info = calloc(1, sizeof(*info)); if (!info) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; info->auth_method = SC_AC_CHV; info->auth_id = *id; info->attrs.pin.min_length = min_length; info->attrs.pin.max_length = max_length; info->attrs.pin.stored_length = max_length; info->attrs.pin.type = type; info->attrs.pin.reference = ref; info->attrs.pin.flags = flags; info->attrs.pin.pad_char = pad_char; info->tries_left = tries_left; info->logged_in = SC_PIN_STATE_UNKNOWN; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags) { sc_pkcs15_cert_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->authority = authority; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_prkey_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->modulus_length = modulus_length; info->usage = usage; info->native = 1; info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE | SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE | SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE | SC_PKCS15_PRKEY_ACCESS_LOCAL; info->key_reference = ref; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, auth_id, obj_flags); } /* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_5
crossvul-cpp_data_bad_2983_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.h> #include <linux/stringify.h> #include "disasm.h" static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { #define BPF_PROG_TYPE(_id, _name) \ [_id] = & _name ## _verifier_ops, #define BPF_MAP_TYPE(_id, _ops) #include <linux/bpf_types.h> #undef BPF_PROG_TYPE #undef BPF_MAP_TYPE }; /* bpf_check() is a static code analyzer that walks eBPF program * instruction by instruction and updates register/stack state. * All paths of conditional branches are analyzed until 'bpf_exit' insn. * * The first pass is depth-first-search to check that the program is a DAG. * It rejects the following programs: * - larger than BPF_MAXINSNS insns * - if loop is present (detected via back-edge) * - unreachable insns exist (shouldn't be a forest. program = one function) * - out of bounds or malformed jumps * The second pass is all possible path descent from the 1st insn. * Since it's analyzing all pathes through the program, the length of the * analysis is limited to 64k insn, which may be hit even if total number of * insn is less then 4K, but there are too many branches that change stack/regs. * Number of 'branches to be analyzed' is limited to 1k * * On entry to each instruction, each register has a type, and the instruction * changes the types of the registers depending on instruction semantics. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is * copied to R1. * * All registers are 64-bit. * R0 - return register * R1-R5 argument passing registers * R6-R9 callee saved registers * R10 - frame pointer read-only * * At the start of BPF program the register R1 contains a pointer to bpf_context * and has type PTR_TO_CTX. * * Verifier tracks arithmetic operations on pointers in case: * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), * 1st insn copies R10 (which has FRAME_PTR) type into R1 * and 2nd arithmetic instruction is pattern matched to recognize * that it wants to construct a pointer to some element within stack. * So after 2nd insn, the register R1 has type PTR_TO_STACK * (and -20 constant is saved for further stack bounds checking). * Meaning that this reg is a pointer to stack plus known immediate constant. * * Most of the time the registers have SCALAR_VALUE type, which * means the register has some value, but it's not a valid pointer. * (like pointer plus pointer becomes SCALAR_VALUE type) * * When verifier sees load or store instructions the type of base register * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer * types recognized by check_mem_access() function. * * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' * and the range of [ptr, ptr + map's value_size) is accessible. * * registers used to pass values to function calls are checked against * function argument constraints. * * ARG_PTR_TO_MAP_KEY is one of such argument constraints. * It means that the register type passed to this function must be * PTR_TO_STACK and it will be used inside the function as * 'pointer to map element key' * * For example the argument constraints for bpf_map_lookup_elem(): * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, * .arg1_type = ARG_CONST_MAP_PTR, * .arg2_type = ARG_PTR_TO_MAP_KEY, * * ret_type says that this function returns 'pointer to map elem value or null' * function expects 1st argument to be a const pointer to 'struct bpf_map' and * 2nd argument should be a pointer to stack, which will be used inside * the helper function as a pointer to map element key. * * On the kernel side the helper function looks like: * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) * { * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; * void *key = (void *) (unsigned long) r2; * void *value; * * here kernel can access 'key' and 'map' pointers safely, knowing that * [key, key + map->key_size) bytes are valid and were initialized on * the stack of eBPF program. * } * * Corresponding eBPF program may look like: * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), * here verifier looks at prototype of map_lookup_elem() and sees: * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, * Now verifier knows that this map has key of R1->map_ptr->key_size bytes * * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, * Now verifier checks that [R2, R2 + map's key_size) are within stack limits * and were initialized prior to this call. * If it's ok, then verifier allows this BPF_CALL insn and looks at * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function * returns ether pointer to map value or NULL. * * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' * insn, the register holding that pointer in the true branch changes state to * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false * branch. See check_cond_jmp_op(). * * After the call R0 is set to return type of the function and registers R1-R5 * are set to NOT_INIT to indicate that they are no longer readable. */ /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct bpf_verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct bpf_verifier_state st; int insn_idx; int prev_insn_idx; struct bpf_verifier_stack_elem *next; }; #define BPF_COMPLEXITY_LIMIT_INSNS 131072 #define BPF_COMPLEXITY_LIMIT_STACK 1024 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA) struct bpf_call_arg_meta { struct bpf_map *map_ptr; bool raw_mode; bool pkt_access; int regno; int access_size; }; static DEFINE_MUTEX(bpf_verifier_lock); /* log_level controls verbosity level of eBPF verifier. * verbose() is used to dump the verification trace to the log, so the user * can figure out what's wrong with the program */ static __printf(2, 3) void verbose(struct bpf_verifier_env *env, const char *fmt, ...) { struct bpf_verifer_log *log = &env->log; unsigned int n; va_list args; if (!log->level || !log->ubuf || bpf_verifier_log_full(log)) return; va_start(args, fmt); n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); va_end(args); WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, "verifier log line truncated - local buffer too short\n"); n = min(log->len_total - log->len_used - 1, n); log->kbuf[n] = '\0'; if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) log->len_used += n; else log->ubuf = NULL; } static bool type_is_pkt_pointer(enum bpf_reg_type type) { return type == PTR_TO_PACKET || type == PTR_TO_PACKET_META; } /* string representation of 'enum bpf_reg_type' */ static const char * const reg_type_str[] = { [NOT_INIT] = "?", [SCALAR_VALUE] = "inv", [PTR_TO_CTX] = "ctx", [CONST_PTR_TO_MAP] = "map_ptr", [PTR_TO_MAP_VALUE] = "map_value", [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", [PTR_TO_STACK] = "fp", [PTR_TO_PACKET] = "pkt", [PTR_TO_PACKET_META] = "pkt_meta", [PTR_TO_PACKET_END] = "pkt_end", }; static void print_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *state) { struct bpf_reg_state *reg; enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { reg = &state->regs[i]; t = reg->type; if (t == NOT_INIT) continue; verbose(env, " R%d=%s", i, reg_type_str[t]); if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && tnum_is_const(reg->var_off)) { /* reg->off should be 0 for SCALAR_VALUE */ verbose(env, "%lld", reg->var_off.value + reg->off); } else { verbose(env, "(id=%d", reg->id); if (t != SCALAR_VALUE) verbose(env, ",off=%d", reg->off); if (type_is_pkt_pointer(t)) verbose(env, ",r=%d", reg->range); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL) verbose(env, ",ks=%d,vs=%d", reg->map_ptr->key_size, reg->map_ptr->value_size); if (tnum_is_const(reg->var_off)) { /* Typically an immediate SCALAR_VALUE, but * could be a pointer whose offset is too big * for reg->off */ verbose(env, ",imm=%llx", reg->var_off.value); } else { if (reg->smin_value != reg->umin_value && reg->smin_value != S64_MIN) verbose(env, ",smin_value=%lld", (long long)reg->smin_value); if (reg->smax_value != reg->umax_value && reg->smax_value != S64_MAX) verbose(env, ",smax_value=%lld", (long long)reg->smax_value); if (reg->umin_value != 0) verbose(env, ",umin_value=%llu", (unsigned long long)reg->umin_value); if (reg->umax_value != U64_MAX) verbose(env, ",umax_value=%llu", (unsigned long long)reg->umax_value); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, ",var_off=%s", tn_buf); } } verbose(env, ")"); } } for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] == STACK_SPILL) verbose(env, " fp%d=%s", -MAX_BPF_STACK + i * BPF_REG_SIZE, reg_type_str[state->stack[i].spilled_ptr.type]); } verbose(env, "\n"); } static int copy_stack_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { if (!src->stack) return 0; if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) { /* internal bug, make state invalid to reject the program */ memset(dst, 0, sizeof(*dst)); return -EFAULT; } memcpy(dst->stack, src->stack, sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE)); return 0; } /* do_check() starts with zero-sized stack in struct bpf_verifier_state to * make it consume minimal amount of memory. check_stack_write() access from * the program calls into realloc_verifier_state() to grow the stack size. * Note there is a non-zero 'parent' pointer inside bpf_verifier_state * which this function copies over. It points to previous bpf_verifier_state * which is never reallocated */ static int realloc_verifier_state(struct bpf_verifier_state *state, int size, bool copy_old) { u32 old_size = state->allocated_stack; struct bpf_stack_state *new_stack; int slot = size / BPF_REG_SIZE; if (size <= old_size || !size) { if (copy_old) return 0; state->allocated_stack = slot * BPF_REG_SIZE; if (!size && old_size) { kfree(state->stack); state->stack = NULL; } return 0; } new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state), GFP_KERNEL); if (!new_stack) return -ENOMEM; if (copy_old) { if (state->stack) memcpy(new_stack, state->stack, sizeof(*new_stack) * (old_size / BPF_REG_SIZE)); memset(new_stack + old_size / BPF_REG_SIZE, 0, sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE); } state->allocated_stack = slot * BPF_REG_SIZE; kfree(state->stack); state->stack = new_stack; return 0; } static void free_verifier_state(struct bpf_verifier_state *state, bool free_self) { kfree(state->stack); if (free_self) kfree(state); } /* copy verifier state from src to dst growing dst stack space * when necessary to accommodate larger src stack */ static int copy_verifier_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) { int err; err = realloc_verifier_state(dst, src->allocated_stack, false); if (err) return err; memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack)); return copy_stack_state(dst, src); } static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem, *head = env->head; int err; if (env->head == NULL) return -ENOENT; if (cur) { err = copy_verifier_state(cur, &head->st); if (err) return err; } if (insn_idx) *insn_idx = head->insn_idx; if (prev_insn_idx) *prev_insn_idx = head->prev_insn_idx; elem = head->next; free_verifier_state(&head->st, false); kfree(head); env->head = elem; env->stack_size--; return 0; } static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } #define CALLER_SAVED_REGS 6 static const int caller_saved[CALLER_SAVED_REGS] = { BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 }; static void __mark_reg_not_init(struct bpf_reg_state *reg); /* Mark the unknown part of a register (variable offset or scalar value) as * known to have the value @imm. */ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) { reg->id = 0; reg->var_off = tnum_const(imm); reg->smin_value = (s64)imm; reg->smax_value = (s64)imm; reg->umin_value = imm; reg->umax_value = imm; } /* Mark the 'variable offset' part of a register as zero. This should be * used only on registers holding a pointer type. */ static void __mark_reg_known_zero(struct bpf_reg_state *reg) { __mark_reg_known(reg, 0); } static void mark_reg_known_zero(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_known_zero(regs + regno); } static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) { return type_is_pkt_pointer(reg->type); } static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) { return reg_is_pkt_pointer(reg) || reg->type == PTR_TO_PACKET_END; } /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, enum bpf_reg_type which) { /* The register can already have a range from prior markings. * This is fine as long as it hasn't been advanced from its * origin. */ return reg->type == which && reg->id == 0 && reg->off == 0 && tnum_equals_const(reg->var_off, 0); } /* Attempts to improve min/max values based on var_off information */ static void __update_reg_bounds(struct bpf_reg_state *reg) { /* min signed is max(sign bit) | min(other bits) */ reg->smin_value = max_t(s64, reg->smin_value, reg->var_off.value | (reg->var_off.mask & S64_MIN)); /* max signed is min(sign bit) | max(other bits) */ reg->smax_value = min_t(s64, reg->smax_value, reg->var_off.value | (reg->var_off.mask & S64_MAX)); reg->umin_value = max(reg->umin_value, reg->var_off.value); reg->umax_value = min(reg->umax_value, reg->var_off.value | reg->var_off.mask); } /* Uses signed min/max values to inform unsigned, and vice-versa */ static void __reg_deduce_bounds(struct bpf_reg_state *reg) { /* Learn sign from signed bounds. * If we cannot cross the sign boundary, then signed and unsigned bounds * are the same, so combine. This works even in the negative case, e.g. * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. */ if (reg->smin_value >= 0 || reg->smax_value < 0) { reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); return; } /* Learn sign from unsigned bounds. Signed bounds cross the sign * boundary, so we must be careful. */ if ((s64)reg->umax_value >= 0) { /* Positive. We can't learn anything from the smin, but smax * is positive, hence safe. */ reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); } else if ((s64)reg->umin_value < 0) { /* Negative. We can't learn anything from the smax, but smin * is negative, hence safe. */ reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); reg->smax_value = reg->umax_value; } } /* Attempts to improve var_off based on unsigned min/max information */ static void __reg_bound_offset(struct bpf_reg_state *reg) { reg->var_off = tnum_intersect(reg->var_off, tnum_range(reg->umin_value, reg->umax_value)); } /* Reset the min/max bounds of a register */ static void __mark_reg_unbounded(struct bpf_reg_state *reg) { reg->smin_value = S64_MIN; reg->smax_value = S64_MAX; reg->umin_value = 0; reg->umax_value = U64_MAX; } /* Mark a register as having a completely unknown (scalar) value. */ static void __mark_reg_unknown(struct bpf_reg_state *reg) { reg->type = SCALAR_VALUE; reg->id = 0; reg->off = 0; reg->var_off = tnum_unknown; __mark_reg_unbounded(reg); } static void mark_reg_unknown(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_unknown(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_unknown(regs + regno); } static void __mark_reg_not_init(struct bpf_reg_state *reg) { __mark_reg_unknown(reg); reg->type = NOT_INIT; } static void mark_reg_not_init(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno) { if (WARN_ON(regno >= MAX_BPF_REG)) { verbose(env, "mark_reg_not_init(regs, %u)\n", regno); /* Something bad happened, let's kill all regs */ for (regno = 0; regno < MAX_BPF_REG; regno++) __mark_reg_not_init(regs + regno); return; } __mark_reg_not_init(regs + regno); } static void init_reg_state(struct bpf_verifier_env *env, struct bpf_reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { mark_reg_not_init(env, regs, i); regs[i].live = REG_LIVE_NONE; } /* frame pointer */ regs[BPF_REG_FP].type = PTR_TO_STACK; mark_reg_known_zero(env, regs, BPF_REG_FP); /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; mark_reg_known_zero(env, regs, BPF_REG_1); } enum reg_arg_type { SRC_OP, /* register is used as source operand */ DST_OP, /* register is used as destination operand */ DST_OP_NO_MARK /* same as above, check only, don't mark */ }; static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno) { struct bpf_verifier_state *parent = state->parent; if (regno == BPF_REG_FP) /* We don't need to worry about FP liveness because it's read-only */ return; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->regs[regno].live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->regs[regno].live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, enum reg_arg_type t) { struct bpf_reg_state *regs = env->cur_state->regs; if (regno >= MAX_BPF_REG) { verbose(env, "R%d is invalid\n", regno); return -EINVAL; } if (t == SRC_OP) { /* check whether register used as source operand can be read */ if (regs[regno].type == NOT_INIT) { verbose(env, "R%d !read_ok\n", regno); return -EACCES; } mark_reg_read(env->cur_state, regno); } else { /* check whether register used as dest operand can be written to */ if (regno == BPF_REG_FP) { verbose(env, "frame pointer is read only\n"); return -EACCES; } regs[regno].live |= REG_LIVE_WRITTEN; if (t == DST_OP) mark_reg_unknown(env, regs, regno); } return 0; } static bool is_spillable_regtype(enum bpf_reg_type type) { switch (type) { case PTR_TO_MAP_VALUE: case PTR_TO_MAP_VALUE_OR_NULL: case PTR_TO_STACK: case PTR_TO_CTX: case PTR_TO_PACKET: case PTR_TO_PACKET_META: case PTR_TO_PACKET_END: case CONST_PTR_TO_MAP: return true; default: return false; } } /* check_stack_read/write functions track spill/fill of registers, * stack boundary and alignment are checked in check_mem_access() */ static int check_stack_write(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE), true); if (err) return err; /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (!env->allow_ptr_leaks && state->stack[spi].slot_type[0] == STACK_SPILL && size != BPF_REG_SIZE) { verbose(env, "attempt to corrupt spilled pointer on stack\n"); return -EACCES; } if (value_regno >= 0 && is_spillable_regtype(state->regs[value_regno].type)) { /* register containing pointer is being spilled into stack */ if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } /* save register state */ state->stack[spi].spilled_ptr = state->regs[value_regno]; state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; for (i = 0; i < BPF_REG_SIZE; i++) state->stack[spi].slot_type[i] = STACK_SPILL; } else { /* regular write of data into stack */ state->stack[spi].spilled_ptr = (struct bpf_reg_state) {}; for (i = 0; i < size; i++) state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = STACK_MISC; } return 0; } static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot) { struct bpf_verifier_state *parent = state->parent; while (parent) { /* if read wasn't screened by an earlier write ... */ if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN) break; /* ... then we depend on parent's value */ parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ; state = parent; parent = state->parent; } } static int check_stack_read(struct bpf_verifier_env *env, struct bpf_verifier_state *state, int off, int size, int value_regno) { int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; u8 *stype; if (state->allocated_stack <= slot) { verbose(env, "invalid read from stack off %d+0 size %d\n", off, size); return -EACCES; } stype = state->stack[spi].slot_type; if (stype[0] == STACK_SPILL) { if (size != BPF_REG_SIZE) { verbose(env, "invalid size of register spill\n"); return -EACCES; } for (i = 1; i < BPF_REG_SIZE; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { verbose(env, "corrupted spill memory\n"); return -EACCES; } } if (value_regno >= 0) { /* restore register state from stack */ state->regs[value_regno] = state->stack[spi].spilled_ptr; mark_stack_slot_read(state, spi); } return 0; } else { for (i = 0; i < size; i++) { if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid read from stack off %d+%d size %d\n", off, i, size); return -EACCES; } } if (value_regno >= 0) /* have read misc data from the stack */ mark_reg_unknown(env, state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_map *map = regs[regno].map_ptr; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || off + size > map->value_size) { verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", map->value_size, off, size); return -EACCES; } return 0; } /* check read/write into a map element with possible variable offset */ static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int err; /* We may have adjusted the register to this map value, so we * need to try adding each of min_value and max_value to off * to make sure our theoretical access will be safe. */ if (env->log.level) print_verifier_state(env, state); /* The minimum value is only important with signed * comparisons where we can't assume the floor of a * value is 0. If we are using signed variables for our * index'es we need to make sure that whatever we use * will have a set floor within our range. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->smin_value + off, size, zero_size_allowed); if (err) { verbose(env, "R%d min value is outside of the array range\n", regno); return err; } /* If we haven't set a max value then we need to bail since we can't be * sure we won't do bad things. * If reg->umax_value + off could overflow, treat that as unbounded too. */ if (reg->umax_value >= BPF_MAX_VAR_OFF) { verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", regno); return -EACCES; } err = __check_map_access(env, regno, reg->umax_value + off, size, zero_size_allowed); if (err) verbose(env, "R%d max value is outside of the array range\n", regno); return err; } #define MAX_PACKET_OFF 0xffff static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, const struct bpf_call_arg_meta *meta, enum bpf_access_type t) { switch (env->prog->type) { case BPF_PROG_TYPE_LWT_IN: case BPF_PROG_TYPE_LWT_OUT: /* dst_input() and dst_output() can't write for now */ if (t == BPF_WRITE) return false; /* fallthrough */ case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: case BPF_PROG_TYPE_XDP: case BPF_PROG_TYPE_LWT_XMIT: case BPF_PROG_TYPE_SK_SKB: if (meta) return meta->pkt_access; env->seen_direct_write = true; return true; default: return false; } } static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || (u64)off + size > reg->range) { verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", off, size, regno, reg->id, reg->off, reg->range); return -EACCES; } return 0; } static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size, bool zero_size_allowed) { struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = &regs[regno]; int err; /* We may have added a variable offset to the packet pointer; but any * reg->range we have comes after that. We are only checking the fixed * offset. */ /* We don't allow negative numbers, because we aren't tracking enough * detail to prove they're safe. */ if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = __check_packet_access(env, regno, off, size, zero_size_allowed); if (err) { verbose(env, "R%d offset is outside of the packet\n", regno); return err; } return err; } /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { struct bpf_insn_access_aux info = { .reg_type = *reg_type, }; if (env->ops->is_valid_access && env->ops->is_valid_access(off, size, t, &info)) { /* A non zero info.ctx_field_size indicates that this field is a * candidate for later verifier transformation to load the whole * field and then apply a mask when accessed with a narrower * access than actual ctx access size. A zero info.ctx_field_size * will only allow for whole field access and rejects any other * type of narrower access. */ *reg_type = info.reg_type; env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool __is_pointer_value(bool allow_ptr_leaks, const struct bpf_reg_state *reg) { if (allow_ptr_leaks) return false; return reg->type != SCALAR_VALUE; } static bool is_pointer_value(struct bpf_verifier_env *env, int regno) { return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno); } static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size, bool strict) { struct tnum reg_off; int ip_align; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; /* For platforms that do not have a Kconfig enabling * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of * NET_IP_ALIGN is universally set to '2'. And on platforms * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get * to this code only in strict mode where we want to emulate * the NET_IP_ALIGN==2 checking. Therefore use an * unconditional IP align value of '2'. */ ip_align = 2; reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned packet access off %d+%s+%d+%d size %d\n", ip_align, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_generic_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, const char *pointer_desc, int off, int size, bool strict) { struct tnum reg_off; /* Byte size accesses are always allowed. */ if (!strict || size == 1) return 0; reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); if (!tnum_is_aligned(reg_off, size)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", pointer_desc, tn_buf, reg->off, off, size); return -EACCES; } return 0; } static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } /* truncate register to smaller size (in bytes) * must be called with size < BPF_REG_SIZE */ static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) { u64 mask; /* clear high bits in bit representation */ reg->var_off = tnum_cast(reg->var_off, size); /* fix arithmetic bounds */ mask = ((u64)1 << (size * 8)) - 1; if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { reg->umin_value &= mask; reg->umax_value &= mask; } else { reg->umin_value = 0; reg->umax_value = mask; } reg->smin_value = reg->umin_value; reg->smax_value = reg->umax_value; } /* check whether memory at (regno + off) is accessible for t = (read | write) * if t==write, value_regno is a register which value is stored into memory * if t==read, value_regno is a register which will receive the value from memory * if t==write && value_regno==-1, some unknown value is stored into memory * if t==read && value_regno==-1, don't care what we read from memory */ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ coerce_reg_to_size(&regs[value_regno], size); } return err; } static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) { int err; if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || insn->imm != 0) { verbose(env, "BPF_XADD uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d leaks addr into mem\n", insn->src_reg); return -EACCES; } /* check whether atomic_add can read the memory */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, -1); if (err) return err; /* check whether atomic_add can write into the same memory */ return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); } /* Does this register contain a constant zero? */ static bool register_is_null(struct bpf_reg_state reg) { return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0); } /* when register 'regno' is passed into function that will read 'access_size' * bytes from that pointer, make sure that it's within stack boundary * and all elements of stack are initialized. * Unlike most pointer bounds-checking functions, this one doesn't take an * 'off' argument, so it has to add in reg->off itself. */ static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: return check_packet_access(env, regno, reg->off, access_size, zero_size_allowed); case PTR_TO_MAP_VALUE: return check_map_access(env, regno, reg->off, access_size, zero_size_allowed); default: /* scalar_value|ptr_to_stack or invalid ptr */ return check_stack_boundary(env, regno, access_size, zero_size_allowed, meta); } } static int check_func_arg(struct bpf_verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno]; enum bpf_reg_type expected_type, type = reg->type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; err = check_reg_arg(env, regno, SRC_OP); if (err) return err; if (arg_type == ARG_ANYTHING) { if (is_pointer_value(env, regno)) { verbose(env, "R%d leaks addr into helper function\n", regno); return -EACCES; } return 0; } if (type_is_pkt_pointer(type) && !may_access_direct_pkt_data(env, meta, BPF_READ)) { verbose(env, "helper access to the packet is not allowed\n"); return -EACCES; } if (arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; if (!type_is_pkt_pointer(type) && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { expected_type = SCALAR_VALUE; if (type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_MEM || arg_type == ARG_PTR_TO_MEM_OR_NULL || arg_type == ARG_PTR_TO_UNINIT_MEM) { expected_type = PTR_TO_STACK; /* One exception here. In case function allows for NULL to be * passed in as argument, it's a SCALAR_VALUE type. Final test * happens during stack boundary checking. */ if (register_is_null(*reg) && arg_type == ARG_PTR_TO_MEM_OR_NULL) /* final test in check_stack_boundary() */; else if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && type != expected_type) goto err_type; meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; } else { verbose(env, "unsupported arg_type %d\n", arg_type); return -EFAULT; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; } else if (arg_type == ARG_PTR_TO_MAP_KEY) { /* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized */ if (!meta->map_ptr) { /* in function declaration map_ptr must come before * map_key, so that it's verified and known before * we have to check map_key here. Otherwise it means * that kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->key\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->key_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->key_size, false, NULL); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!meta->map_ptr) { /* kernel subsystem misconfigured verifier */ verbose(env, "invalid map_ptr to access map->value\n"); return -EACCES; } if (type_is_pkt_pointer(type)) err = check_packet_access(env, regno, reg->off, meta->map_ptr->value_size, false); else err = check_stack_boundary(env, regno, meta->map_ptr->value_size, false, NULL); } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); /* bpf_xxx(..., buf, len) call will access 'len' bytes * from stack pointer 'buf'. Check it * note: regno == len, regno - 1 == buf */ if (regno == 0) { /* kernel subsystem misconfigured verifier */ verbose(env, "ARG_CONST_SIZE cannot be first argument\n"); return -EACCES; } /* The register is SCALAR_VALUE; the access check * happens using its boundaries. */ if (!tnum_is_const(reg->var_off)) /* For unprivileged variable accesses, disable raw * mode so that the program is required to * initialize all the memory that the helper could * just partially fill up. */ meta = NULL; if (reg->smin_value < 0) { verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", regno); return -EACCES; } if (reg->umin_value == 0) { err = check_helper_mem_access(env, regno - 1, 0, zero_size_allowed, meta); if (err) return err; } if (reg->umax_value >= BPF_MAX_VAR_SIZ) { verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", regno); return -EACCES; } err = check_helper_mem_access(env, regno - 1, reg->umax_value, zero_size_allowed, meta); } return err; err_type: verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[type], reg_type_str[expected_type]); return -EACCES; } static int check_map_func_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, int func_id) { if (!map) return 0; /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: if (func_id != BPF_FUNC_tail_call) goto error; break; case BPF_MAP_TYPE_PERF_EVENT_ARRAY: if (func_id != BPF_FUNC_perf_event_read && func_id != BPF_FUNC_perf_event_output && func_id != BPF_FUNC_perf_event_read_value) goto error; break; case BPF_MAP_TYPE_STACK_TRACE: if (func_id != BPF_FUNC_get_stackid) goto error; break; case BPF_MAP_TYPE_CGROUP_ARRAY: if (func_id != BPF_FUNC_skb_under_cgroup && func_id != BPF_FUNC_current_task_under_cgroup) goto error; break; /* devmap returns a pointer to a live net_device ifindex that we cannot * allow to be modified from bpf side. So do not allow lookup elements * for now. */ case BPF_MAP_TYPE_DEVMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; /* Restrict bpf side of cpumap, open when use-cases appear */ case BPF_MAP_TYPE_CPUMAP: if (func_id != BPF_FUNC_redirect_map) goto error; break; case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: if (func_id != BPF_FUNC_map_lookup_elem) goto error; break; case BPF_MAP_TYPE_SOCKMAP: if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem) goto error; break; default: break; } /* ... and second from the function itself. */ switch (func_id) { case BPF_FUNC_tail_call: if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) goto error; break; case BPF_FUNC_perf_event_read: case BPF_FUNC_perf_event_output: case BPF_FUNC_perf_event_read_value: if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) goto error; break; case BPF_FUNC_get_stackid: if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) goto error; break; case BPF_FUNC_current_task_under_cgroup: case BPF_FUNC_skb_under_cgroup: if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) goto error; break; case BPF_FUNC_redirect_map: if (map->map_type != BPF_MAP_TYPE_DEVMAP && map->map_type != BPF_MAP_TYPE_CPUMAP) goto error; break; case BPF_FUNC_sk_redirect_map: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; case BPF_FUNC_sock_map_update: if (map->map_type != BPF_MAP_TYPE_SOCKMAP) goto error; break; default: break; } return 0; error: verbose(env, "cannot pass map_type %d into func %s#%d\n", map->map_type, func_id_name(func_id), func_id); return -EINVAL; } static int check_raw_mode(const struct bpf_func_proto *fn) { int count = 0; if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) count++; return count > 1 ? -EINVAL : 0; } /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] * are now invalid, so turn them into unknown SCALAR_VALUE. */ static void clear_all_pkt_pointers(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs, *reg; int i; for (i = 0; i < MAX_BPF_REG; i++) if (reg_is_pkt_pointer_any(&regs[i])) mark_reg_unknown(env, regs, i); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg_is_pkt_pointer_any(reg)) __mark_reg_unknown(reg); } } static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->ops->get_func_proto) fn = env->ops->get_func_proto(func_id); if (!fn) { verbose(env, "unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose(env, "cannot call GPL only function from proprietary program\n"); return -EINVAL; } /* With LD_ABS/IND some JITs save/restore skb from r1. */ changes_data = bpf_helper_changes_pkt_data(fn->func); if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", func_id_name(func_id), func_id); return -EINVAL; } memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; /* We only support one arg being in raw mode at the moment, which * is sufficient for the helper functions we have right now. */ err = check_raw_mode(fn); if (err) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1); if (err) return err; } regs = cur_regs(env); /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* update return register (already marked as written above) */ if (fn->ret_type == RET_INTEGER) { /* sets type to SCALAR_VALUE */ mark_reg_unknown(env, regs, BPF_REG_0); } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { struct bpf_insn_aux_data *insn_aux; regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; /* There is no offset yet applied, variable or fixed */ mark_reg_known_zero(env, regs, BPF_REG_0); regs[BPF_REG_0].off = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose(env, "kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; insn_aux = &env->insn_aux_data[insn_idx]; if (!insn_aux->map_ptr) insn_aux->map_ptr = meta.map_ptr; else if (insn_aux->map_ptr != meta.map_ptr) insn_aux->map_ptr = BPF_MAP_PTR_POISON; } else { verbose(env, "unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } err = check_map_func_compatibility(env, meta.map_ptr, func_id); if (err) return err; if (changes_data) clear_all_pkt_pointers(env); return 0; } static bool signed_add_overflows(s64 a, s64 b) { /* Do the add in u64, where overflow is well-defined */ s64 res = (s64)((u64)a + (u64)b); if (b < 0) return res > a; return res < a; } static bool signed_sub_overflows(s64 a, s64 b) { /* Do the sub in u64, where overflow is well-defined */ s64 res = (s64)((u64)a - (u64)b); if (b < 0) return res < a; return res > a; } /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. * Caller should also handle BPF_MOV case separately. * If we return -EACCES, caller may want to try again treating pointer as a * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. */ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u8 opcode = BPF_OP(insn->code); u32 dst = insn->dst_reg; dst_reg = &regs[dst]; if (WARN_ON_ONCE(known && (smin_val != smax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad sbounds\n"); return -EINVAL; } if (WARN_ON_ONCE(known && (umin_val != umax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad ubounds\n"); return -EINVAL; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ if (!env->allow_ptr_leaks) verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n", dst); return -EACCES; } if (ptr_reg->type == CONST_PTR_TO_MAP) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_PACKET_END) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n", dst); return -EACCES; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->range = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ if (!env->allow_ptr_leaks) verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { if (!env->allow_ptr_leaks) verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->range = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit for now. * (However, in principle we could allow some cases, e.g. * ptr &= ~3 which would reduce min_value by 3.) */ if (!env->allow_ptr_leaks) verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->64 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val > 63) { /* Shifts greater than 63 are undefined. This includes * shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max * and var_off. */ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; u8 opcode = BPF_OP(insn->code); int rc; dst_reg = &regs[insn->dst_reg]; src_reg = NULL; if (dst_reg->type != SCALAR_VALUE) ptr_reg = dst_reg; if (BPF_SRC(insn->code) == BPF_X) { src_reg = &regs[insn->src_reg]; if (src_reg->type != SCALAR_VALUE) { if (dst_reg->type != SCALAR_VALUE) { /* Combining two pointers by any ALU op yields * an arbitrary scalar. */ if (!env->allow_ptr_leaks) { verbose(env, "R%d pointer %s pointer prohibited\n", insn->dst_reg, bpf_alu_string[opcode >> 4]); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); return 0; } else { /* scalar += pointer * This is legal, but we have to reverse our * src/dest handling in computing the range */ rc = adjust_ptr_min_max_vals(env, insn, src_reg, dst_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* scalar += unknown scalar */ __mark_reg_unknown(&off_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } else if (ptr_reg) { /* pointer += scalar */ rc = adjust_ptr_min_max_vals(env, insn, dst_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += scalar */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, *src_reg); } return rc; } } else { /* Pretend the src is a reg with a known value, since we only * need to be able to read from this state. */ off_reg.type = SCALAR_VALUE; __mark_reg_known(&off_reg, insn->imm); src_reg = &off_reg; if (ptr_reg) { /* pointer += K */ rc = adjust_ptr_min_max_vals(env, insn, ptr_reg, src_reg); if (rc == -EACCES && env->allow_ptr_leaks) { /* unknown scalar += K */ __mark_reg_unknown(dst_reg); return adjust_scalar_min_max_vals( env, insn, dst_reg, off_reg); } return rc; } } /* Got here implies adding two SCALAR_VALUEs */ if (WARN_ON_ONCE(ptr_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: unexpected ptr_reg\n"); return -EINVAL; } if (WARN_ON(!src_reg)) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: no src_reg\n"); return -EINVAL; } return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose(env, "BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || BPF_CLASS(insn->code) == BPF_ALU64) { verbose(env, "BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; } else { /* R1 = (u32) R2 */ if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown(env, regs, insn->dst_reg); coerce_reg_to_size(&regs[insn->dst_reg], 4); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = SCALAR_VALUE; if (BPF_CLASS(insn->code) == BPF_ALU64) { __mark_reg_known(regs + insn->dst_reg, insn->imm); } else { __mark_reg_known(regs + insn->dst_reg, (u32)insn->imm); } } } else if (opcode > BPF_END) { verbose(env, "invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose(env, "BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose(env, "div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose(env, "invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; return adjust_reg_min_max_vals(env, insn); } return 0; } static void find_good_pkt_pointers(struct bpf_verifier_state *state, struct bpf_reg_state *dst_reg, enum bpf_reg_type type, bool range_right_open) { struct bpf_reg_state *regs = state->regs, *reg; u16 new_range; int i; if (dst_reg->off < 0 || (dst_reg->off == 0 && range_right_open)) /* This doesn't give us any range */ return; if (dst_reg->umax_value > MAX_PACKET_OFF || dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) /* Risk of overflow. For instance, ptr + (1<<63) may be less * than pkt_end, but that's because it's also less than pkt. */ return; new_range = dst_reg->off; if (range_right_open) new_range--; /* Examples for register markings: * * pkt_data in dst register: * * r2 = r3; * r2 += 8; * if (r2 > pkt_end) goto <handle exception> * <access okay> * * r2 = r3; * r2 += 8; * if (r2 < pkt_end) goto <access okay> * <handle exception> * * Where: * r2 == dst_reg, pkt_end == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * pkt_data in src register: * * r2 = r3; * r2 += 8; * if (pkt_end >= r2) goto <access okay> * <handle exception> * * r2 = r3; * r2 += 8; * if (pkt_end <= r2) goto <handle exception> * <access okay> * * Where: * pkt_end == dst_reg, r2 == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) * and [r3, r3 + 8-1) respectively is safe to access depending on * the check. */ /* If our ids match, then we must have the same max_value. And we * don't care about the other reg's fixed offset, since if it's too big * the range won't allow anything. * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. */ for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == type && regs[i].id == dst_reg->id) /* keep the maximum range already checked */ regs[i].range = max(regs[i].range, new_range); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; reg = &state->stack[i].spilled_ptr; if (reg->type == type && reg->id == dst_reg->id) reg->range = max(reg->range, new_range); } } /* Adjusts the register min/max values in the case that the dst_reg is the * variable register that we are working on, and src_reg is a constant or we're * simply doing a BPF_K check. * In JEQ/JNE cases we also adjust the var_off values. */ static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { /* If the dst_reg is a pointer, we can't learn anything about its * variable offset from the compare (unless src_reg were a pointer into * the same object, but we don't bother with that. * Since false_reg and true_reg have the same type by construction, we * only need to check one of them for pointerness. */ if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: false_reg->umax_value = min(false_reg->umax_value, val); true_reg->umin_value = max(true_reg->umin_value, val + 1); break; case BPF_JSGT: false_reg->smax_value = min_t(s64, false_reg->smax_value, val); true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); break; case BPF_JLT: false_reg->umin_value = max(false_reg->umin_value, val); true_reg->umax_value = min(true_reg->umax_value, val - 1); break; case BPF_JSLT: false_reg->smin_value = max_t(s64, false_reg->smin_value, val); true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); break; case BPF_JGE: false_reg->umax_value = min(false_reg->umax_value, val - 1); true_reg->umin_value = max(true_reg->umin_value, val); break; case BPF_JSGE: false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); true_reg->smin_value = max_t(s64, true_reg->smin_value, val); break; case BPF_JLE: false_reg->umin_value = max(false_reg->umin_value, val + 1); true_reg->umax_value = min(true_reg->umax_value, val); break; case BPF_JSLE: false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); true_reg->smax_value = min_t(s64, true_reg->smax_value, val); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Same as above, but for the case that dst_reg holds a constant and src_reg is * the variable reg. */ static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { if (__is_pointer_value(false, false_reg)) return; switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ __mark_reg_known(true_reg, val); break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ __mark_reg_known(false_reg, val); break; case BPF_JGT: true_reg->umax_value = min(true_reg->umax_value, val - 1); false_reg->umin_value = max(false_reg->umin_value, val); break; case BPF_JSGT: true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); false_reg->smin_value = max_t(s64, false_reg->smin_value, val); break; case BPF_JLT: true_reg->umin_value = max(true_reg->umin_value, val + 1); false_reg->umax_value = min(false_reg->umax_value, val); break; case BPF_JSLT: true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); false_reg->smax_value = min_t(s64, false_reg->smax_value, val); break; case BPF_JGE: true_reg->umax_value = min(true_reg->umax_value, val); false_reg->umin_value = max(false_reg->umin_value, val + 1); break; case BPF_JSGE: true_reg->smax_value = min_t(s64, true_reg->smax_value, val); false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); break; case BPF_JLE: true_reg->umin_value = max(true_reg->umin_value, val); false_reg->umax_value = min(false_reg->umax_value, val - 1); break; case BPF_JSLE: true_reg->smin_value = max_t(s64, true_reg->smin_value, val); false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); break; default: break; } __reg_deduce_bounds(false_reg); __reg_deduce_bounds(true_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(false_reg); __reg_bound_offset(true_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(false_reg); __update_reg_bounds(true_reg); } /* Regs are known to be equal, so intersect their min/max/var_off */ static void __reg_combine_min_max(struct bpf_reg_state *src_reg, struct bpf_reg_state *dst_reg) { src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, dst_reg->umin_value); src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, dst_reg->umax_value); src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, dst_reg->smin_value); src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, dst_reg->smax_value); src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, dst_reg->var_off); /* We might have learned new bounds from the var_off. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); /* We might have learned something about the sign bit. */ __reg_deduce_bounds(src_reg); __reg_deduce_bounds(dst_reg); /* We might have learned some bits from the bounds. */ __reg_bound_offset(src_reg); __reg_bound_offset(dst_reg); /* Intersecting with the old var_off might have improved our bounds * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), * then new var_off is (0; 0x7f...fc) which improves our umax. */ __update_reg_bounds(src_reg); __update_reg_bounds(dst_reg); } static void reg_combine_min_max(struct bpf_reg_state *true_src, struct bpf_reg_state *true_dst, struct bpf_reg_state *false_src, struct bpf_reg_state *false_dst, u8 opcode) { switch (opcode) { case BPF_JEQ: __reg_combine_min_max(true_src, true_dst); break; case BPF_JNE: __reg_combine_min_max(false_src, false_dst); break; } } static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id, bool is_null) { struct bpf_reg_state *reg = &regs[regno]; if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) { /* Old offset (both fixed and variable parts) should * have been known-zero, because we don't allow pointer * arithmetic on pointers that might be NULL. */ if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0) || reg->off)) { __mark_reg_known_zero(reg); reg->off = 0; } if (is_null) { reg->type = SCALAR_VALUE; } else if (reg->map_ptr->inner_map_meta) { reg->type = CONST_PTR_TO_MAP; reg->map_ptr = reg->map_ptr->inner_map_meta; } else { reg->type = PTR_TO_MAP_VALUE; } /* We don't need id from this point onwards anymore, thus we * should better reset it, so that state pruning has chances * to take effect. */ reg->id = 0; } } /* The logic is similar to find_good_pkt_pointers(), both could eventually * be folded together at some point. */ static void mark_map_regs(struct bpf_verifier_state *state, u32 regno, bool is_null) { struct bpf_reg_state *regs = state->regs; u32 id = regs[regno].id; int i; for (i = 0; i < MAX_BPF_REG; i++) mark_map_reg(regs, i, id, is_null); for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { if (state->stack[i].slot_type[0] != STACK_SPILL) continue; mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null); } } static bool try_match_pkt_pointers(const struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg, struct bpf_verifier_state *this_branch, struct bpf_verifier_state *other_branch) { if (BPF_SRC(insn->code) != BPF_X) return false; switch (BPF_OP(insn->code)) { case BPF_JGT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end > pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, true); } else { return false; } break; case BPF_JLT: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end < pkt_data', pkt_data > pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JGE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ find_good_pkt_pointers(this_branch, dst_reg, dst_reg->type, true); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ find_good_pkt_pointers(other_branch, src_reg, src_reg->type, false); } else { return false; } break; case BPF_JLE: if ((dst_reg->type == PTR_TO_PACKET && src_reg->type == PTR_TO_PACKET_END) || (dst_reg->type == PTR_TO_PACKET_META && reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ find_good_pkt_pointers(other_branch, dst_reg, dst_reg->type, false); } else if ((dst_reg->type == PTR_TO_PACKET_END && src_reg->type == PTR_TO_PACKET) || (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && src_reg->type == PTR_TO_PACKET_META)) { /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ find_good_pkt_pointers(this_branch, src_reg, src_reg->type, true); } else { return false; } break; default: return false; } return true; } static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *other_branch, *this_branch = env->cur_state; struct bpf_reg_state *regs = this_branch->regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, "invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, "BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == SCALAR_VALUE && tnum_equals_const(dst_reg->var_off, insn->imm)) { if (opcode == BPF_JEQ) { /* if (imm == imm) goto pc+off; * only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else { /* if (imm != imm) goto pc+off; * only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch->regs[insn->src_reg], &regs[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch->regs[insn->src_reg], &other_branch->regs[insn->dst_reg], &regs[insn->src_reg], &regs[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { /* Mark all identical map registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, "R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch); return 0; } /* return the map pointer stored inside BPF_LD_IMM64 instruction */ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) { u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; return (struct bpf_map *) (unsigned long) imm64; } /* verify BPF_LD_IMM64 instruction */ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); int err; if (BPF_SIZE(insn->code) != BPF_DW) { verbose(env, "invalid BPF_LD_IMM insn\n"); return -EINVAL; } if (insn->off != 0) { verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); return -EINVAL; } err = check_reg_arg(env, insn->dst_reg, DST_OP); if (err) return err; if (insn->src_reg == 0) { u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; regs[insn->dst_reg].type = SCALAR_VALUE; __mark_reg_known(&regs[insn->dst_reg], imm); return 0; } /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); regs[insn->dst_reg].type = CONST_PTR_TO_MAP; regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); return 0; } static bool may_access_skb(enum bpf_prog_type type) { switch (type) { case BPF_PROG_TYPE_SOCKET_FILTER: case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: return true; default: return false; } } /* verify safety of LD_ABS|LD_IND instructions: * - they can only appear in the programs where ctx == skb * - since they are wrappers of function calls, they scratch R1-R5 registers, * preserve R6-R9, and store return value into R0 * * Implicit input: * ctx == skb == R6 == CTX * * Explicit input: * SRC == any register * IMM == 32-bit immediate * * Output: * R0 - 8/16/32-bit skb data converted to cpu endianness */ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = cur_regs(env); u8 mode = BPF_MODE(insn->code); int i, err; if (!may_access_skb(env->prog->type)) { verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); return -EINVAL; } if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || BPF_SIZE(insn->code) == BPF_DW || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); return -EINVAL; } /* check whether implicit source operand (register R6) is readable */ err = check_reg_arg(env, BPF_REG_6, SRC_OP); if (err) return err; if (regs[BPF_REG_6].type != PTR_TO_CTX) { verbose(env, "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); return -EINVAL; } if (mode == BPF_IND) { /* check explicit source operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; } /* reset caller saved regs to unreadable */ for (i = 0; i < CALLER_SAVED_REGS; i++) { mark_reg_not_init(env, regs, caller_saved[i]); check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); } /* mark destination R0 register as readable, since it contains * the value fetched from the packet. * Already marked as written above. */ mark_reg_unknown(env, regs, BPF_REG_0); return 0; } static int check_return_code(struct bpf_verifier_env *env) { struct bpf_reg_state *reg; struct tnum range = tnum_range(0, 1); switch (env->prog->type) { case BPF_PROG_TYPE_CGROUP_SKB: case BPF_PROG_TYPE_CGROUP_SOCK: case BPF_PROG_TYPE_SOCK_OPS: case BPF_PROG_TYPE_CGROUP_DEVICE: break; default: return 0; } reg = cur_regs(env) + BPF_REG_0; if (reg->type != SCALAR_VALUE) { verbose(env, "At program exit the register R0 is not a known value (%s)\n", reg_type_str[reg->type]); return -EINVAL; } if (!tnum_in(range, reg->var_off)) { verbose(env, "At program exit the register R0 "); if (!tnum_is_unknown(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "has value %s", tn_buf); } else { verbose(env, "has unknown scalar value"); } verbose(env, " should have been 0 or 1\n"); return -EINVAL; } return 0; } /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered * 3 let S be a stack * 4 S.push(v) * 5 while S is not empty * 6 t <- S.pop() * 7 if t is what we're looking for: * 8 return t * 9 for all edges e in G.adjacentEdges(t) do * 10 if edge e is already labelled * 11 continue with the next edge * 12 w <- G.adjacentVertex(t,e) * 13 if vertex w is not discovered and not explored * 14 label e as tree-edge * 15 label w as discovered * 16 S.push(w) * 17 continue at 5 * 18 else if vertex w is discovered * 19 label e as back-edge * 20 else * 21 // vertex w is explored * 22 label e as forward- or cross-edge * 23 label t as explored * 24 S.pop() * * convention: * 0x10 - discovered * 0x11 - discovered and fall-through edge labelled * 0x12 - discovered and fall-through and branch edges labelled * 0x20 - explored */ enum { DISCOVERED = 0x10, EXPLORED = 0x20, FALLTHROUGH = 1, BRANCH = 2, }; #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) static int *insn_stack; /* stack of insns to process */ static int cur_stack; /* current stack index */ static int *insn_state; /* t, w, e - match pseudo-code above: * t - index of current instruction * w - next instruction * e - edge */ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose(env, "jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose(env, "back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose(env, "insn state internal bug\n"); return -EFAULT; } return 0; } /* non-recursive depth-first-search to detect loops in BPF program * loop == back-edge in directed graph */ static int check_cfg(struct bpf_verifier_env *env) { struct bpf_insn *insns = env->prog->insnsi; int insn_cnt = env->prog->len; int ret = 0; int i, t; insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_state) return -ENOMEM; insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_stack) { kfree(insn_state); return -ENOMEM; } insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ insn_stack[0] = 0; /* 0 is the first instruction */ cur_stack = 1; peek_stack: if (cur_stack == 0) goto check_state; t = insn_stack[cur_stack - 1]; if (BPF_CLASS(insns[t].code) == BPF_JMP) { u8 opcode = BPF_OP(insns[t].code); if (opcode == BPF_EXIT) { goto mark_explored; } else if (opcode == BPF_CALL) { ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else if (opcode == BPF_JA) { if (BPF_SRC(insns[t].code) != BPF_K) { ret = -EINVAL; goto err_free; } /* unconditional jump with single edge */ ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; /* tell verifier to check for equivalent states * after every call and jump */ if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else { /* conditional jump with two edges */ env->explored_states[t] = STATE_LIST_MARK; ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } } else { /* all other non-branch instructions with single * fall-through edge */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } mark_explored: insn_state[t] = EXPLORED; if (cur_stack-- <= 0) { verbose(env, "pop stack internal bug\n"); ret = -EFAULT; goto err_free; } goto peek_stack; check_state: for (i = 0; i < insn_cnt; i++) { if (insn_state[i] != EXPLORED) { verbose(env, "unreachable insn %d\n", i); ret = -EINVAL; goto err_free; } } ret = 0; /* cfg looks good */ err_free: kfree(insn_state); kfree(insn_stack); return ret; } /* check %cur's range satisfies %old's */ static bool range_within(struct bpf_reg_state *old, struct bpf_reg_state *cur) { return old->umin_value <= cur->umin_value && old->umax_value >= cur->umax_value && old->smin_value <= cur->smin_value && old->smax_value >= cur->smax_value; } /* Maximum number of register states that can exist at once */ #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) struct idpair { u32 old; u32 cur; }; /* If in the old state two registers had the same id, then they need to have * the same id in the new state as well. But that id could be different from * the old state, so we need to track the mapping from old to new ids. * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent * regs with old id 5 must also have new id 9 for the new state to be safe. But * regs with a different old id could still have new id 9, we don't care about * that. * So we look through our idmap to see if this old id has been seen before. If * so, we require the new id to match; otherwise, we add the id pair to the map. */ static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) { unsigned int i; for (i = 0; i < ID_MAP_SIZE; i++) { if (!idmap[i].old) { /* Reached an empty slot; haven't seen this id before */ idmap[i].old = old_id; idmap[i].cur = cur_id; return true; } if (idmap[i].old == old_id) return idmap[i].cur == cur_id; } /* We ran out of idmap slots, which should be impossible */ WARN_ON_ONCE(1); return false; } /* Returns true if (rold safe implies rcur safe) */ static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } static bool stacksafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, struct idpair *idmap) { int i, spi; /* if explored stack has more populated slots than current stack * such stacks are not equivalent */ if (old->allocated_stack > cur->allocated_stack) return false; /* walk slots of the explored stack and ignore any additional * slots in the current stack, since explored(safe) state * didn't use them */ for (i = 0; i < old->allocated_stack; i++) { spi = i / BPF_REG_SIZE; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) continue; if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != cur->stack[spi].slot_type[i % BPF_REG_SIZE]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; if (i % BPF_REG_SIZE) continue; if (old->stack[spi].slot_type[0] != STACK_SPILL) continue; if (!regsafe(&old->stack[spi].spilled_ptr, &cur->stack[spi].spilled_ptr, idmap)) /* when explored and current stack slot are both storing * spilled registers, check that stored pointers types * are the same as well. * Ex: explored safe path could have stored * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} * but current path has stored: * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} * such verifier states are not equivalent. * return false to continue verification of this path */ return false; } return true; } /* compare two verifier states * * all states stored in state_list are known to be valid, since * verifier reached 'bpf_exit' instruction through them * * this function is called when verifier exploring different branches of * execution popped from the state stack. If it sees an old state that has * more strict register state and more strict stack state then this execution * branch doesn't need to be explored further, since verifier already * concluded that more strict state leads to valid finish. * * Therefore two states are equivalent if register state is more conservative * and explored stack state is more conservative than the current one. * Example: * explored current * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) * * In other words if current stack state (one being explored) has more * valid slots than old one that already passed validation, it means * the verifier can stop exploring and conclude that current state is valid too * * Similarly with registers. If explored state has register type as invalid * whereas register type in current state is meaningful, it means that * the current state will reach 'bpf_exit' instruction safely */ static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { struct idpair *idmap; bool ret = false; int i; idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); /* If we failed to allocate the idmap, just say it's not safe */ if (!idmap) return false; for (i = 0; i < MAX_BPF_REG; i++) { if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) goto out_free; } if (!stacksafe(old, cur, idmap)) goto out_free; ret = true; out_free: kfree(idmap); return ret; } /* A write screens off any subsequent reads; but write marks come from the * straight-line code between a state and its parent. When we arrive at a * jump target (in the first iteration of the propagate_liveness() loop), * we didn't arrive by the straight-line code, so read marks in state must * propagate to parent regardless of state's write marks. */ static bool do_propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { bool writes = parent == state->parent; /* Observe write marks */ bool touched = false; /* any changes made? */ int i; if (!parent) return touched; /* Propagate read liveness of registers... */ BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); /* We don't need to worry about FP liveness because it's read-only */ for (i = 0; i < BPF_REG_FP; i++) { if (parent->regs[i].live & REG_LIVE_READ) continue; if (writes && (state->regs[i].live & REG_LIVE_WRITTEN)) continue; if (state->regs[i].live & REG_LIVE_READ) { parent->regs[i].live |= REG_LIVE_READ; touched = true; } } /* ... and stack slots */ for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && i < parent->allocated_stack / BPF_REG_SIZE; i++) { if (parent->stack[i].slot_type[0] != STACK_SPILL) continue; if (state->stack[i].slot_type[0] != STACK_SPILL) continue; if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ) continue; if (writes && (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN)) continue; if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) { parent->stack[i].spilled_ptr.live |= REG_LIVE_READ; touched = true; } } return touched; } /* "parent" is "a state from which we reach the current state", but initially * it is not the state->parent (i.e. "the state whose straight-line code leads * to the current state"), instead it is the state that happened to arrive at * a (prunable) equivalent of the current state. See comment above * do_propagate_liveness() for consequences of this. * This function is just a more efficient way of calling mark_reg_read() or * mark_stack_slot_read() on each reg in "parent" that is read in "state", * though it requires that parent != state->parent in the call arguments. */ static void propagate_liveness(const struct bpf_verifier_state *state, struct bpf_verifier_state *parent) { while (do_propagate_liveness(state, parent)) { /* Something changed, so we need to feed those changes onward */ state = parent; parent = state->parent; } } static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) { struct bpf_verifier_state_list *new_sl; struct bpf_verifier_state_list *sl; struct bpf_verifier_state *cur = env->cur_state; int i, err; sl = env->explored_states[insn_idx]; if (!sl) /* this 'insn_idx' instruction wasn't marked, so we will not * be doing state search here */ return 0; while (sl != STATE_LIST_MARK) { if (states_equal(env, &sl->state, cur)) { /* reached equivalent register/stack state, * prune the search. * Registers read by the continuation are read by us. * If we have any write marks in env->cur_state, they * will prevent corresponding reads in the continuation * from reaching our parent (an explored_state). Our * own state will get the read marks recorded, but * they'll be immediately forgotten as we're pruning * this state and will pop a new one. */ propagate_liveness(&sl->state, cur); return 1; } sl = sl->next; } /* there were no equivalent states, remember current one. * technically the current state is not proven to be safe yet, * but it will either reach bpf_exit (which means it's safe) or * it will be rejected. Since there are no loops, we won't be * seeing this 'insn_idx' instruction again on the way to bpf_exit */ new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); if (!new_sl) return -ENOMEM; /* add new state to the head of linked list */ err = copy_verifier_state(&new_sl->state, cur); if (err) { free_verifier_state(&new_sl->state, false); kfree(new_sl); return err; } new_sl->next = env->explored_states[insn_idx]; env->explored_states[insn_idx] = new_sl; /* connect new state to parentage chain */ cur->parent = &new_sl->state; /* clear write marks in current state: the writes we did are not writes * our child did, so they don't screen off its reads from us. * (There are no read marks in current state, because reads always mark * their parent and current state never has children yet. Only * explored_states can get read marks.) */ for (i = 0; i < BPF_REG_FP; i++) cur->regs[i].live = REG_LIVE_NONE; for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++) if (cur->stack[i].slot_type[0] == STACK_SPILL) cur->stack[i].spilled_ptr.live = REG_LIVE_NONE; return 0; } static int ext_analyzer_insn_hook(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { if (env->dev_ops && env->dev_ops->insn_hook) return env->dev_ops->insn_hook(env, insn_idx, prev_insn_idx); return 0; } static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); if (!state) return -ENOMEM; env->cur_state = state; init_reg_state(env, state->regs); state->parent = NULL; insn_idx = 0; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose(env, "invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose(env, "BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (env->log.level) { if (do_print_state) verbose(env, "\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose(env, "%d: safe\n", insn_idx); } goto process_bpf_exit; } if (need_resched()) cond_resched(); if (env->log.level > 1 || (env->log.level && do_print_state)) { if (env->log.level > 1) verbose(env, "%d:", insn_idx); else verbose(env, "\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(env, state); do_print_state = false; } if (env->log.level) { verbose(env, "%d: ", insn_idx); print_bpf_insn(verbose, env, insn, env->allow_ptr_leaks); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; regs = cur_regs(env); env->insn_aux_data[insn_idx].seen = true; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn_idx, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn_idx, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose(env, "same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose(env, "BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose(env, "BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(env, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose(env, "R0 leaks addr as return value\n"); return -EACCES; } err = check_return_code(env); if (err) return err; process_bpf_exit: err = pop_stack(env, &prev_insn_idx, &insn_idx); if (err < 0) { if (err != -ENOENT) return err; break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; env->insn_aux_data[insn_idx].seen = true; } else { verbose(env, "invalid BPF_LD mode\n"); return -EINVAL; } } else { verbose(env, "unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose(env, "processed %d insns, stack depth %d\n", insn_processed, env->prog->aux->stack_depth); return 0; } static int check_map_prealloc(struct bpf_map *map) { return (map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_PERCPU_HASH && map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || !(map->map_flags & BPF_F_NO_PREALLOC); } static int check_map_prog_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, struct bpf_prog *prog) { /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use * preallocated hash maps, since doing memory allocation * in overflow_handler can crash depending on where nmi got * triggered. */ if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { if (!check_map_prealloc(map)) { verbose(env, "perf_event programs can only use preallocated hash map\n"); return -EINVAL; } if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) { verbose(env, "perf_event programs can only use preallocated inner hash map\n"); return -EINVAL; } } return 0; } /* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */ static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j, err; err = bpf_prog_calc_tag(env->prog); if (err) return err; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose(env, "BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose(env, "BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose(env, "invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose(env, "unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose(env, "fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } err = check_map_prog_compatibility(env, map, env->prog); if (err) { fdput(f); return err; } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ map = bpf_map_inc(map, false); if (IS_ERR(map)) { fdput(f); return PTR_ERR(map); } env->used_maps[env->used_map_cnt++] = map; fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } /* drop refcnt of maps used by the rejected program */ static void release_maps(struct bpf_verifier_env *env) { int i; for (i = 0; i < env->used_map_cnt; i++) bpf_map_put(env->used_maps[i]); } /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) insn->src_reg = 0; } /* single env->prog->insni[off] instruction was replaced with the range * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying * [0, off) and [off, end) to new locations, so the patched range stays zero */ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; } static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, const struct bpf_insn *patch, u32 len) { struct bpf_prog *new_prog; new_prog = bpf_patch_insn_single(env->prog, off, patch, len); if (!new_prog) return NULL; if (adjust_insn_aux_data(env, new_prog->len, off, len)) return NULL; return new_prog; } /* The verifier does more data flow analysis than llvm and will not explore * branches that are dead at run time. Malicious programs can have dead code * too. Therefore replace all dead at-run-time code with nops. */ static void sanitize_dead_code(struct bpf_verifier_env *env) { struct bpf_insn_aux_data *aux_data = env->insn_aux_data; struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0); struct bpf_insn *insn = env->prog->insnsi; const int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++) { if (aux_data[i].seen) continue; memcpy(insn + i, &nop, sizeof(nop)); } } /* convert load instructions that access fields of 'struct __sk_buff' * into sequence of instructions that access fields of 'struct sk_buff' */ static int convert_ctx_accesses(struct bpf_verifier_env *env) { const struct bpf_verifier_ops *ops = env->ops; int i, cnt, size, ctx_field_size, delta = 0; const int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16], *insn; struct bpf_prog *new_prog; enum bpf_access_type type; bool is_narrower_load; u32 target_size; if (ops->gen_prologue) { cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, env->prog); if (cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } else if (cnt) { new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); if (!new_prog) return -ENOMEM; env->prog = new_prog; delta += cnt - 1; } } if (!ops->convert_ctx_access) return 0; insn = env->prog->insnsi + delta; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || insn->code == (BPF_LDX | BPF_MEM | BPF_H) || insn->code == (BPF_LDX | BPF_MEM | BPF_W) || insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || insn->code == (BPF_STX | BPF_MEM | BPF_H) || insn->code == (BPF_STX | BPF_MEM | BPF_W) || insn->code == (BPF_STX | BPF_MEM | BPF_DW)) type = BPF_WRITE; else continue; if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX) continue; ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; size = BPF_LDST_BYTES(insn); /* If the read access is a narrower load of the field, * convert to a 4/8-byte load, to minimum program type specific * convert_ctx_access changes. If conversion is successful, * we will apply proper mask to the result. */ is_narrower_load = size < ctx_field_size; if (is_narrower_load) { u32 off = insn->off; u8 size_code; if (type == BPF_WRITE) { verbose(env, "bpf verifier narrow ctx access misconfigured\n"); return -EINVAL; } size_code = BPF_H; if (ctx_field_size == 4) size_code = BPF_W; else if (ctx_field_size == 8) size_code = BPF_DW; insn->off = off & ~(ctx_field_size - 1); insn->code = BPF_LDX | BPF_MEM | size_code; } target_size = 0; cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog, &target_size); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || (ctx_field_size && !target_size)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } if (is_narrower_load && size < target_size) { if (ctx_field_size <= 4) insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); else insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, (1 << size * 8) - 1); } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + delta; } return 0; } /* fixup insn->imm field of bpf_call instructions * and inline eligible helpers as explicit sequence of BPF instructions * * this function is called after eBPF program passed verification */ static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * handlers are currently limited to 64 bit only. */ if (ebpf_jit_enabled() && BITS_PER_LONG == 64 && insn->imm == BPF_FUNC_map_lookup_elem) { map_ptr = env->insn_aux_data[i + delta].map_ptr; if (map_ptr == BPF_MAP_PTR_POISON || !map_ptr->ops->map_gen_lookup) goto patch_call_imm; cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->imm == BPF_FUNC_redirect_map) { /* Note, we cannot use prog directly as imm as subsequent * rewrites would still change the prog pointer. The only * stable address we can use is aux, which also works with * prog clones during blinding. */ u64 addr = (unsigned long)prog->aux; struct bpf_insn r4_ld[] = { BPF_LD_IMM64(BPF_REG_4, addr), *insn, }; cnt = ARRAY_SIZE(r4_ld); new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } static void free_states(struct bpf_verifier_env *env) { struct bpf_verifier_state_list *sl, *sln; int i; if (!env->explored_states) return; for (i = 0; i < env->prog->len; i++) { sl = env->explored_states[i]; if (sl) while (sl != STATE_LIST_MARK) { sln = sl->next; free_verifier_state(&sl->state, false); kfree(sl); sl = sln; } } kfree(env->explored_states); } int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) sanitize_dead_code(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2983_0
crossvul-cpp_data_good_2907_0
/* * Ultra Wide Band * Neighborhood Management Daemon * * Copyright (C) 2005-2006 Intel Corporation * Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * This daemon takes care of maintaing information that describes the * UWB neighborhood that the radios in this machine can see. It also * keeps a tab of which devices are visible, makes sure each HC sits * on a different channel to avoid interfering, etc. * * Different drivers (radio controller, device, any API in general) * communicate with this daemon through an event queue. Daemon wakes * up, takes a list of events and handles them one by one; handling * function is extracted from a table based on the event's type and * subtype. Events are freed only if the handling function says so. * * . Lock protecting the event list has to be an spinlock and locked * with IRQSAVE because it might be called from an interrupt * context (ie: when events arrive and the notification drops * down from the ISR). * * . UWB radio controller drivers queue events to the daemon using * uwbd_event_queue(). They just get the event, chew it to make it * look like UWBD likes it and pass it in a buffer allocated with * uwb_event_alloc(). * * EVENTS * * Events have a type, a subtype, a length, some other stuff and the * data blob, which depends on the event. The header is 'struct * uwb_event'; for payloads, see 'struct uwbd_evt_*'. * * EVENT HANDLER TABLES * * To find a handling function for an event, the type is used to index * a subtype-table in the type-table. The subtype-table is indexed * with the subtype to get the function that handles the event. Start * with the main type-table 'uwbd_evt_type_handler'. * * DEVICES * * Devices are created when a bunch of beacons have been received and * it is stablished that the device has stable radio presence. CREATED * only, not configured. Devices are ONLY configured when an * Application-Specific IE Probe is receieved, in which the device * declares which Protocol ID it groks. Then the device is CONFIGURED * (and the driver->probe() stuff of the device model is invoked). * * Devices are considered disconnected when a certain number of * beacons are not received in an amount of time. * * Handler functions are called normally uwbd_evt_handle_*(). */ #include <linux/kthread.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/freezer.h> #include "uwb-internal.h" /* * UWBD Event handler function signature * * Return !0 if the event needs not to be freed (ie the handler * takes/took care of it). 0 means the daemon code will free the * event. * * @evt->rc is already referenced and guaranteed to exist. See * uwb_evt_handle(). */ typedef int (*uwbd_evt_handler_f)(struct uwb_event *); /** * Properties of a UWBD event * * @handler: the function that will handle this event * @name: text name of event */ struct uwbd_event { uwbd_evt_handler_f handler; const char *name; }; /* Table of handlers for and properties of the UWBD Radio Control Events */ static struct uwbd_event uwbd_urc_events[] = { [UWB_RC_EVT_IE_RCV] = { .handler = uwbd_evt_handle_rc_ie_rcv, .name = "IE_RECEIVED" }, [UWB_RC_EVT_BEACON] = { .handler = uwbd_evt_handle_rc_beacon, .name = "BEACON_RECEIVED" }, [UWB_RC_EVT_BEACON_SIZE] = { .handler = uwbd_evt_handle_rc_beacon_size, .name = "BEACON_SIZE_CHANGE" }, [UWB_RC_EVT_BPOIE_CHANGE] = { .handler = uwbd_evt_handle_rc_bpoie_change, .name = "BPOIE_CHANGE" }, [UWB_RC_EVT_BP_SLOT_CHANGE] = { .handler = uwbd_evt_handle_rc_bp_slot_change, .name = "BP_SLOT_CHANGE" }, [UWB_RC_EVT_DRP_AVAIL] = { .handler = uwbd_evt_handle_rc_drp_avail, .name = "DRP_AVAILABILITY_CHANGE" }, [UWB_RC_EVT_DRP] = { .handler = uwbd_evt_handle_rc_drp, .name = "DRP" }, [UWB_RC_EVT_DEV_ADDR_CONFLICT] = { .handler = uwbd_evt_handle_rc_dev_addr_conflict, .name = "DEV_ADDR_CONFLICT", }, }; struct uwbd_evt_type_handler { const char *name; struct uwbd_event *uwbd_events; size_t size; }; /* Table of handlers for each UWBD Event type. */ static struct uwbd_evt_type_handler uwbd_urc_evt_type_handlers[] = { [UWB_RC_CET_GENERAL] = { .name = "URC", .uwbd_events = uwbd_urc_events, .size = ARRAY_SIZE(uwbd_urc_events), }, }; static const struct uwbd_event uwbd_message_handlers[] = { [UWB_EVT_MSG_RESET] = { .handler = uwbd_msg_handle_reset, .name = "reset", }, }; /* * Handle an URC event passed to the UWB Daemon * * @evt: the event to handle * @returns: 0 if the event can be kfreed, !0 on the contrary * (somebody else took ownership) [coincidentally, returning * a <0 errno code will free it :)]. * * Looks up the two indirection tables (one for the type, one for the * subtype) to decide which function handles it and then calls the * handler. * * The event structure passed to the event handler has the radio * controller in @evt->rc referenced. The reference will be dropped * once the handler returns, so if it needs it for longer (async), * it'll need to take another one. */ static int uwbd_event_handle_urc(struct uwb_event *evt) { int result = -EINVAL; struct uwbd_evt_type_handler *type_table; uwbd_evt_handler_f handler; u8 type, context; u16 event; type = evt->notif.rceb->bEventType; event = le16_to_cpu(evt->notif.rceb->wEvent); context = evt->notif.rceb->bEventContext; if (type >= ARRAY_SIZE(uwbd_urc_evt_type_handlers)) goto out; type_table = &uwbd_urc_evt_type_handlers[type]; if (type_table->uwbd_events == NULL) goto out; if (event >= type_table->size) goto out; handler = type_table->uwbd_events[event].handler; if (handler == NULL) goto out; result = (*handler)(evt); out: if (result < 0) dev_err(&evt->rc->uwb_dev.dev, "UWBD: event 0x%02x/%04x/%02x, handling failed: %d\n", type, event, context, result); return result; } static void uwbd_event_handle_message(struct uwb_event *evt) { struct uwb_rc *rc; int result; rc = evt->rc; if (evt->message < 0 || evt->message >= ARRAY_SIZE(uwbd_message_handlers)) { dev_err(&rc->uwb_dev.dev, "UWBD: invalid message type %d\n", evt->message); return; } result = uwbd_message_handlers[evt->message].handler(evt); if (result < 0) dev_err(&rc->uwb_dev.dev, "UWBD: '%s' message failed: %d\n", uwbd_message_handlers[evt->message].name, result); } static void uwbd_event_handle(struct uwb_event *evt) { struct uwb_rc *rc; int should_keep; rc = evt->rc; if (rc->ready) { switch (evt->type) { case UWB_EVT_TYPE_NOTIF: should_keep = uwbd_event_handle_urc(evt); if (should_keep <= 0) kfree(evt->notif.rceb); break; case UWB_EVT_TYPE_MSG: uwbd_event_handle_message(evt); break; default: dev_err(&rc->uwb_dev.dev, "UWBD: invalid event type %d\n", evt->type); break; } } __uwb_rc_put(rc); /* for the __uwb_rc_get() in uwb_rc_notif_cb() */ } /** * UWB Daemon * * Listens to all UWB notifications and takes care to track the state * of the UWB neighbourhood for the kernel. When we do a run, we * spinlock, move the list to a private copy and release the * lock. Hold it as little as possible. Not a conflict: it is * guaranteed we own the events in the private list. * * FIXME: should change so we don't have a 1HZ timer all the time, but * only if there are devices. */ static int uwbd(void *param) { struct uwb_rc *rc = param; unsigned long flags; struct uwb_event *evt; int should_stop = 0; while (1) { wait_event_interruptible_timeout( rc->uwbd.wq, !list_empty(&rc->uwbd.event_list) || (should_stop = kthread_should_stop()), HZ); if (should_stop) break; spin_lock_irqsave(&rc->uwbd.event_list_lock, flags); if (!list_empty(&rc->uwbd.event_list)) { evt = list_first_entry(&rc->uwbd.event_list, struct uwb_event, list_node); list_del(&evt->list_node); } else evt = NULL; spin_unlock_irqrestore(&rc->uwbd.event_list_lock, flags); if (evt) { uwbd_event_handle(evt); kfree(evt); } uwb_beca_purge(rc); /* Purge devices that left */ } return 0; } /** Start the UWB daemon */ void uwbd_start(struct uwb_rc *rc) { struct task_struct *task = kthread_run(uwbd, rc, "uwbd"); if (IS_ERR(task)) { rc->uwbd.task = NULL; printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); } else { rc->uwbd.task = task; rc->uwbd.pid = rc->uwbd.task->pid; } } /* Stop the UWB daemon and free any unprocessed events */ void uwbd_stop(struct uwb_rc *rc) { if (rc->uwbd.task) kthread_stop(rc->uwbd.task); uwbd_flush(rc); } /* * Queue an event for the management daemon * * When some lower layer receives an event, it uses this function to * push it forward to the UWB daemon. * * Once you pass the event, you don't own it any more, but the daemon * does. It will uwb_event_free() it when done, so make sure you * uwb_event_alloc()ed it or bad things will happen. * * If the daemon is not running, we just free the event. */ void uwbd_event_queue(struct uwb_event *evt) { struct uwb_rc *rc = evt->rc; unsigned long flags; spin_lock_irqsave(&rc->uwbd.event_list_lock, flags); if (rc->uwbd.pid != 0) { list_add(&evt->list_node, &rc->uwbd.event_list); wake_up_all(&rc->uwbd.wq); } else { __uwb_rc_put(evt->rc); if (evt->type == UWB_EVT_TYPE_NOTIF) kfree(evt->notif.rceb); kfree(evt); } spin_unlock_irqrestore(&rc->uwbd.event_list_lock, flags); return; } void uwbd_flush(struct uwb_rc *rc) { struct uwb_event *evt, *nxt; spin_lock_irq(&rc->uwbd.event_list_lock); list_for_each_entry_safe(evt, nxt, &rc->uwbd.event_list, list_node) { if (evt->rc == rc) { __uwb_rc_put(rc); list_del(&evt->list_node); if (evt->type == UWB_EVT_TYPE_NOTIF) kfree(evt->notif.rceb); kfree(evt); } } spin_unlock_irq(&rc->uwbd.event_list_lock); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2907_0
crossvul-cpp_data_bad_3419_0
/* * ScreenPressor decoder * * Copyright (c) 2017 Paul B Mahol * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "avcodec.h" #include "bytestream.h" #include "internal.h" #define TOP 0x01000000 #define BOT 0x010000 typedef struct RangeCoder { unsigned code; unsigned range; unsigned code1; } RangeCoder; typedef struct PixelModel { unsigned freq[256]; unsigned lookup[16]; unsigned total_freq; } PixelModel; typedef struct SCPRContext { AVFrame *last_frame; AVFrame *current_frame; GetByteContext gb; RangeCoder rc; PixelModel pixel_model[3][4096]; unsigned op_model[6][7]; unsigned run_model[6][257]; unsigned range_model[257]; unsigned count_model[257]; unsigned fill_model[6]; unsigned sxy_model[4][17]; unsigned mv_model[2][513]; unsigned nbx, nby; unsigned nbcount; unsigned *blocks; unsigned cbits; int cxshift; int (*get_freq)(RangeCoder *rc, unsigned total_freq, unsigned *freq); int (*decode)(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq); } SCPRContext; static void init_rangecoder(RangeCoder *rc, GetByteContext *gb) { rc->code1 = 0; rc->range = 0xFFFFFFFFU; rc->code = bytestream2_get_be32(gb); } static void reinit_tables(SCPRContext *s) { int comp, i, j; for (comp = 0; comp < 3; comp++) { for (j = 0; j < 4096; j++) { if (s->pixel_model[comp][j].total_freq != 256) { for (i = 0; i < 256; i++) s->pixel_model[comp][j].freq[i] = 1; for (i = 0; i < 16; i++) s->pixel_model[comp][j].lookup[i] = 16; s->pixel_model[comp][j].total_freq = 256; } } } for (j = 0; j < 6; j++) { unsigned *p = s->run_model[j]; for (i = 0; i < 256; i++) p[i] = 1; p[256] = 256; } for (j = 0; j < 6; j++) { unsigned *op = s->op_model[j]; for (i = 0; i < 6; i++) op[i] = 1; op[6] = 6; } for (i = 0; i < 256; i++) { s->range_model[i] = 1; s->count_model[i] = 1; } s->range_model[256] = 256; s->count_model[256] = 256; for (i = 0; i < 5; i++) { s->fill_model[i] = 1; } s->fill_model[5] = 5; for (j = 0; j < 4; j++) { for (i = 0; i < 16; i++) { s->sxy_model[j][i] = 1; } s->sxy_model[j][16] = 16; } for (i = 0; i < 512; i++) { s->mv_model[0][i] = 1; s->mv_model[1][i] = 1; } s->mv_model[0][512] = 512; s->mv_model[1][512] = 512; } static int decode(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq) { rc->code -= cumFreq * rc->range; rc->range *= freq; while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) { unsigned byte = bytestream2_get_byte(gb); rc->code = (rc->code << 8) | byte; rc->range <<= 8; } return 0; } static int get_freq(RangeCoder *rc, unsigned total_freq, unsigned *freq) { if (total_freq == 0) return AVERROR_INVALIDDATA; rc->range = rc->range / total_freq; if (rc->range == 0) return AVERROR_INVALIDDATA; *freq = rc->code / rc->range; return 0; } static int decode0(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq) { unsigned t; if (total_freq == 0) return AVERROR_INVALIDDATA; t = rc->range * (uint64_t)cumFreq / total_freq; rc->code1 += t + 1; rc->range = rc->range * (uint64_t)(freq + cumFreq) / total_freq - (t + 1); while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) { unsigned byte = bytestream2_get_byte(gb); rc->code = (rc->code << 8) | byte; rc->code1 <<= 8; rc->range <<= 8; } return 0; } static int get_freq0(RangeCoder *rc, unsigned total_freq, unsigned *freq) { if (rc->range == 0) return AVERROR_INVALIDDATA; *freq = total_freq * (uint64_t)(rc->code - rc->code1) / rc->range; return 0; } static int decode_value(SCPRContext *s, unsigned *cnt, unsigned maxc, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = cnt[maxc]; unsigned value; unsigned c = 0, cumfr = 0, cnt_c = 0; int i, ret; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (c < maxc) { cnt_c = cnt[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0) return ret; cnt[c] = cnt_c + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < maxc; i++) { unsigned nc = (cnt[i] >> 1) + 1; cnt[i] = nc; totfr += nc; } } cnt[maxc] = totfr; *rval = c; return 0; } static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = pixel->total_freq; unsigned value, x = 0, cumfr = 0, cnt_x = 0; int i, j, ret, c, cnt_c; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (x < 16) { cnt_x = pixel->lookup[x]; if (value >= cumfr + cnt_x) cumfr += cnt_x; else break; x++; } c = x * 16; cnt_c = 0; while (c < 256) { cnt_c = pixel->freq[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0) return ret; pixel->freq[c] = cnt_c + step; pixel->lookup[x] = cnt_x + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < 256; i++) { unsigned nc = (pixel->freq[i] >> 1) + 1; pixel->freq[i] = nc; totfr += nc; } for (i = 0; i < 16; i++) { unsigned sum = 0; unsigned i16_17 = i << 4; for (j = 0; j < 16; j++) sum += pixel->freq[i16_17 + j]; pixel->lookup[i] = sum; } } pixel->total_freq = totfr; *rval = c & s->cbits; return 0; } static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int cx = 0, cx1 = 0, k = 0, clr = 0; int run, r, g, b, off, y = 0, x = 0, z, ret; unsigned backstep = linesize - avctx->width; const int cxshift = s->cxshift; unsigned lx, ly, ptype; reinit_tables(s); bytestream2_skip(gb, 2); init_rangecoder(&s->rc, gb); while (k < avctx->width + 1) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = b >> cxshift; ret = decode_value(s, s->run_model[0], 256, 400, &run); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; k += run; while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } } off = -linesize - 1; ptype = 0; while (x < avctx->width && y < avctx->height) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ret < 0) return ret; if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 1: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = dst[ly * linesize + lx]; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } clr = dst[ly * linesize + lx]; break; case 2: while (run-- > 0) { if (y < 1 || y >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[y * linesize + x + off + 1]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } r = odst[(ly * linesize + lx) * 4] + odst[((y * linesize + x) + off - z) * 4 + 4] - odst[((y * linesize + x) + off - z) * 4]; g = odst[(ly * linesize + lx) * 4 + 1] + odst[((y * linesize + x) + off - z) * 4 + 5] - odst[((y * linesize + x) + off - z) * 4 + 1]; b = odst[(ly * linesize + lx) * 4 + 2] + odst[((y * linesize + x) + off - z) * 4 + 6] - odst[((y * linesize + x) + off - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 5: while (run-- > 0) { if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } clr = dst[y * linesize + x + off - z]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } return 0; } static int decompress_p(AVCodecContext *avctx, uint32_t *dst, int linesize, uint32_t *prev, int plinesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int ret, temp, min, max, x, y, cx = 0, cx1 = 0; int backstep = linesize - avctx->width; const int cxshift = s->cxshift; if (bytestream2_get_byte(gb) == 0) return 0; bytestream2_skip(gb, 1); init_rangecoder(&s->rc, gb); ret = decode_value(s, s->range_model, 256, 1, &min); ret |= decode_value(s, s->range_model, 256, 1, &temp); min += temp << 8; ret |= decode_value(s, s->range_model, 256, 1, &max); ret |= decode_value(s, s->range_model, 256, 1, &temp); if (ret < 0) return ret; max += temp << 8; memset(s->blocks, 0, sizeof(*s->blocks) * s->nbcount); while (min <= max) { int fill, count; ret = decode_value(s, s->fill_model, 5, 10, &fill); ret |= decode_value(s, s->count_model, 256, 20, &count); if (ret < 0) return ret; while (min < s->nbcount && count-- > 0) { s->blocks[min++] = fill; } } for (y = 0; y < s->nby; y++) { for (x = 0; x < s->nbx; x++) { int sy1 = 0, sy2 = 16, sx1 = 0, sx2 = 16; if (s->blocks[y * s->nbx + x] == 0) continue; if (((s->blocks[y * s->nbx + x] - 1) & 1) > 0) { ret = decode_value(s, s->sxy_model[0], 16, 100, &sx1); ret |= decode_value(s, s->sxy_model[1], 16, 100, &sy1); ret |= decode_value(s, s->sxy_model[2], 16, 100, &sx2); ret |= decode_value(s, s->sxy_model[3], 16, 100, &sy2); if (ret < 0) return ret; sx2++; sy2++; } if (((s->blocks[y * s->nbx + x] - 1) & 2) > 0) { int i, j, by = y * 16, bx = x * 16; int mvx, mvy; ret = decode_value(s, s->mv_model[0], 512, 100, &mvx); ret |= decode_value(s, s->mv_model[1], 512, 100, &mvy); if (ret < 0) return ret; mvx -= 256; mvy -= 256; if (by + mvy + sy1 < 0 || bx + mvx + sx1 < 0 || by + mvy + sy1 >= avctx->height || bx + mvx + sx1 >= avctx->width) return AVERROR_INVALIDDATA; for (i = 0; i < sy2 - sy1 && (by + sy1 + i) < avctx->height && (by + mvy + sy1 + i) < avctx->height; i++) { for (j = 0; j < sx2 - sx1 && (bx + sx1 + j) < avctx->width && (bx + mvx + sx1 + j) < avctx->width; j++) { dst[(by + i + sy1) * linesize + bx + sx1 + j] = prev[(by + mvy + sy1 + i) * plinesize + bx + sx1 + mvx + j]; } } } else { int run, r, g, b, z, bx = x * 16 + sx1, by = y * 16 + sy1; unsigned clr, ptype = 0; for (; by < y * 16 + sy2 && by < avctx->height;) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (by >= avctx->height) return AVERROR_INVALIDDATA; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 1: while (run-- > 0) { if (bx == 0) { if (by < 1) return AVERROR_INVALIDDATA; z = backstep; } else { z = 0; } if (by >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[by * linesize + bx - 1 - z]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 2: while (run-- > 0) { if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[(by - 1) * linesize + bx]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 3: while (run-- > 0) { if (by >= avctx->height) return AVERROR_INVALIDDATA; clr = prev[by * plinesize + bx]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; if (bx == 0) { z = backstep; } else { z = 0; } r = odst[((by - 1) * linesize + bx) * 4] + odst[(by * linesize + bx - 1 - z) * 4] - odst[((by - 1) * linesize + bx - 1 - z) * 4]; g = odst[((by - 1) * linesize + bx) * 4 + 1] + odst[(by * linesize + bx - 1 - z) * 4 + 1] - odst[((by - 1) * linesize + bx - 1 - z) * 4 + 1]; b = odst[((by - 1) * linesize + bx) * 4 + 2] + odst[(by * linesize + bx - 1 - z) * 4 + 2] - odst[((by - 1) * linesize + bx - 1 - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 5: while (run-- > 0) { if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; if (bx == 0) { z = backstep; } else { z = 0; } clr = dst[(by - 1) * linesize + bx - 1 - z]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } } } } return 0; } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; AVFrame *frame = data; int ret, type; if (avctx->bits_per_coded_sample == 16) { if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; } if ((ret = ff_reget_buffer(avctx, s->current_frame)) < 0) return ret; bytestream2_init(gb, avpkt->data, avpkt->size); type = bytestream2_peek_byte(gb); if (type == 2) { s->get_freq = get_freq0; s->decode = decode0; frame->key_frame = 1; ret = decompress_i(avctx, (uint32_t *)s->current_frame->data[0], s->current_frame->linesize[0] / 4); } else if (type == 18) { s->get_freq = get_freq; s->decode = decode; frame->key_frame = 1; ret = decompress_i(avctx, (uint32_t *)s->current_frame->data[0], s->current_frame->linesize[0] / 4); } else if (type == 17) { uint32_t clr, *dst = (uint32_t *)s->current_frame->data[0]; int x, y; frame->key_frame = 1; bytestream2_skip(gb, 1); if (avctx->bits_per_coded_sample == 16) { uint16_t value = bytestream2_get_le16(gb); int r, g, b; r = (value ) & 31; g = (value >> 5) & 31; b = (value >> 10) & 31; clr = (r << 16) + (g << 8) + b; } else { clr = bytestream2_get_le24(gb); } for (y = 0; y < avctx->height; y++) { for (x = 0; x < avctx->width; x++) { dst[x] = clr; } dst += s->current_frame->linesize[0] / 4; } } else if (type == 0 || type == 1) { frame->key_frame = 0; ret = av_frame_copy(s->current_frame, s->last_frame); if (ret < 0) return ret; ret = decompress_p(avctx, (uint32_t *)s->current_frame->data[0], s->current_frame->linesize[0] / 4, (uint32_t *)s->last_frame->data[0], s->last_frame->linesize[0] / 4); } else { return AVERROR_PATCHWELCOME; } if (ret < 0) return ret; if (avctx->bits_per_coded_sample != 16) { ret = av_frame_ref(data, s->current_frame); if (ret < 0) return ret; } else { uint8_t *dst = frame->data[0]; int x, y; ret = av_frame_copy(frame, s->current_frame); if (ret < 0) return ret; for (y = 0; y < avctx->height; y++) { for (x = 0; x < avctx->width * 4; x++) { dst[x] = dst[x] << 3; } dst += frame->linesize[0]; } } frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; FFSWAP(AVFrame *, s->current_frame, s->last_frame); frame->data[0] += frame->linesize[0] * (avctx->height - 1); frame->linesize[0] *= -1; *got_frame = 1; return avpkt->size; } static av_cold int decode_init(AVCodecContext *avctx) { SCPRContext *s = avctx->priv_data; switch (avctx->bits_per_coded_sample) { case 16: avctx->pix_fmt = AV_PIX_FMT_RGB0; break; case 24: case 32: avctx->pix_fmt = AV_PIX_FMT_BGR0; break; default: av_log(avctx, AV_LOG_ERROR, "Unsupported bitdepth %i\n", avctx->bits_per_coded_sample); return AVERROR_INVALIDDATA; } s->get_freq = get_freq0; s->decode = decode0; s->cxshift = avctx->bits_per_coded_sample == 16 ? 0 : 2; s->cbits = avctx->bits_per_coded_sample == 16 ? 0x1F : 0xFF; s->nbx = (avctx->width + 15) / 16; s->nby = (avctx->height + 15) / 16; s->nbcount = s->nbx * s->nby; s->blocks = av_malloc_array(s->nbcount, sizeof(*s->blocks)); if (!s->blocks) return AVERROR(ENOMEM); s->last_frame = av_frame_alloc(); s->current_frame = av_frame_alloc(); if (!s->last_frame || !s->current_frame) return AVERROR(ENOMEM); return 0; } static av_cold int decode_close(AVCodecContext *avctx) { SCPRContext *s = avctx->priv_data; av_freep(&s->blocks); av_frame_free(&s->last_frame); av_frame_free(&s->current_frame); return 0; } AVCodec ff_scpr_decoder = { .name = "scpr", .long_name = NULL_IF_CONFIG_SMALL("ScreenPressor"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_SCPR, .priv_data_size = sizeof(SCPRContext), .init = decode_init, .close = decode_close, .decode = decode_frame, .capabilities = AV_CODEC_CAP_DR1, .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3419_0
crossvul-cpp_data_good_3687_0
/* * super.c * * PURPOSE * Super block routines for the OSTA-UDF(tm) filesystem. * * DESCRIPTION * OSTA-UDF(tm) = Optical Storage Technology Association * Universal Disk Format. * * This code is based on version 2.00 of the UDF specification, * and revision 3 of the ECMA 167 standard [equivalent to ISO 13346]. * http://www.osta.org/ * http://www.ecma.ch/ * http://www.iso.org/ * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. * * (C) 1998 Dave Boynton * (C) 1998-2004 Ben Fennema * (C) 2000 Stelias Computing Inc * * HISTORY * * 09/24/98 dgb changed to allow compiling outside of kernel, and * added some debugging. * 10/01/98 dgb updated to allow (some) possibility of compiling w/2.0.34 * 10/16/98 attempting some multi-session support * 10/17/98 added freespace count for "df" * 11/11/98 gr added novrs option * 11/26/98 dgb added fileset,anchor mount options * 12/06/98 blf really hosed things royally. vat/sparing support. sequenced * vol descs. rewrote option handling based on isofs * 12/20/98 find the free space bitmap (if it exists) */ #include "udfdecl.h" #include <linux/blkdev.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/parser.h> #include <linux/stat.h> #include <linux/cdrom.h> #include <linux/nls.h> #include <linux/buffer_head.h> #include <linux/vfs.h> #include <linux/vmalloc.h> #include <linux/errno.h> #include <linux/mount.h> #include <linux/seq_file.h> #include <linux/bitmap.h> #include <linux/crc-itu-t.h> #include <asm/byteorder.h> #include "udf_sb.h" #include "udf_i.h" #include <linux/init.h> #include <asm/uaccess.h> #define VDS_POS_PRIMARY_VOL_DESC 0 #define VDS_POS_UNALLOC_SPACE_DESC 1 #define VDS_POS_LOGICAL_VOL_DESC 2 #define VDS_POS_PARTITION_DESC 3 #define VDS_POS_IMP_USE_VOL_DESC 4 #define VDS_POS_VOL_DESC_PTR 5 #define VDS_POS_TERMINATING_DESC 6 #define VDS_POS_LENGTH 7 #define UDF_DEFAULT_BLOCKSIZE 2048 enum { UDF_MAX_LINKS = 0xffff }; /* These are the "meat" - everything else is stuffing */ static int udf_fill_super(struct super_block *, void *, int); static void udf_put_super(struct super_block *); static int udf_sync_fs(struct super_block *, int); static int udf_remount_fs(struct super_block *, int *, char *); static void udf_load_logicalvolint(struct super_block *, struct kernel_extent_ad); static int udf_find_fileset(struct super_block *, struct kernel_lb_addr *, struct kernel_lb_addr *); static void udf_load_fileset(struct super_block *, struct buffer_head *, struct kernel_lb_addr *); static void udf_open_lvid(struct super_block *); static void udf_close_lvid(struct super_block *); static unsigned int udf_count_free(struct super_block *); static int udf_statfs(struct dentry *, struct kstatfs *); static int udf_show_options(struct seq_file *, struct dentry *); struct logicalVolIntegrityDescImpUse *udf_sb_lvidiu(struct udf_sb_info *sbi) { struct logicalVolIntegrityDesc *lvid = (struct logicalVolIntegrityDesc *)sbi->s_lvid_bh->b_data; __u32 number_of_partitions = le32_to_cpu(lvid->numOfPartitions); __u32 offset = number_of_partitions * 2 * sizeof(uint32_t)/sizeof(uint8_t); return (struct logicalVolIntegrityDescImpUse *)&(lvid->impUse[offset]); } /* UDF filesystem type */ static struct dentry *udf_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_bdev(fs_type, flags, dev_name, data, udf_fill_super); } static struct file_system_type udf_fstype = { .owner = THIS_MODULE, .name = "udf", .mount = udf_mount, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; static struct kmem_cache *udf_inode_cachep; static struct inode *udf_alloc_inode(struct super_block *sb) { struct udf_inode_info *ei; ei = kmem_cache_alloc(udf_inode_cachep, GFP_KERNEL); if (!ei) return NULL; ei->i_unique = 0; ei->i_lenExtents = 0; ei->i_next_alloc_block = 0; ei->i_next_alloc_goal = 0; ei->i_strat4096 = 0; init_rwsem(&ei->i_data_sem); return &ei->vfs_inode; } static void udf_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(udf_inode_cachep, UDF_I(inode)); } static void udf_destroy_inode(struct inode *inode) { call_rcu(&inode->i_rcu, udf_i_callback); } static void init_once(void *foo) { struct udf_inode_info *ei = (struct udf_inode_info *)foo; ei->i_ext.i_data = NULL; inode_init_once(&ei->vfs_inode); } static int init_inodecache(void) { udf_inode_cachep = kmem_cache_create("udf_inode_cache", sizeof(struct udf_inode_info), 0, (SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD), init_once); if (!udf_inode_cachep) return -ENOMEM; return 0; } static void destroy_inodecache(void) { kmem_cache_destroy(udf_inode_cachep); } /* Superblock operations */ static const struct super_operations udf_sb_ops = { .alloc_inode = udf_alloc_inode, .destroy_inode = udf_destroy_inode, .write_inode = udf_write_inode, .evict_inode = udf_evict_inode, .put_super = udf_put_super, .sync_fs = udf_sync_fs, .statfs = udf_statfs, .remount_fs = udf_remount_fs, .show_options = udf_show_options, }; struct udf_options { unsigned char novrs; unsigned int blocksize; unsigned int session; unsigned int lastblock; unsigned int anchor; unsigned int volume; unsigned short partition; unsigned int fileset; unsigned int rootdir; unsigned int flags; umode_t umask; gid_t gid; uid_t uid; umode_t fmode; umode_t dmode; struct nls_table *nls_map; }; static int __init init_udf_fs(void) { int err; err = init_inodecache(); if (err) goto out1; err = register_filesystem(&udf_fstype); if (err) goto out; return 0; out: destroy_inodecache(); out1: return err; } static void __exit exit_udf_fs(void) { unregister_filesystem(&udf_fstype); destroy_inodecache(); } module_init(init_udf_fs) module_exit(exit_udf_fs) static int udf_sb_alloc_partition_maps(struct super_block *sb, u32 count) { struct udf_sb_info *sbi = UDF_SB(sb); sbi->s_partmaps = kcalloc(count, sizeof(struct udf_part_map), GFP_KERNEL); if (!sbi->s_partmaps) { udf_err(sb, "Unable to allocate space for %d partition maps\n", count); sbi->s_partitions = 0; return -ENOMEM; } sbi->s_partitions = count; return 0; } static int udf_show_options(struct seq_file *seq, struct dentry *root) { struct super_block *sb = root->d_sb; struct udf_sb_info *sbi = UDF_SB(sb); if (!UDF_QUERY_FLAG(sb, UDF_FLAG_STRICT)) seq_puts(seq, ",nostrict"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_BLOCKSIZE_SET)) seq_printf(seq, ",bs=%lu", sb->s_blocksize); if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNHIDE)) seq_puts(seq, ",unhide"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNDELETE)) seq_puts(seq, ",undelete"); if (!UDF_QUERY_FLAG(sb, UDF_FLAG_USE_AD_IN_ICB)) seq_puts(seq, ",noadinicb"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_USE_SHORT_AD)) seq_puts(seq, ",shortad"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_FORGET)) seq_puts(seq, ",uid=forget"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_IGNORE)) seq_puts(seq, ",uid=ignore"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_FORGET)) seq_puts(seq, ",gid=forget"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_IGNORE)) seq_puts(seq, ",gid=ignore"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_SET)) seq_printf(seq, ",uid=%u", sbi->s_uid); if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_SET)) seq_printf(seq, ",gid=%u", sbi->s_gid); if (sbi->s_umask != 0) seq_printf(seq, ",umask=%ho", sbi->s_umask); if (sbi->s_fmode != UDF_INVALID_MODE) seq_printf(seq, ",mode=%ho", sbi->s_fmode); if (sbi->s_dmode != UDF_INVALID_MODE) seq_printf(seq, ",dmode=%ho", sbi->s_dmode); if (UDF_QUERY_FLAG(sb, UDF_FLAG_SESSION_SET)) seq_printf(seq, ",session=%u", sbi->s_session); if (UDF_QUERY_FLAG(sb, UDF_FLAG_LASTBLOCK_SET)) seq_printf(seq, ",lastblock=%u", sbi->s_last_block); if (sbi->s_anchor != 0) seq_printf(seq, ",anchor=%u", sbi->s_anchor); /* * volume, partition, fileset and rootdir seem to be ignored * currently */ if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) seq_puts(seq, ",utf8"); if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP) && sbi->s_nls_map) seq_printf(seq, ",iocharset=%s", sbi->s_nls_map->charset); return 0; } /* * udf_parse_options * * PURPOSE * Parse mount options. * * DESCRIPTION * The following mount options are supported: * * gid= Set the default group. * umask= Set the default umask. * mode= Set the default file permissions. * dmode= Set the default directory permissions. * uid= Set the default user. * bs= Set the block size. * unhide Show otherwise hidden files. * undelete Show deleted files in lists. * adinicb Embed data in the inode (default) * noadinicb Don't embed data in the inode * shortad Use short ad's * longad Use long ad's (default) * nostrict Unset strict conformance * iocharset= Set the NLS character set * * The remaining are for debugging and disaster recovery: * * novrs Skip volume sequence recognition * * The following expect a offset from 0. * * session= Set the CDROM session (default= last session) * anchor= Override standard anchor location. (default= 256) * volume= Override the VolumeDesc location. (unused) * partition= Override the PartitionDesc location. (unused) * lastblock= Set the last block of the filesystem/ * * The following expect a offset from the partition root. * * fileset= Override the fileset block location. (unused) * rootdir= Override the root directory location. (unused) * WARNING: overriding the rootdir to a non-directory may * yield highly unpredictable results. * * PRE-CONDITIONS * options Pointer to mount options string. * uopts Pointer to mount options variable. * * POST-CONDITIONS * <return> 1 Mount options parsed okay. * <return> 0 Error parsing mount options. * * HISTORY * July 1, 1997 - Andrew E. Mileski * Written, tested, and released. */ enum { Opt_novrs, Opt_nostrict, Opt_bs, Opt_unhide, Opt_undelete, Opt_noadinicb, Opt_adinicb, Opt_shortad, Opt_longad, Opt_gid, Opt_uid, Opt_umask, Opt_session, Opt_lastblock, Opt_anchor, Opt_volume, Opt_partition, Opt_fileset, Opt_rootdir, Opt_utf8, Opt_iocharset, Opt_err, Opt_uforget, Opt_uignore, Opt_gforget, Opt_gignore, Opt_fmode, Opt_dmode }; static const match_table_t tokens = { {Opt_novrs, "novrs"}, {Opt_nostrict, "nostrict"}, {Opt_bs, "bs=%u"}, {Opt_unhide, "unhide"}, {Opt_undelete, "undelete"}, {Opt_noadinicb, "noadinicb"}, {Opt_adinicb, "adinicb"}, {Opt_shortad, "shortad"}, {Opt_longad, "longad"}, {Opt_uforget, "uid=forget"}, {Opt_uignore, "uid=ignore"}, {Opt_gforget, "gid=forget"}, {Opt_gignore, "gid=ignore"}, {Opt_gid, "gid=%u"}, {Opt_uid, "uid=%u"}, {Opt_umask, "umask=%o"}, {Opt_session, "session=%u"}, {Opt_lastblock, "lastblock=%u"}, {Opt_anchor, "anchor=%u"}, {Opt_volume, "volume=%u"}, {Opt_partition, "partition=%u"}, {Opt_fileset, "fileset=%u"}, {Opt_rootdir, "rootdir=%u"}, {Opt_utf8, "utf8"}, {Opt_iocharset, "iocharset=%s"}, {Opt_fmode, "mode=%o"}, {Opt_dmode, "dmode=%o"}, {Opt_err, NULL} }; static int udf_parse_options(char *options, struct udf_options *uopt, bool remount) { char *p; int option; uopt->novrs = 0; uopt->partition = 0xFFFF; uopt->session = 0xFFFFFFFF; uopt->lastblock = 0; uopt->anchor = 0; uopt->volume = 0xFFFFFFFF; uopt->rootdir = 0xFFFFFFFF; uopt->fileset = 0xFFFFFFFF; uopt->nls_map = NULL; if (!options) return 1; while ((p = strsep(&options, ",")) != NULL) { substring_t args[MAX_OPT_ARGS]; int token; if (!*p) continue; token = match_token(p, tokens, args); switch (token) { case Opt_novrs: uopt->novrs = 1; break; case Opt_bs: if (match_int(&args[0], &option)) return 0; uopt->blocksize = option; uopt->flags |= (1 << UDF_FLAG_BLOCKSIZE_SET); break; case Opt_unhide: uopt->flags |= (1 << UDF_FLAG_UNHIDE); break; case Opt_undelete: uopt->flags |= (1 << UDF_FLAG_UNDELETE); break; case Opt_noadinicb: uopt->flags &= ~(1 << UDF_FLAG_USE_AD_IN_ICB); break; case Opt_adinicb: uopt->flags |= (1 << UDF_FLAG_USE_AD_IN_ICB); break; case Opt_shortad: uopt->flags |= (1 << UDF_FLAG_USE_SHORT_AD); break; case Opt_longad: uopt->flags &= ~(1 << UDF_FLAG_USE_SHORT_AD); break; case Opt_gid: if (match_int(args, &option)) return 0; uopt->gid = option; uopt->flags |= (1 << UDF_FLAG_GID_SET); break; case Opt_uid: if (match_int(args, &option)) return 0; uopt->uid = option; uopt->flags |= (1 << UDF_FLAG_UID_SET); break; case Opt_umask: if (match_octal(args, &option)) return 0; uopt->umask = option; break; case Opt_nostrict: uopt->flags &= ~(1 << UDF_FLAG_STRICT); break; case Opt_session: if (match_int(args, &option)) return 0; uopt->session = option; if (!remount) uopt->flags |= (1 << UDF_FLAG_SESSION_SET); break; case Opt_lastblock: if (match_int(args, &option)) return 0; uopt->lastblock = option; if (!remount) uopt->flags |= (1 << UDF_FLAG_LASTBLOCK_SET); break; case Opt_anchor: if (match_int(args, &option)) return 0; uopt->anchor = option; break; case Opt_volume: if (match_int(args, &option)) return 0; uopt->volume = option; break; case Opt_partition: if (match_int(args, &option)) return 0; uopt->partition = option; break; case Opt_fileset: if (match_int(args, &option)) return 0; uopt->fileset = option; break; case Opt_rootdir: if (match_int(args, &option)) return 0; uopt->rootdir = option; break; case Opt_utf8: uopt->flags |= (1 << UDF_FLAG_UTF8); break; #ifdef CONFIG_UDF_NLS case Opt_iocharset: uopt->nls_map = load_nls(args[0].from); uopt->flags |= (1 << UDF_FLAG_NLS_MAP); break; #endif case Opt_uignore: uopt->flags |= (1 << UDF_FLAG_UID_IGNORE); break; case Opt_uforget: uopt->flags |= (1 << UDF_FLAG_UID_FORGET); break; case Opt_gignore: uopt->flags |= (1 << UDF_FLAG_GID_IGNORE); break; case Opt_gforget: uopt->flags |= (1 << UDF_FLAG_GID_FORGET); break; case Opt_fmode: if (match_octal(args, &option)) return 0; uopt->fmode = option & 0777; break; case Opt_dmode: if (match_octal(args, &option)) return 0; uopt->dmode = option & 0777; break; default: pr_err("bad mount option \"%s\" or missing value\n", p); return 0; } } return 1; } static int udf_remount_fs(struct super_block *sb, int *flags, char *options) { struct udf_options uopt; struct udf_sb_info *sbi = UDF_SB(sb); int error = 0; uopt.flags = sbi->s_flags; uopt.uid = sbi->s_uid; uopt.gid = sbi->s_gid; uopt.umask = sbi->s_umask; uopt.fmode = sbi->s_fmode; uopt.dmode = sbi->s_dmode; if (!udf_parse_options(options, &uopt, true)) return -EINVAL; write_lock(&sbi->s_cred_lock); sbi->s_flags = uopt.flags; sbi->s_uid = uopt.uid; sbi->s_gid = uopt.gid; sbi->s_umask = uopt.umask; sbi->s_fmode = uopt.fmode; sbi->s_dmode = uopt.dmode; write_unlock(&sbi->s_cred_lock); if (sbi->s_lvid_bh) { int write_rev = le16_to_cpu(udf_sb_lvidiu(sbi)->minUDFWriteRev); if (write_rev > UDF_MAX_WRITE_VERSION) *flags |= MS_RDONLY; } if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY)) goto out_unlock; if (*flags & MS_RDONLY) udf_close_lvid(sb); else udf_open_lvid(sb); out_unlock: return error; } /* Check Volume Structure Descriptors (ECMA 167 2/9.1) */ /* We also check any "CD-ROM Volume Descriptor Set" (ECMA 167 2/8.3.1) */ static loff_t udf_check_vsd(struct super_block *sb) { struct volStructDesc *vsd = NULL; loff_t sector = 32768; int sectorsize; struct buffer_head *bh = NULL; int nsr02 = 0; int nsr03 = 0; struct udf_sb_info *sbi; sbi = UDF_SB(sb); if (sb->s_blocksize < sizeof(struct volStructDesc)) sectorsize = sizeof(struct volStructDesc); else sectorsize = sb->s_blocksize; sector += (sbi->s_session << sb->s_blocksize_bits); udf_debug("Starting at sector %u (%ld byte sectors)\n", (unsigned int)(sector >> sb->s_blocksize_bits), sb->s_blocksize); /* Process the sequence (if applicable) */ for (; !nsr02 && !nsr03; sector += sectorsize) { /* Read a block */ bh = udf_tread(sb, sector >> sb->s_blocksize_bits); if (!bh) break; /* Look for ISO descriptors */ vsd = (struct volStructDesc *)(bh->b_data + (sector & (sb->s_blocksize - 1))); if (vsd->stdIdent[0] == 0) { brelse(bh); break; } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_CD001, VSD_STD_ID_LEN)) { switch (vsd->structType) { case 0: udf_debug("ISO9660 Boot Record found\n"); break; case 1: udf_debug("ISO9660 Primary Volume Descriptor found\n"); break; case 2: udf_debug("ISO9660 Supplementary Volume Descriptor found\n"); break; case 3: udf_debug("ISO9660 Volume Partition Descriptor found\n"); break; case 255: udf_debug("ISO9660 Volume Descriptor Set Terminator found\n"); break; default: udf_debug("ISO9660 VRS (%u) found\n", vsd->structType); break; } } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_BEA01, VSD_STD_ID_LEN)) ; /* nothing */ else if (!strncmp(vsd->stdIdent, VSD_STD_ID_TEA01, VSD_STD_ID_LEN)) { brelse(bh); break; } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR02, VSD_STD_ID_LEN)) nsr02 = sector; else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR03, VSD_STD_ID_LEN)) nsr03 = sector; brelse(bh); } if (nsr03) return nsr03; else if (nsr02) return nsr02; else if (sector - (sbi->s_session << sb->s_blocksize_bits) == 32768) return -1; else return 0; } static int udf_find_fileset(struct super_block *sb, struct kernel_lb_addr *fileset, struct kernel_lb_addr *root) { struct buffer_head *bh = NULL; long lastblock; uint16_t ident; struct udf_sb_info *sbi; if (fileset->logicalBlockNum != 0xFFFFFFFF || fileset->partitionReferenceNum != 0xFFFF) { bh = udf_read_ptagged(sb, fileset, 0, &ident); if (!bh) { return 1; } else if (ident != TAG_IDENT_FSD) { brelse(bh); return 1; } } sbi = UDF_SB(sb); if (!bh) { /* Search backwards through the partitions */ struct kernel_lb_addr newfileset; /* --> cvg: FIXME - is it reasonable? */ return 1; for (newfileset.partitionReferenceNum = sbi->s_partitions - 1; (newfileset.partitionReferenceNum != 0xFFFF && fileset->logicalBlockNum == 0xFFFFFFFF && fileset->partitionReferenceNum == 0xFFFF); newfileset.partitionReferenceNum--) { lastblock = sbi->s_partmaps [newfileset.partitionReferenceNum] .s_partition_len; newfileset.logicalBlockNum = 0; do { bh = udf_read_ptagged(sb, &newfileset, 0, &ident); if (!bh) { newfileset.logicalBlockNum++; continue; } switch (ident) { case TAG_IDENT_SBD: { struct spaceBitmapDesc *sp; sp = (struct spaceBitmapDesc *) bh->b_data; newfileset.logicalBlockNum += 1 + ((le32_to_cpu(sp->numOfBytes) + sizeof(struct spaceBitmapDesc) - 1) >> sb->s_blocksize_bits); brelse(bh); break; } case TAG_IDENT_FSD: *fileset = newfileset; break; default: newfileset.logicalBlockNum++; brelse(bh); bh = NULL; break; } } while (newfileset.logicalBlockNum < lastblock && fileset->logicalBlockNum == 0xFFFFFFFF && fileset->partitionReferenceNum == 0xFFFF); } } if ((fileset->logicalBlockNum != 0xFFFFFFFF || fileset->partitionReferenceNum != 0xFFFF) && bh) { udf_debug("Fileset at block=%d, partition=%d\n", fileset->logicalBlockNum, fileset->partitionReferenceNum); sbi->s_partition = fileset->partitionReferenceNum; udf_load_fileset(sb, bh, root); brelse(bh); return 0; } return 1; } static int udf_load_pvoldesc(struct super_block *sb, sector_t block) { struct primaryVolDesc *pvoldesc; struct ustr *instr, *outstr; struct buffer_head *bh; uint16_t ident; int ret = 1; instr = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!instr) return 1; outstr = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!outstr) goto out1; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) goto out2; BUG_ON(ident != TAG_IDENT_PVD); pvoldesc = (struct primaryVolDesc *)bh->b_data; if (udf_disk_stamp_to_time(&UDF_SB(sb)->s_record_time, pvoldesc->recordingDateAndTime)) { #ifdef UDFFS_DEBUG struct timestamp *ts = &pvoldesc->recordingDateAndTime; udf_debug("recording time %04u/%02u/%02u %02u:%02u (%x)\n", le16_to_cpu(ts->year), ts->month, ts->day, ts->hour, ts->minute, le16_to_cpu(ts->typeAndTimezone)); #endif } if (!udf_build_ustr(instr, pvoldesc->volIdent, 32)) if (udf_CS0toUTF8(outstr, instr)) { strncpy(UDF_SB(sb)->s_volume_ident, outstr->u_name, outstr->u_len > 31 ? 31 : outstr->u_len); udf_debug("volIdent[] = '%s'\n", UDF_SB(sb)->s_volume_ident); } if (!udf_build_ustr(instr, pvoldesc->volSetIdent, 128)) if (udf_CS0toUTF8(outstr, instr)) udf_debug("volSetIdent[] = '%s'\n", outstr->u_name); brelse(bh); ret = 0; out2: kfree(outstr); out1: kfree(instr); return ret; } struct inode *udf_find_metadata_inode_efe(struct super_block *sb, u32 meta_file_loc, u32 partition_num) { struct kernel_lb_addr addr; struct inode *metadata_fe; addr.logicalBlockNum = meta_file_loc; addr.partitionReferenceNum = partition_num; metadata_fe = udf_iget(sb, &addr); if (metadata_fe == NULL) udf_warn(sb, "metadata inode efe not found\n"); else if (UDF_I(metadata_fe)->i_alloc_type != ICBTAG_FLAG_AD_SHORT) { udf_warn(sb, "metadata inode efe does not have short allocation descriptors!\n"); iput(metadata_fe); metadata_fe = NULL; } return metadata_fe; } static int udf_load_metadata_files(struct super_block *sb, int partition) { struct udf_sb_info *sbi = UDF_SB(sb); struct udf_part_map *map; struct udf_meta_data *mdata; struct kernel_lb_addr addr; map = &sbi->s_partmaps[partition]; mdata = &map->s_type_specific.s_metadata; /* metadata address */ udf_debug("Metadata file location: block = %d part = %d\n", mdata->s_meta_file_loc, map->s_partition_num); mdata->s_metadata_fe = udf_find_metadata_inode_efe(sb, mdata->s_meta_file_loc, map->s_partition_num); if (mdata->s_metadata_fe == NULL) { /* mirror file entry */ udf_debug("Mirror metadata file location: block = %d part = %d\n", mdata->s_mirror_file_loc, map->s_partition_num); mdata->s_mirror_fe = udf_find_metadata_inode_efe(sb, mdata->s_mirror_file_loc, map->s_partition_num); if (mdata->s_mirror_fe == NULL) { udf_err(sb, "Both metadata and mirror metadata inode efe can not found\n"); goto error_exit; } } /* * bitmap file entry * Note: * Load only if bitmap file location differs from 0xFFFFFFFF (DCN-5102) */ if (mdata->s_bitmap_file_loc != 0xFFFFFFFF) { addr.logicalBlockNum = mdata->s_bitmap_file_loc; addr.partitionReferenceNum = map->s_partition_num; udf_debug("Bitmap file location: block = %d part = %d\n", addr.logicalBlockNum, addr.partitionReferenceNum); mdata->s_bitmap_fe = udf_iget(sb, &addr); if (mdata->s_bitmap_fe == NULL) { if (sb->s_flags & MS_RDONLY) udf_warn(sb, "bitmap inode efe not found but it's ok since the disc is mounted read-only\n"); else { udf_err(sb, "bitmap inode efe not found and attempted read-write mount\n"); goto error_exit; } } } udf_debug("udf_load_metadata_files Ok\n"); return 0; error_exit: return 1; } static void udf_load_fileset(struct super_block *sb, struct buffer_head *bh, struct kernel_lb_addr *root) { struct fileSetDesc *fset; fset = (struct fileSetDesc *)bh->b_data; *root = lelb_to_cpu(fset->rootDirectoryICB.extLocation); UDF_SB(sb)->s_serial_number = le16_to_cpu(fset->descTag.tagSerialNum); udf_debug("Rootdir at block=%d, partition=%d\n", root->logicalBlockNum, root->partitionReferenceNum); } int udf_compute_nr_groups(struct super_block *sb, u32 partition) { struct udf_part_map *map = &UDF_SB(sb)->s_partmaps[partition]; return DIV_ROUND_UP(map->s_partition_len + (sizeof(struct spaceBitmapDesc) << 3), sb->s_blocksize * 8); } static struct udf_bitmap *udf_sb_alloc_bitmap(struct super_block *sb, u32 index) { struct udf_bitmap *bitmap; int nr_groups; int size; nr_groups = udf_compute_nr_groups(sb, index); size = sizeof(struct udf_bitmap) + (sizeof(struct buffer_head *) * nr_groups); if (size <= PAGE_SIZE) bitmap = kzalloc(size, GFP_KERNEL); else bitmap = vzalloc(size); /* TODO: get rid of vzalloc */ if (bitmap == NULL) return NULL; bitmap->s_block_bitmap = (struct buffer_head **)(bitmap + 1); bitmap->s_nr_groups = nr_groups; return bitmap; } static int udf_fill_partdesc_info(struct super_block *sb, struct partitionDesc *p, int p_index) { struct udf_part_map *map; struct udf_sb_info *sbi = UDF_SB(sb); struct partitionHeaderDesc *phd; map = &sbi->s_partmaps[p_index]; map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */ map->s_partition_root = le32_to_cpu(p->partitionStartingLocation); if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY)) map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY; if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE)) map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE; if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE)) map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE; if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE)) map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE; udf_debug("Partition (%d type %x) starts at physical %d, block length %d\n", p_index, map->s_partition_type, map->s_partition_root, map->s_partition_len); if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) && strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03)) return 0; phd = (struct partitionHeaderDesc *)p->partitionContentsUse; if (phd->unallocSpaceTable.extLength) { struct kernel_lb_addr loc = { .logicalBlockNum = le32_to_cpu( phd->unallocSpaceTable.extPosition), .partitionReferenceNum = p_index, }; map->s_uspace.s_table = udf_iget(sb, &loc); if (!map->s_uspace.s_table) { udf_debug("cannot load unallocSpaceTable (part %d)\n", p_index); return 1; } map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE; udf_debug("unallocSpaceTable (part %d) @ %ld\n", p_index, map->s_uspace.s_table->i_ino); } if (phd->unallocSpaceBitmap.extLength) { struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index); if (!bitmap) return 1; map->s_uspace.s_bitmap = bitmap; bitmap->s_extLength = le32_to_cpu( phd->unallocSpaceBitmap.extLength); bitmap->s_extPosition = le32_to_cpu( phd->unallocSpaceBitmap.extPosition); map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP; udf_debug("unallocSpaceBitmap (part %d) @ %d\n", p_index, bitmap->s_extPosition); } if (phd->partitionIntegrityTable.extLength) udf_debug("partitionIntegrityTable (part %d)\n", p_index); if (phd->freedSpaceTable.extLength) { struct kernel_lb_addr loc = { .logicalBlockNum = le32_to_cpu( phd->freedSpaceTable.extPosition), .partitionReferenceNum = p_index, }; map->s_fspace.s_table = udf_iget(sb, &loc); if (!map->s_fspace.s_table) { udf_debug("cannot load freedSpaceTable (part %d)\n", p_index); return 1; } map->s_partition_flags |= UDF_PART_FLAG_FREED_TABLE; udf_debug("freedSpaceTable (part %d) @ %ld\n", p_index, map->s_fspace.s_table->i_ino); } if (phd->freedSpaceBitmap.extLength) { struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index); if (!bitmap) return 1; map->s_fspace.s_bitmap = bitmap; bitmap->s_extLength = le32_to_cpu( phd->freedSpaceBitmap.extLength); bitmap->s_extPosition = le32_to_cpu( phd->freedSpaceBitmap.extPosition); map->s_partition_flags |= UDF_PART_FLAG_FREED_BITMAP; udf_debug("freedSpaceBitmap (part %d) @ %d\n", p_index, bitmap->s_extPosition); } return 0; } static void udf_find_vat_block(struct super_block *sb, int p_index, int type1_index, sector_t start_block) { struct udf_sb_info *sbi = UDF_SB(sb); struct udf_part_map *map = &sbi->s_partmaps[p_index]; sector_t vat_block; struct kernel_lb_addr ino; /* * VAT file entry is in the last recorded block. Some broken disks have * it a few blocks before so try a bit harder... */ ino.partitionReferenceNum = type1_index; for (vat_block = start_block; vat_block >= map->s_partition_root && vat_block >= start_block - 3 && !sbi->s_vat_inode; vat_block--) { ino.logicalBlockNum = vat_block - map->s_partition_root; sbi->s_vat_inode = udf_iget(sb, &ino); } } static int udf_load_vat(struct super_block *sb, int p_index, int type1_index) { struct udf_sb_info *sbi = UDF_SB(sb); struct udf_part_map *map = &sbi->s_partmaps[p_index]; struct buffer_head *bh = NULL; struct udf_inode_info *vati; uint32_t pos; struct virtualAllocationTable20 *vat20; sector_t blocks = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block); if (!sbi->s_vat_inode && sbi->s_last_block != blocks - 1) { pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n", (unsigned long)sbi->s_last_block, (unsigned long)blocks - 1); udf_find_vat_block(sb, p_index, type1_index, blocks - 1); } if (!sbi->s_vat_inode) return 1; if (map->s_partition_type == UDF_VIRTUAL_MAP15) { map->s_type_specific.s_virtual.s_start_offset = 0; map->s_type_specific.s_virtual.s_num_entries = (sbi->s_vat_inode->i_size - 36) >> 2; } else if (map->s_partition_type == UDF_VIRTUAL_MAP20) { vati = UDF_I(sbi->s_vat_inode); if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { pos = udf_block_map(sbi->s_vat_inode, 0); bh = sb_bread(sb, pos); if (!bh) return 1; vat20 = (struct virtualAllocationTable20 *)bh->b_data; } else { vat20 = (struct virtualAllocationTable20 *) vati->i_ext.i_data; } map->s_type_specific.s_virtual.s_start_offset = le16_to_cpu(vat20->lengthHeader); map->s_type_specific.s_virtual.s_num_entries = (sbi->s_vat_inode->i_size - map->s_type_specific.s_virtual. s_start_offset) >> 2; brelse(bh); } return 0; } static int udf_load_partdesc(struct super_block *sb, sector_t block) { struct buffer_head *bh; struct partitionDesc *p; struct udf_part_map *map; struct udf_sb_info *sbi = UDF_SB(sb); int i, type1_idx; uint16_t partitionNumber; uint16_t ident; int ret = 0; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) return 1; if (ident != TAG_IDENT_PD) goto out_bh; p = (struct partitionDesc *)bh->b_data; partitionNumber = le16_to_cpu(p->partitionNumber); /* First scan for TYPE1, SPARABLE and METADATA partitions */ for (i = 0; i < sbi->s_partitions; i++) { map = &sbi->s_partmaps[i]; udf_debug("Searching map: (%d == %d)\n", map->s_partition_num, partitionNumber); if (map->s_partition_num == partitionNumber && (map->s_partition_type == UDF_TYPE1_MAP15 || map->s_partition_type == UDF_SPARABLE_MAP15)) break; } if (i >= sbi->s_partitions) { udf_debug("Partition (%d) not found in partition map\n", partitionNumber); goto out_bh; } ret = udf_fill_partdesc_info(sb, p, i); /* * Now rescan for VIRTUAL or METADATA partitions when SPARABLE and * PHYSICAL partitions are already set up */ type1_idx = i; for (i = 0; i < sbi->s_partitions; i++) { map = &sbi->s_partmaps[i]; if (map->s_partition_num == partitionNumber && (map->s_partition_type == UDF_VIRTUAL_MAP15 || map->s_partition_type == UDF_VIRTUAL_MAP20 || map->s_partition_type == UDF_METADATA_MAP25)) break; } if (i >= sbi->s_partitions) goto out_bh; ret = udf_fill_partdesc_info(sb, p, i); if (ret) goto out_bh; if (map->s_partition_type == UDF_METADATA_MAP25) { ret = udf_load_metadata_files(sb, i); if (ret) { udf_err(sb, "error loading MetaData partition map %d\n", i); goto out_bh; } } else { ret = udf_load_vat(sb, i, type1_idx); if (ret) goto out_bh; /* * Mark filesystem read-only if we have a partition with * virtual map since we don't handle writing to it (we * overwrite blocks instead of relocating them). */ sb->s_flags |= MS_RDONLY; pr_notice("Filesystem marked read-only because writing to pseudooverwrite partition is not implemented\n"); } out_bh: /* In case loading failed, we handle cleanup in udf_fill_super */ brelse(bh); return ret; } static int udf_load_logicalvol(struct super_block *sb, sector_t block, struct kernel_lb_addr *fileset) { struct logicalVolDesc *lvd; int i, j, offset; uint8_t type; struct udf_sb_info *sbi = UDF_SB(sb); struct genericPartitionMap *gpm; uint16_t ident; struct buffer_head *bh; unsigned int table_len; int ret = 0; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) return 1; BUG_ON(ident != TAG_IDENT_LVD); lvd = (struct logicalVolDesc *)bh->b_data; table_len = le32_to_cpu(lvd->mapTableLength); if (sizeof(*lvd) + table_len > sb->s_blocksize) { udf_err(sb, "error loading logical volume descriptor: " "Partition table too long (%u > %lu)\n", table_len, sb->s_blocksize - sizeof(*lvd)); goto out_bh; } ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps)); if (ret) goto out_bh; for (i = 0, offset = 0; i < sbi->s_partitions && offset < table_len; i++, offset += gpm->partitionMapLength) { struct udf_part_map *map = &sbi->s_partmaps[i]; gpm = (struct genericPartitionMap *) &(lvd->partitionMaps[offset]); type = gpm->partitionMapType; if (type == 1) { struct genericPartitionMap1 *gpm1 = (struct genericPartitionMap1 *)gpm; map->s_partition_type = UDF_TYPE1_MAP15; map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum); map->s_partition_num = le16_to_cpu(gpm1->partitionNum); map->s_partition_func = NULL; } else if (type == 2) { struct udfPartitionMap2 *upm2 = (struct udfPartitionMap2 *)gpm; if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL, strlen(UDF_ID_VIRTUAL))) { u16 suf = le16_to_cpu(((__le16 *)upm2->partIdent. identSuffix)[0]); if (suf < 0x0200) { map->s_partition_type = UDF_VIRTUAL_MAP15; map->s_partition_func = udf_get_pblock_virt15; } else { map->s_partition_type = UDF_VIRTUAL_MAP20; map->s_partition_func = udf_get_pblock_virt20; } } else if (!strncmp(upm2->partIdent.ident, UDF_ID_SPARABLE, strlen(UDF_ID_SPARABLE))) { uint32_t loc; struct sparingTable *st; struct sparablePartitionMap *spm = (struct sparablePartitionMap *)gpm; map->s_partition_type = UDF_SPARABLE_MAP15; map->s_type_specific.s_sparing.s_packet_len = le16_to_cpu(spm->packetLength); for (j = 0; j < spm->numSparingTables; j++) { struct buffer_head *bh2; loc = le32_to_cpu( spm->locSparingTable[j]); bh2 = udf_read_tagged(sb, loc, loc, &ident); map->s_type_specific.s_sparing. s_spar_map[j] = bh2; if (bh2 == NULL) continue; st = (struct sparingTable *)bh2->b_data; if (ident != 0 || strncmp( st->sparingIdent.ident, UDF_ID_SPARING, strlen(UDF_ID_SPARING))) { brelse(bh2); map->s_type_specific.s_sparing. s_spar_map[j] = NULL; } } map->s_partition_func = udf_get_pblock_spar15; } else if (!strncmp(upm2->partIdent.ident, UDF_ID_METADATA, strlen(UDF_ID_METADATA))) { struct udf_meta_data *mdata = &map->s_type_specific.s_metadata; struct metadataPartitionMap *mdm = (struct metadataPartitionMap *) &(lvd->partitionMaps[offset]); udf_debug("Parsing Logical vol part %d type %d id=%s\n", i, type, UDF_ID_METADATA); map->s_partition_type = UDF_METADATA_MAP25; map->s_partition_func = udf_get_pblock_meta25; mdata->s_meta_file_loc = le32_to_cpu(mdm->metadataFileLoc); mdata->s_mirror_file_loc = le32_to_cpu(mdm->metadataMirrorFileLoc); mdata->s_bitmap_file_loc = le32_to_cpu(mdm->metadataBitmapFileLoc); mdata->s_alloc_unit_size = le32_to_cpu(mdm->allocUnitSize); mdata->s_align_unit_size = le16_to_cpu(mdm->alignUnitSize); if (mdm->flags & 0x01) mdata->s_flags |= MF_DUPLICATE_MD; udf_debug("Metadata Ident suffix=0x%x\n", le16_to_cpu(*(__le16 *) mdm->partIdent.identSuffix)); udf_debug("Metadata part num=%d\n", le16_to_cpu(mdm->partitionNum)); udf_debug("Metadata part alloc unit size=%d\n", le32_to_cpu(mdm->allocUnitSize)); udf_debug("Metadata file loc=%d\n", le32_to_cpu(mdm->metadataFileLoc)); udf_debug("Mirror file loc=%d\n", le32_to_cpu(mdm->metadataMirrorFileLoc)); udf_debug("Bitmap file loc=%d\n", le32_to_cpu(mdm->metadataBitmapFileLoc)); udf_debug("Flags: %d %d\n", mdata->s_flags, mdm->flags); } else { udf_debug("Unknown ident: %s\n", upm2->partIdent.ident); continue; } map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum); map->s_partition_num = le16_to_cpu(upm2->partitionNum); } udf_debug("Partition (%d:%d) type %d on volume %d\n", i, map->s_partition_num, type, map->s_volumeseqnum); } if (fileset) { struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]); *fileset = lelb_to_cpu(la->extLocation); udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n", fileset->logicalBlockNum, fileset->partitionReferenceNum); } if (lvd->integritySeqExt.extLength) udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt)); out_bh: brelse(bh); return ret; } /* * udf_load_logicalvolint * */ static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc) { struct buffer_head *bh = NULL; uint16_t ident; struct udf_sb_info *sbi = UDF_SB(sb); struct logicalVolIntegrityDesc *lvid; while (loc.extLength > 0 && (bh = udf_read_tagged(sb, loc.extLocation, loc.extLocation, &ident)) && ident == TAG_IDENT_LVID) { sbi->s_lvid_bh = bh; lvid = (struct logicalVolIntegrityDesc *)bh->b_data; if (lvid->nextIntegrityExt.extLength) udf_load_logicalvolint(sb, leea_to_cpu(lvid->nextIntegrityExt)); if (sbi->s_lvid_bh != bh) brelse(bh); loc.extLength -= sb->s_blocksize; loc.extLocation++; } if (sbi->s_lvid_bh != bh) brelse(bh); } /* * udf_process_sequence * * PURPOSE * Process a main/reserve volume descriptor sequence. * * PRE-CONDITIONS * sb Pointer to _locked_ superblock. * block First block of first extent of the sequence. * lastblock Lastblock of first extent of the sequence. * * HISTORY * July 1, 1997 - Andrew E. Mileski * Written, tested, and released. */ static noinline int udf_process_sequence(struct super_block *sb, long block, long lastblock, struct kernel_lb_addr *fileset) { struct buffer_head *bh = NULL; struct udf_vds_record vds[VDS_POS_LENGTH]; struct udf_vds_record *curr; struct generic_desc *gd; struct volDescPtr *vdp; int done = 0; uint32_t vdsn; uint16_t ident; long next_s = 0, next_e = 0; memset(vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH); /* * Read the main descriptor sequence and find which descriptors * are in it. */ for (; (!done && block <= lastblock); block++) { bh = udf_read_tagged(sb, block, block, &ident); if (!bh) { udf_err(sb, "Block %llu of volume descriptor sequence is corrupted or we could not read it\n", (unsigned long long)block); return 1; } /* Process each descriptor (ISO 13346 3/8.3-8.4) */ gd = (struct generic_desc *)bh->b_data; vdsn = le32_to_cpu(gd->volDescSeqNum); switch (ident) { case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */ curr = &vds[VDS_POS_PRIMARY_VOL_DESC]; if (vdsn >= curr->volDescSeqNum) { curr->volDescSeqNum = vdsn; curr->block = block; } break; case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */ curr = &vds[VDS_POS_VOL_DESC_PTR]; if (vdsn >= curr->volDescSeqNum) { curr->volDescSeqNum = vdsn; curr->block = block; vdp = (struct volDescPtr *)bh->b_data; next_s = le32_to_cpu( vdp->nextVolDescSeqExt.extLocation); next_e = le32_to_cpu( vdp->nextVolDescSeqExt.extLength); next_e = next_e >> sb->s_blocksize_bits; next_e += next_s; } break; case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */ curr = &vds[VDS_POS_IMP_USE_VOL_DESC]; if (vdsn >= curr->volDescSeqNum) { curr->volDescSeqNum = vdsn; curr->block = block; } break; case TAG_IDENT_PD: /* ISO 13346 3/10.5 */ curr = &vds[VDS_POS_PARTITION_DESC]; if (!curr->block) curr->block = block; break; case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */ curr = &vds[VDS_POS_LOGICAL_VOL_DESC]; if (vdsn >= curr->volDescSeqNum) { curr->volDescSeqNum = vdsn; curr->block = block; } break; case TAG_IDENT_USD: /* ISO 13346 3/10.8 */ curr = &vds[VDS_POS_UNALLOC_SPACE_DESC]; if (vdsn >= curr->volDescSeqNum) { curr->volDescSeqNum = vdsn; curr->block = block; } break; case TAG_IDENT_TD: /* ISO 13346 3/10.9 */ vds[VDS_POS_TERMINATING_DESC].block = block; if (next_e) { block = next_s; lastblock = next_e; next_s = next_e = 0; } else done = 1; break; } brelse(bh); } /* * Now read interesting descriptors again and process them * in a suitable order */ if (!vds[VDS_POS_PRIMARY_VOL_DESC].block) { udf_err(sb, "Primary Volume Descriptor not found!\n"); return 1; } if (udf_load_pvoldesc(sb, vds[VDS_POS_PRIMARY_VOL_DESC].block)) return 1; if (vds[VDS_POS_LOGICAL_VOL_DESC].block && udf_load_logicalvol(sb, vds[VDS_POS_LOGICAL_VOL_DESC].block, fileset)) return 1; if (vds[VDS_POS_PARTITION_DESC].block) { /* * We rescan the whole descriptor sequence to find * partition descriptor blocks and process them. */ for (block = vds[VDS_POS_PARTITION_DESC].block; block < vds[VDS_POS_TERMINATING_DESC].block; block++) if (udf_load_partdesc(sb, block)) return 1; } return 0; } static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh, struct kernel_lb_addr *fileset) { struct anchorVolDescPtr *anchor; long main_s, main_e, reserve_s, reserve_e; anchor = (struct anchorVolDescPtr *)bh->b_data; /* Locate the main sequence */ main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation); main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength); main_e = main_e >> sb->s_blocksize_bits; main_e += main_s; /* Locate the reserve sequence */ reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation); reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength); reserve_e = reserve_e >> sb->s_blocksize_bits; reserve_e += reserve_s; /* Process the main & reserve sequences */ /* responsible for finding the PartitionDesc(s) */ if (!udf_process_sequence(sb, main_s, main_e, fileset)) return 1; return !udf_process_sequence(sb, reserve_s, reserve_e, fileset); } /* * Check whether there is an anchor block in the given block and * load Volume Descriptor Sequence if so. */ static int udf_check_anchor_block(struct super_block *sb, sector_t block, struct kernel_lb_addr *fileset) { struct buffer_head *bh; uint16_t ident; int ret; if (UDF_QUERY_FLAG(sb, UDF_FLAG_VARCONV) && udf_fixed_to_variable(block) >= sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits) return 0; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) return 0; if (ident != TAG_IDENT_AVDP) { brelse(bh); return 0; } ret = udf_load_sequence(sb, bh, fileset); brelse(bh); return ret; } /* Search for an anchor volume descriptor pointer */ static sector_t udf_scan_anchors(struct super_block *sb, sector_t lastblock, struct kernel_lb_addr *fileset) { sector_t last[6]; int i; struct udf_sb_info *sbi = UDF_SB(sb); int last_count = 0; /* First try user provided anchor */ if (sbi->s_anchor) { if (udf_check_anchor_block(sb, sbi->s_anchor, fileset)) return lastblock; } /* * according to spec, anchor is in either: * block 256 * lastblock-256 * lastblock * however, if the disc isn't closed, it could be 512. */ if (udf_check_anchor_block(sb, sbi->s_session + 256, fileset)) return lastblock; /* * The trouble is which block is the last one. Drives often misreport * this so we try various possibilities. */ last[last_count++] = lastblock; if (lastblock >= 1) last[last_count++] = lastblock - 1; last[last_count++] = lastblock + 1; if (lastblock >= 2) last[last_count++] = lastblock - 2; if (lastblock >= 150) last[last_count++] = lastblock - 150; if (lastblock >= 152) last[last_count++] = lastblock - 152; for (i = 0; i < last_count; i++) { if (last[i] >= sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits) continue; if (udf_check_anchor_block(sb, last[i], fileset)) return last[i]; if (last[i] < 256) continue; if (udf_check_anchor_block(sb, last[i] - 256, fileset)) return last[i]; } /* Finally try block 512 in case media is open */ if (udf_check_anchor_block(sb, sbi->s_session + 512, fileset)) return last[0]; return 0; } /* * Find an anchor volume descriptor and load Volume Descriptor Sequence from * area specified by it. The function expects sbi->s_lastblock to be the last * block on the media. * * Return 1 if ok, 0 if not found. * */ static int udf_find_anchor(struct super_block *sb, struct kernel_lb_addr *fileset) { sector_t lastblock; struct udf_sb_info *sbi = UDF_SB(sb); lastblock = udf_scan_anchors(sb, sbi->s_last_block, fileset); if (lastblock) goto out; /* No anchor found? Try VARCONV conversion of block numbers */ UDF_SET_FLAG(sb, UDF_FLAG_VARCONV); /* Firstly, we try to not convert number of the last block */ lastblock = udf_scan_anchors(sb, udf_variable_to_fixed(sbi->s_last_block), fileset); if (lastblock) goto out; /* Secondly, we try with converted number of the last block */ lastblock = udf_scan_anchors(sb, sbi->s_last_block, fileset); if (!lastblock) { /* VARCONV didn't help. Clear it. */ UDF_CLEAR_FLAG(sb, UDF_FLAG_VARCONV); return 0; } out: sbi->s_last_block = lastblock; return 1; } /* * Check Volume Structure Descriptor, find Anchor block and load Volume * Descriptor Sequence */ static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt, int silent, struct kernel_lb_addr *fileset) { struct udf_sb_info *sbi = UDF_SB(sb); loff_t nsr_off; if (!sb_set_blocksize(sb, uopt->blocksize)) { if (!silent) udf_warn(sb, "Bad block size\n"); return 0; } sbi->s_last_block = uopt->lastblock; if (!uopt->novrs) { /* Check that it is NSR02 compliant */ nsr_off = udf_check_vsd(sb); if (!nsr_off) { if (!silent) udf_warn(sb, "No VRS found\n"); return 0; } if (nsr_off == -1) udf_debug("Failed to read byte 32768. Assuming open disc. Skipping validity check\n"); if (!sbi->s_last_block) sbi->s_last_block = udf_get_last_block(sb); } else { udf_debug("Validity check skipped because of novrs option\n"); } /* Look for anchor block and load Volume Descriptor Sequence */ sbi->s_anchor = uopt->anchor; if (!udf_find_anchor(sb, fileset)) { if (!silent) udf_warn(sb, "No anchor found\n"); return 0; } return 1; } static void udf_open_lvid(struct super_block *sb) { struct udf_sb_info *sbi = UDF_SB(sb); struct buffer_head *bh = sbi->s_lvid_bh; struct logicalVolIntegrityDesc *lvid; struct logicalVolIntegrityDescImpUse *lvidiu; if (!bh) return; mutex_lock(&sbi->s_alloc_mutex); lvid = (struct logicalVolIntegrityDesc *)bh->b_data; lvidiu = udf_sb_lvidiu(sbi); lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX; lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX; udf_time_to_disk_stamp(&lvid->recordingDateAndTime, CURRENT_TIME); lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN); lvid->descTag.descCRC = cpu_to_le16( crc_itu_t(0, (char *)lvid + sizeof(struct tag), le16_to_cpu(lvid->descTag.descCRCLength))); lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag); mark_buffer_dirty(bh); sbi->s_lvid_dirty = 0; mutex_unlock(&sbi->s_alloc_mutex); } static void udf_close_lvid(struct super_block *sb) { struct udf_sb_info *sbi = UDF_SB(sb); struct buffer_head *bh = sbi->s_lvid_bh; struct logicalVolIntegrityDesc *lvid; struct logicalVolIntegrityDescImpUse *lvidiu; if (!bh) return; mutex_lock(&sbi->s_alloc_mutex); lvid = (struct logicalVolIntegrityDesc *)bh->b_data; lvidiu = udf_sb_lvidiu(sbi); lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX; lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX; udf_time_to_disk_stamp(&lvid->recordingDateAndTime, CURRENT_TIME); if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev)) lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION); if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev)) lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev); if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev)) lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev); lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE); lvid->descTag.descCRC = cpu_to_le16( crc_itu_t(0, (char *)lvid + sizeof(struct tag), le16_to_cpu(lvid->descTag.descCRCLength))); lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag); /* * We set buffer uptodate unconditionally here to avoid spurious * warnings from mark_buffer_dirty() when previous EIO has marked * the buffer as !uptodate */ set_buffer_uptodate(bh); mark_buffer_dirty(bh); sbi->s_lvid_dirty = 0; mutex_unlock(&sbi->s_alloc_mutex); } u64 lvid_get_unique_id(struct super_block *sb) { struct buffer_head *bh; struct udf_sb_info *sbi = UDF_SB(sb); struct logicalVolIntegrityDesc *lvid; struct logicalVolHeaderDesc *lvhd; u64 uniqueID; u64 ret; bh = sbi->s_lvid_bh; if (!bh) return 0; lvid = (struct logicalVolIntegrityDesc *)bh->b_data; lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse; mutex_lock(&sbi->s_alloc_mutex); ret = uniqueID = le64_to_cpu(lvhd->uniqueID); if (!(++uniqueID & 0xFFFFFFFF)) uniqueID += 16; lvhd->uniqueID = cpu_to_le64(uniqueID); mutex_unlock(&sbi->s_alloc_mutex); mark_buffer_dirty(bh); return ret; } static void udf_sb_free_bitmap(struct udf_bitmap *bitmap) { int i; int nr_groups = bitmap->s_nr_groups; int size = sizeof(struct udf_bitmap) + (sizeof(struct buffer_head *) * nr_groups); for (i = 0; i < nr_groups; i++) if (bitmap->s_block_bitmap[i]) brelse(bitmap->s_block_bitmap[i]); if (size <= PAGE_SIZE) kfree(bitmap); else vfree(bitmap); } static void udf_free_partition(struct udf_part_map *map) { int i; struct udf_meta_data *mdata; if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) iput(map->s_uspace.s_table); if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE) iput(map->s_fspace.s_table); if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) udf_sb_free_bitmap(map->s_uspace.s_bitmap); if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP) udf_sb_free_bitmap(map->s_fspace.s_bitmap); if (map->s_partition_type == UDF_SPARABLE_MAP15) for (i = 0; i < 4; i++) brelse(map->s_type_specific.s_sparing.s_spar_map[i]); else if (map->s_partition_type == UDF_METADATA_MAP25) { mdata = &map->s_type_specific.s_metadata; iput(mdata->s_metadata_fe); mdata->s_metadata_fe = NULL; iput(mdata->s_mirror_fe); mdata->s_mirror_fe = NULL; iput(mdata->s_bitmap_fe); mdata->s_bitmap_fe = NULL; } } static int udf_fill_super(struct super_block *sb, void *options, int silent) { int i; int ret; struct inode *inode = NULL; struct udf_options uopt; struct kernel_lb_addr rootdir, fileset; struct udf_sb_info *sbi; uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT); uopt.uid = -1; uopt.gid = -1; uopt.umask = 0; uopt.fmode = UDF_INVALID_MODE; uopt.dmode = UDF_INVALID_MODE; sbi = kzalloc(sizeof(struct udf_sb_info), GFP_KERNEL); if (!sbi) return -ENOMEM; sb->s_fs_info = sbi; mutex_init(&sbi->s_alloc_mutex); if (!udf_parse_options((char *)options, &uopt, false)) goto error_out; if (uopt.flags & (1 << UDF_FLAG_UTF8) && uopt.flags & (1 << UDF_FLAG_NLS_MAP)) { udf_err(sb, "utf8 cannot be combined with iocharset\n"); goto error_out; } #ifdef CONFIG_UDF_NLS if ((uopt.flags & (1 << UDF_FLAG_NLS_MAP)) && !uopt.nls_map) { uopt.nls_map = load_nls_default(); if (!uopt.nls_map) uopt.flags &= ~(1 << UDF_FLAG_NLS_MAP); else udf_debug("Using default NLS map\n"); } #endif if (!(uopt.flags & (1 << UDF_FLAG_NLS_MAP))) uopt.flags |= (1 << UDF_FLAG_UTF8); fileset.logicalBlockNum = 0xFFFFFFFF; fileset.partitionReferenceNum = 0xFFFF; sbi->s_flags = uopt.flags; sbi->s_uid = uopt.uid; sbi->s_gid = uopt.gid; sbi->s_umask = uopt.umask; sbi->s_fmode = uopt.fmode; sbi->s_dmode = uopt.dmode; sbi->s_nls_map = uopt.nls_map; rwlock_init(&sbi->s_cred_lock); if (uopt.session == 0xFFFFFFFF) sbi->s_session = udf_get_last_session(sb); else sbi->s_session = uopt.session; udf_debug("Multi-session=%d\n", sbi->s_session); /* Fill in the rest of the superblock */ sb->s_op = &udf_sb_ops; sb->s_export_op = &udf_export_ops; sb->s_dirt = 0; sb->s_magic = UDF_SUPER_MAGIC; sb->s_time_gran = 1000; if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) { ret = udf_load_vrs(sb, &uopt, silent, &fileset); } else { uopt.blocksize = bdev_logical_block_size(sb->s_bdev); ret = udf_load_vrs(sb, &uopt, silent, &fileset); if (!ret && uopt.blocksize != UDF_DEFAULT_BLOCKSIZE) { if (!silent) pr_notice("Rescanning with blocksize %d\n", UDF_DEFAULT_BLOCKSIZE); uopt.blocksize = UDF_DEFAULT_BLOCKSIZE; ret = udf_load_vrs(sb, &uopt, silent, &fileset); } } if (!ret) { udf_warn(sb, "No partition found (1)\n"); goto error_out; } udf_debug("Lastblock=%d\n", sbi->s_last_block); if (sbi->s_lvid_bh) { struct logicalVolIntegrityDescImpUse *lvidiu = udf_sb_lvidiu(sbi); uint16_t minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev); uint16_t minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev); /* uint16_t maxUDFWriteRev = le16_to_cpu(lvidiu->maxUDFWriteRev); */ if (minUDFReadRev > UDF_MAX_READ_VERSION) { udf_err(sb, "minUDFReadRev=%x (max is %x)\n", le16_to_cpu(lvidiu->minUDFReadRev), UDF_MAX_READ_VERSION); goto error_out; } else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION) sb->s_flags |= MS_RDONLY; sbi->s_udfrev = minUDFWriteRev; if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE) UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE); if (minUDFReadRev >= UDF_VERS_USE_STREAMS) UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS); } if (!sbi->s_partitions) { udf_warn(sb, "No partition found (2)\n"); goto error_out; } if (sbi->s_partmaps[sbi->s_partition].s_partition_flags & UDF_PART_FLAG_READ_ONLY) { pr_notice("Partition marked readonly; forcing readonly mount\n"); sb->s_flags |= MS_RDONLY; } if (udf_find_fileset(sb, &fileset, &rootdir)) { udf_warn(sb, "No fileset found\n"); goto error_out; } if (!silent) { struct timestamp ts; udf_time_to_disk_stamp(&ts, sbi->s_record_time); udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n", sbi->s_volume_ident, le16_to_cpu(ts.year), ts.month, ts.day, ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone)); } if (!(sb->s_flags & MS_RDONLY)) udf_open_lvid(sb); /* Assign the root inode */ /* assign inodes by physical block number */ /* perhaps it's not extensible enough, but for now ... */ inode = udf_iget(sb, &rootdir); if (!inode) { udf_err(sb, "Error in udf_iget, block=%d, partition=%d\n", rootdir.logicalBlockNum, rootdir.partitionReferenceNum); goto error_out; } /* Allocate a dentry for the root inode */ sb->s_root = d_make_root(inode); if (!sb->s_root) { udf_err(sb, "Couldn't allocate root dentry\n"); goto error_out; } sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_max_links = UDF_MAX_LINKS; return 0; error_out: if (sbi->s_vat_inode) iput(sbi->s_vat_inode); if (sbi->s_partitions) for (i = 0; i < sbi->s_partitions; i++) udf_free_partition(&sbi->s_partmaps[i]); #ifdef CONFIG_UDF_NLS if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) unload_nls(sbi->s_nls_map); #endif if (!(sb->s_flags & MS_RDONLY)) udf_close_lvid(sb); brelse(sbi->s_lvid_bh); kfree(sbi->s_partmaps); kfree(sbi); sb->s_fs_info = NULL; return -EINVAL; } void _udf_err(struct super_block *sb, const char *function, const char *fmt, ...) { struct va_format vaf; va_list args; /* mark sb error */ if (!(sb->s_flags & MS_RDONLY)) sb->s_dirt = 1; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf); va_end(args); } void _udf_warn(struct super_block *sb, const char *function, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf); va_end(args); } static void udf_put_super(struct super_block *sb) { int i; struct udf_sb_info *sbi; sbi = UDF_SB(sb); if (sbi->s_vat_inode) iput(sbi->s_vat_inode); if (sbi->s_partitions) for (i = 0; i < sbi->s_partitions; i++) udf_free_partition(&sbi->s_partmaps[i]); #ifdef CONFIG_UDF_NLS if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) unload_nls(sbi->s_nls_map); #endif if (!(sb->s_flags & MS_RDONLY)) udf_close_lvid(sb); brelse(sbi->s_lvid_bh); kfree(sbi->s_partmaps); kfree(sb->s_fs_info); sb->s_fs_info = NULL; } static int udf_sync_fs(struct super_block *sb, int wait) { struct udf_sb_info *sbi = UDF_SB(sb); mutex_lock(&sbi->s_alloc_mutex); if (sbi->s_lvid_dirty) { /* * Blockdevice will be synced later so we don't have to submit * the buffer for IO */ mark_buffer_dirty(sbi->s_lvid_bh); sb->s_dirt = 0; sbi->s_lvid_dirty = 0; } mutex_unlock(&sbi->s_alloc_mutex); return 0; } static int udf_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; struct udf_sb_info *sbi = UDF_SB(sb); struct logicalVolIntegrityDescImpUse *lvidiu; u64 id = huge_encode_dev(sb->s_bdev->bd_dev); if (sbi->s_lvid_bh != NULL) lvidiu = udf_sb_lvidiu(sbi); else lvidiu = NULL; buf->f_type = UDF_SUPER_MAGIC; buf->f_bsize = sb->s_blocksize; buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len; buf->f_bfree = udf_count_free(sb); buf->f_bavail = buf->f_bfree; buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) + le32_to_cpu(lvidiu->numDirs)) : 0) + buf->f_bfree; buf->f_ffree = buf->f_bfree; buf->f_namelen = UDF_NAME_LEN - 2; buf->f_fsid.val[0] = (u32)id; buf->f_fsid.val[1] = (u32)(id >> 32); return 0; } static unsigned int udf_count_free_bitmap(struct super_block *sb, struct udf_bitmap *bitmap) { struct buffer_head *bh = NULL; unsigned int accum = 0; int index; int block = 0, newblock; struct kernel_lb_addr loc; uint32_t bytes; uint8_t *ptr; uint16_t ident; struct spaceBitmapDesc *bm; loc.logicalBlockNum = bitmap->s_extPosition; loc.partitionReferenceNum = UDF_SB(sb)->s_partition; bh = udf_read_ptagged(sb, &loc, 0, &ident); if (!bh) { udf_err(sb, "udf_count_free failed\n"); goto out; } else if (ident != TAG_IDENT_SBD) { brelse(bh); udf_err(sb, "udf_count_free failed\n"); goto out; } bm = (struct spaceBitmapDesc *)bh->b_data; bytes = le32_to_cpu(bm->numOfBytes); index = sizeof(struct spaceBitmapDesc); /* offset in first block only */ ptr = (uint8_t *)bh->b_data; while (bytes > 0) { u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index); accum += bitmap_weight((const unsigned long *)(ptr + index), cur_bytes * 8); bytes -= cur_bytes; if (bytes) { brelse(bh); newblock = udf_get_lb_pblock(sb, &loc, ++block); bh = udf_tread(sb, newblock); if (!bh) { udf_debug("read failed\n"); goto out; } index = 0; ptr = (uint8_t *)bh->b_data; } } brelse(bh); out: return accum; } static unsigned int udf_count_free_table(struct super_block *sb, struct inode *table) { unsigned int accum = 0; uint32_t elen; struct kernel_lb_addr eloc; int8_t etype; struct extent_position epos; mutex_lock(&UDF_SB(sb)->s_alloc_mutex); epos.block = UDF_I(table)->i_location; epos.offset = sizeof(struct unallocSpaceEntry); epos.bh = NULL; while ((etype = udf_next_aext(table, &epos, &eloc, &elen, 1)) != -1) accum += (elen >> table->i_sb->s_blocksize_bits); brelse(epos.bh); mutex_unlock(&UDF_SB(sb)->s_alloc_mutex); return accum; } static unsigned int udf_count_free(struct super_block *sb) { unsigned int accum = 0; struct udf_sb_info *sbi; struct udf_part_map *map; sbi = UDF_SB(sb); if (sbi->s_lvid_bh) { struct logicalVolIntegrityDesc *lvid = (struct logicalVolIntegrityDesc *) sbi->s_lvid_bh->b_data; if (le32_to_cpu(lvid->numOfPartitions) > sbi->s_partition) { accum = le32_to_cpu( lvid->freeSpaceTable[sbi->s_partition]); if (accum == 0xFFFFFFFF) accum = 0; } } if (accum) return accum; map = &sbi->s_partmaps[sbi->s_partition]; if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) { accum += udf_count_free_bitmap(sb, map->s_uspace.s_bitmap); } if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP) { accum += udf_count_free_bitmap(sb, map->s_fspace.s_bitmap); } if (accum) return accum; if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) { accum += udf_count_free_table(sb, map->s_uspace.s_table); } if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE) { accum += udf_count_free_table(sb, map->s_fspace.s_table); } return accum; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3687_0
crossvul-cpp_data_good_2206_0
/* * Copyright 2011-2014 Con Kolivas * Copyright 2010 Jeff Garzik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. See COPYING for more details. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <stdarg.h> #include <string.h> #include <jansson.h> #ifdef HAVE_LIBCURL #include <curl/curl.h> #endif #include <time.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #ifndef WIN32 #include <fcntl.h> # ifdef __linux # include <sys/prctl.h> # endif # include <sys/socket.h> # include <netinet/in.h> # include <netinet/tcp.h> # include <netdb.h> #else # include <winsock2.h> # include <ws2tcpip.h> # include <mmsystem.h> #endif #include "miner.h" #include "elist.h" #include "compat.h" #include "util.h" #define DEFAULT_SOCKWAIT 60 bool successful_connect = false; static void keep_sockalive(SOCKETTYPE fd) { const int tcp_one = 1; #ifndef WIN32 const int tcp_keepidle = 45; const int tcp_keepintvl = 30; int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, O_NONBLOCK | flags); #else u_long flags = 1; ioctlsocket(fd, FIONBIO, &flags); #endif setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&tcp_one, sizeof(tcp_one)); if (!opt_delaynet) #ifndef __linux setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one)); #else /* __linux */ setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one)); setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one)); setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle)); setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl)); #endif /* __linux */ #ifdef __APPLE_CC__ setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl)); #endif /* __APPLE_CC__ */ } struct tq_ent { void *data; struct list_head q_node; }; #ifdef HAVE_LIBCURL struct timeval nettime; struct data_buffer { void *buf; size_t len; }; struct upload_buffer { const void *buf; size_t len; }; struct header_info { char *lp_path; int rolltime; char *reason; char *stratum_url; bool hadrolltime; bool canroll; bool hadexpire; }; static void databuf_free(struct data_buffer *db) { if (!db) return; free(db->buf); memset(db, 0, sizeof(*db)); } static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb, void *user_data) { struct data_buffer *db = user_data; size_t len = size * nmemb; size_t oldlen, newlen; void *newmem; static const unsigned char zero = 0; oldlen = db->len; newlen = oldlen + len; newmem = realloc(db->buf, newlen + 1); if (!newmem) return 0; db->buf = newmem; db->len = newlen; memcpy(db->buf + oldlen, ptr, len); memcpy(db->buf + newlen, &zero, 1); /* null terminate */ return len; } static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb, void *user_data) { struct upload_buffer *ub = user_data; unsigned int len = size * nmemb; if (len > ub->len) len = ub->len; if (len) { memcpy(ptr, ub->buf, len); ub->buf += len; ub->len -= len; } return len; } static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data) { struct header_info *hi = user_data; size_t remlen, slen, ptrlen = size * nmemb; char *rem, *val = NULL, *key = NULL; void *tmp; val = calloc(1, ptrlen); key = calloc(1, ptrlen); if (!key || !val) goto out; tmp = memchr(ptr, ':', ptrlen); if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */ goto out; slen = tmp - ptr; if ((slen + 1) == ptrlen) /* skip key w/ no value */ goto out; memcpy(key, ptr, slen); /* store & nul term key */ key[slen] = 0; rem = ptr + slen + 1; /* trim value's leading whitespace */ remlen = ptrlen - slen - 1; while ((remlen > 0) && (isspace(*rem))) { remlen--; rem++; } memcpy(val, rem, remlen); /* store value, trim trailing ws */ val[remlen] = 0; while ((*val) && (isspace(val[strlen(val) - 1]))) val[strlen(val) - 1] = 0; if (!*val) /* skip blank value */ goto out; if (opt_protocol) applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val); if (!strcasecmp("X-Roll-Ntime", key)) { hi->hadrolltime = true; if (!strncasecmp("N", val, 1)) applog(LOG_DEBUG, "X-Roll-Ntime: N found"); else { hi->canroll = true; /* Check to see if expire= is supported and if not, set * the rolltime to the default scantime */ if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) { sscanf(val + 7, "%d", &hi->rolltime); hi->hadexpire = true; } else hi->rolltime = opt_scantime; applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime); } } if (!strcasecmp("X-Long-Polling", key)) { hi->lp_path = val; /* steal memory reference */ val = NULL; } if (!strcasecmp("X-Reject-Reason", key)) { hi->reason = val; /* steal memory reference */ val = NULL; } if (!strcasecmp("X-Stratum", key)) { hi->stratum_url = val; val = NULL; } out: free(key); free(val); return ptrlen; } static void last_nettime(struct timeval *last) { rd_lock(&netacc_lock); last->tv_sec = nettime.tv_sec; last->tv_usec = nettime.tv_usec; rd_unlock(&netacc_lock); } static void set_nettime(void) { wr_lock(&netacc_lock); cgtime(&nettime); wr_unlock(&netacc_lock); } #if CURL_HAS_KEEPALIVE static void keep_curlalive(CURL *curl) { const int tcp_keepidle = 45; const int tcp_keepintvl = 30; const long int keepalive = 1; curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive); curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle); curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl); } #else static void keep_curlalive(CURL *curl) { SOCKETTYPE sock; curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock); keep_sockalive(sock); } #endif static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type, __maybe_unused char *data, size_t size, void *userdata) { struct pool *pool = (struct pool *)userdata; switch(type) { case CURLINFO_HEADER_IN: case CURLINFO_DATA_IN: case CURLINFO_SSL_DATA_IN: pool->cgminer_pool_stats.net_bytes_received += size; break; case CURLINFO_HEADER_OUT: case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_OUT: pool->cgminer_pool_stats.net_bytes_sent += size; break; case CURLINFO_TEXT: default: break; } return 0; } json_t *json_web_config(const char *url) { struct data_buffer all_data = {NULL, 0}; char curl_err_str[CURL_ERROR_SIZE]; long timeout = 60; json_error_t err; json_t *val; CURL *curl; int rc; memset(&err, 0, sizeof(err)); curl = curl_easy_init(); if (unlikely(!curl)) quithere(1, "CURL initialisation failed"); curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY); val = NULL; rc = curl_easy_perform(curl); curl_easy_cleanup(curl); if (rc) { applog(LOG_ERR, "HTTP config request of '%s' failed: %s", url, curl_err_str); goto c_out; } if (!all_data.buf) { applog(LOG_ERR, "Empty config data received from '%s'", url); goto c_out; } val = JSON_LOADS(all_data.buf, &err); if (!val) { applog(LOG_ERR, "JSON config decode of '%s' failed(%d): %s", url, err.line, err.text); } databuf_free(&all_data); c_out: return val; } json_t *json_rpc_call(CURL *curl, const char *url, const char *userpass, const char *rpc_req, bool probe, bool longpoll, int *rolltime, struct pool *pool, bool share) { long timeout = longpoll ? (60 * 60) : 60; struct data_buffer all_data = {NULL, 0}; struct header_info hi = {NULL, 0, NULL, NULL, false, false, false}; char len_hdr[64], user_agent_hdr[128]; char curl_err_str[CURL_ERROR_SIZE]; struct curl_slist *headers = NULL; struct upload_buffer upload_data; json_t *val, *err_val, *res_val; bool probing = false; double byte_count; json_error_t err; int rc; memset(&err, 0, sizeof(err)); /* it is assumed that 'curl' is freshly [re]initialized at this pt */ if (probe) probing = !pool->probed; curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb); curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); /* Shares are staggered already and delays in submission can be costly * so do not delay them */ if (!opt_delaynet || share) curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data); curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi); curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY); if (pool->rpc_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype); } else if (opt_socks_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4); } if (userpass) { curl_easy_setopt(curl, CURLOPT_USERPWD, userpass); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } if (longpoll) keep_curlalive(curl); curl_easy_setopt(curl, CURLOPT_POST, 1); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req); upload_data.buf = rpc_req; upload_data.len = strlen(rpc_req); sprintf(len_hdr, "Content-Length: %lu", (unsigned long) upload_data.len); sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING); headers = curl_slist_append(headers, "Content-type: application/json"); headers = curl_slist_append(headers, "X-Mining-Extensions: longpoll midstate rollntime submitold"); if (likely(global_hashrate)) { char ghashrate[255]; sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate); headers = curl_slist_append(headers, ghashrate); } headers = curl_slist_append(headers, len_hdr); headers = curl_slist_append(headers, user_agent_hdr); headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); if (opt_delaynet) { /* Don't delay share submission, but still track the nettime */ if (!share) { long long now_msecs, last_msecs; struct timeval now, last; cgtime(&now); last_nettime(&last); now_msecs = (long long)now.tv_sec * 1000; now_msecs += now.tv_usec / 1000; last_msecs = (long long)last.tv_sec * 1000; last_msecs += last.tv_usec / 1000; if (now_msecs > last_msecs && now_msecs - last_msecs < 250) { struct timespec rgtp; rgtp.tv_sec = 0; rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000; nanosleep(&rgtp, NULL); } } set_nettime(); } rc = curl_easy_perform(curl); if (rc) { applog(LOG_INFO, "HTTP request failed: %s", curl_err_str); goto err_out; } if (!all_data.buf) { applog(LOG_DEBUG, "Empty data received in json_rpc_call."); goto err_out; } pool->cgminer_pool_stats.times_sent++; if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK) pool->cgminer_pool_stats.bytes_sent += byte_count; pool->cgminer_pool_stats.times_received++; if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK) pool->cgminer_pool_stats.bytes_received += byte_count; if (probing) { pool->probed = true; /* If X-Long-Polling was found, activate long polling */ if (hi.lp_path) { if (pool->hdr_path != NULL) free(pool->hdr_path); pool->hdr_path = hi.lp_path; } else pool->hdr_path = NULL; if (hi.stratum_url) { pool->stratum_url = hi.stratum_url; hi.stratum_url = NULL; } } else { if (hi.lp_path) { free(hi.lp_path); hi.lp_path = NULL; } if (hi.stratum_url) { free(hi.stratum_url); hi.stratum_url = NULL; } } *rolltime = hi.rolltime; pool->cgminer_pool_stats.rolltime = hi.rolltime; pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime; pool->cgminer_pool_stats.canroll = hi.canroll; pool->cgminer_pool_stats.hadexpire = hi.hadexpire; val = JSON_LOADS(all_data.buf, &err); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf)); goto err_out; } if (opt_protocol) { char *s = json_dumps(val, JSON_INDENT(3)); applog(LOG_DEBUG, "JSON protocol response:\n%s", s); free(s); } /* JSON-RPC valid response returns a non-null 'result', * and a null 'error'. */ res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val ||(err_val && !json_is_null(err_val))) { char *s; if (err_val) s = json_dumps(err_val, JSON_INDENT(3)); else s = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC call failed: %s", s); free(s); goto err_out; } if (hi.reason) { json_object_set_new(val, "reject-reason", json_string(hi.reason)); free(hi.reason); hi.reason = NULL; } successful_connect = true; databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); return val; err_out: databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); if (!successful_connect) applog(LOG_DEBUG, "Failed to connect in json_rpc_call"); curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1); return NULL; } #define PROXY_HTTP CURLPROXY_HTTP #define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0 #define PROXY_SOCKS4 CURLPROXY_SOCKS4 #define PROXY_SOCKS5 CURLPROXY_SOCKS5 #define PROXY_SOCKS4A CURLPROXY_SOCKS4A #define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME #else /* HAVE_LIBCURL */ #define PROXY_HTTP 0 #define PROXY_HTTP_1_0 1 #define PROXY_SOCKS4 2 #define PROXY_SOCKS5 3 #define PROXY_SOCKS4A 4 #define PROXY_SOCKS5H 5 #endif /* HAVE_LIBCURL */ static struct { const char *name; proxytypes_t proxytype; } proxynames[] = { { "http:", PROXY_HTTP }, { "http0:", PROXY_HTTP_1_0 }, { "socks4:", PROXY_SOCKS4 }, { "socks5:", PROXY_SOCKS5 }, { "socks4a:", PROXY_SOCKS4A }, { "socks5h:", PROXY_SOCKS5H }, { NULL, 0 } }; const char *proxytype(proxytypes_t proxytype) { int i; for (i = 0; proxynames[i].name; i++) if (proxynames[i].proxytype == proxytype) return proxynames[i].name; return "invalid"; } char *get_proxy(char *url, struct pool *pool) { pool->rpc_proxy = NULL; char *split; int plen, len, i; for (i = 0; proxynames[i].name; i++) { plen = strlen(proxynames[i].name); if (strncmp(url, proxynames[i].name, plen) == 0) { if (!(split = strchr(url, '|'))) return url; *split = '\0'; len = split - url; pool->rpc_proxy = malloc(1 + len - plen); if (!(pool->rpc_proxy)) quithere(1, "Failed to malloc rpc_proxy"); strcpy(pool->rpc_proxy, url + plen); extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port); pool->rpc_proxytype = proxynames[i].proxytype; url = split + 1; break; } } return url; } /* Adequate size s==len*2 + 1 must be alloced to use this variant */ void __bin2hex(char *s, const unsigned char *p, size_t len) { int i; static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; for (i = 0; i < (int)len; i++) { *s++ = hex[p[i] >> 4]; *s++ = hex[p[i] & 0xF]; } *s++ = '\0'; } /* Returns a malloced array string of a binary value of arbitrary length. The * array is rounded up to a 4 byte size to appease architectures that need * aligned array sizes */ char *bin2hex(const unsigned char *p, size_t len) { ssize_t slen; char *s; slen = len * 2 + 1; if (slen % 4) slen += 4 - (slen % 4); s = calloc(slen, 1); if (unlikely(!s)) quithere(1, "Failed to calloc"); __bin2hex(s, p, len); return s; } static const int hex2bin_tbl[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /* Does the reverse of bin2hex but does not allocate any ram */ bool hex2bin(unsigned char *p, const char *hexstr, size_t len) { int nibble1, nibble2; unsigned char idx; bool ret = false; while (*hexstr && len) { if (unlikely(!hexstr[1])) { applog(LOG_ERR, "hex2bin str truncated"); return ret; } idx = *hexstr++; nibble1 = hex2bin_tbl[idx]; idx = *hexstr++; nibble2 = hex2bin_tbl[idx]; if (unlikely((nibble1 < 0) || (nibble2 < 0))) { applog(LOG_ERR, "hex2bin scan failed"); return ret; } *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2); --len; } if (likely(len == 0 && *hexstr == 0)) ret = true; return ret; } static bool _valid_hex(char *s, const char *file, const char *func, const int line) { bool ret = false; int i, len; if (unlikely(!s)) { applog(LOG_ERR, "Null string passed to valid_hex from"IN_FMT_FFL, file, func, line); return ret; } len = strlen(s); if (unlikely(!len)) { applog(LOG_ERR, "Zero length string passed to valid_hex from"IN_FMT_FFL, file, func, line); return ret; } for (i = 0; i < len; i++) { unsigned char idx = s[i]; if (unlikely(hex2bin_tbl[idx] < 0)) { applog(LOG_ERR, "Invalid char %x passed to valid_hex from"IN_FMT_FFL, idx, file, func, line); return ret; } } ret = true; return ret; } #define valid_hex(s) _valid_hex(s, __FILE__, __func__, __LINE__) static const int b58tobin_tbl[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1, -1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, -1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 }; /* b58bin should always be at least 25 bytes long and already checked to be * valid. */ void b58tobin(unsigned char *b58bin, const char *b58) { uint32_t c, bin32[7]; int len, i, j; uint64_t t; memset(bin32, 0, 7 * sizeof(uint32_t)); len = strlen(b58); for (i = 0; i < len; i++) { c = b58[i]; c = b58tobin_tbl[c]; for (j = 6; j >= 0; j--) { t = ((uint64_t)bin32[j]) * 58 + c; c = (t & 0x3f00000000ull) >> 32; bin32[j] = t & 0xffffffffull; } } *(b58bin++) = bin32[0] & 0xff; for (i = 1; i < 7; i++) { *((uint32_t *)b58bin) = htobe32(bin32[i]); b58bin += sizeof(uint32_t); } } void address_to_pubkeyhash(unsigned char *pkh, const char *addr) { unsigned char b58bin[25]; memset(b58bin, 0, 25); b58tobin(b58bin, addr); pkh[0] = 0x76; pkh[1] = 0xa9; pkh[2] = 0x14; memcpy(&pkh[3], &b58bin[1], 20); pkh[23] = 0x88; pkh[24] = 0xac; } /* For encoding nHeight into coinbase, return how many bytes were used */ int ser_number(unsigned char *s, int32_t val) { int32_t *i32 = (int32_t *)&s[1]; int len; if (val < 128) len = 1; else if (val < 16512) len = 2; else if (val < 2113664) len = 3; else len = 4; *i32 = htole32(val); s[0] = len++; return len; } /* For encoding variable length strings */ unsigned char *ser_string(char *s, int *slen) { size_t len = strlen(s); unsigned char *ret; ret = malloc(1 + len + 8); // Leave room for largest size if (unlikely(!ret)) quit(1, "Failed to malloc ret in ser_string"); if (len < 253) { ret[0] = len; memcpy(ret + 1, s, len); *slen = len + 1; } else if (len < 0x10000) { uint16_t *u16 = (uint16_t *)&ret[1]; ret[0] = 253; *u16 = htobe16(len); memcpy(ret + 3, s, len); *slen = len + 3; } else { /* size_t is only 32 bit on many platforms anyway */ uint32_t *u32 = (uint32_t *)&ret[1]; ret[0] = 254; *u32 = htobe32(len); memcpy(ret + 5, s, len); *slen = len + 5; } return ret; } bool fulltest(const unsigned char *hash, const unsigned char *target) { uint32_t *hash32 = (uint32_t *)hash; uint32_t *target32 = (uint32_t *)target; bool rc = true; int i; for (i = 28 / 4; i >= 0; i--) { uint32_t h32tmp = le32toh(hash32[i]); uint32_t t32tmp = le32toh(target32[i]); if (h32tmp > t32tmp) { rc = false; break; } if (h32tmp < t32tmp) { rc = true; break; } } if (opt_debug) { unsigned char hash_swap[32], target_swap[32]; char *hash_str, *target_str; swab256(hash_swap, hash); swab256(target_swap, target); hash_str = bin2hex(hash_swap, 32); target_str = bin2hex(target_swap, 32); applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s", hash_str, target_str, rc ? "YES (hash <= target)" : "no (false positive; hash > target)"); free(hash_str); free(target_str); } return rc; } struct thread_q *tq_new(void) { struct thread_q *tq; tq = calloc(1, sizeof(*tq)); if (!tq) return NULL; INIT_LIST_HEAD(&tq->q); pthread_mutex_init(&tq->mutex, NULL); pthread_cond_init(&tq->cond, NULL); return tq; } void tq_free(struct thread_q *tq) { struct tq_ent *ent, *iter; if (!tq) return; list_for_each_entry_safe(ent, iter, &tq->q, q_node) { list_del(&ent->q_node); free(ent); } pthread_cond_destroy(&tq->cond); pthread_mutex_destroy(&tq->mutex); memset(tq, 0, sizeof(*tq)); /* poison */ free(tq); } static void tq_freezethaw(struct thread_q *tq, bool frozen) { mutex_lock(&tq->mutex); tq->frozen = frozen; pthread_cond_signal(&tq->cond); mutex_unlock(&tq->mutex); } void tq_freeze(struct thread_q *tq) { tq_freezethaw(tq, true); } void tq_thaw(struct thread_q *tq) { tq_freezethaw(tq, false); } bool tq_push(struct thread_q *tq, void *data) { struct tq_ent *ent; bool rc = true; ent = calloc(1, sizeof(*ent)); if (!ent) return false; ent->data = data; INIT_LIST_HEAD(&ent->q_node); mutex_lock(&tq->mutex); if (!tq->frozen) { list_add_tail(&ent->q_node, &tq->q); } else { free(ent); rc = false; } pthread_cond_signal(&tq->cond); mutex_unlock(&tq->mutex); return rc; } void *tq_pop(struct thread_q *tq, const struct timespec *abstime) { struct tq_ent *ent; void *rval = NULL; int rc; mutex_lock(&tq->mutex); if (!list_empty(&tq->q)) goto pop; if (abstime) rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime); else rc = pthread_cond_wait(&tq->cond, &tq->mutex); if (rc) goto out; if (list_empty(&tq->q)) goto out; pop: ent = list_entry(tq->q.next, struct tq_ent, q_node); rval = ent->data; list_del(&ent->q_node); free(ent); out: mutex_unlock(&tq->mutex); return rval; } int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg) { cgsem_init(&thr->sem); return pthread_create(&thr->pth, attr, start, arg); } void thr_info_cancel(struct thr_info *thr) { if (!thr) return; if (PTH(thr) != 0L) { pthread_cancel(thr->pth); PTH(thr) = 0L; } cgsem_destroy(&thr->sem); } void subtime(struct timeval *a, struct timeval *b) { timersub(a, b, b); } void addtime(struct timeval *a, struct timeval *b) { timeradd(a, b, b); } bool time_more(struct timeval *a, struct timeval *b) { return timercmp(a, b, >); } bool time_less(struct timeval *a, struct timeval *b) { return timercmp(a, b, <); } void copy_time(struct timeval *dest, const struct timeval *src) { memcpy(dest, src, sizeof(struct timeval)); } void timespec_to_val(struct timeval *val, const struct timespec *spec) { val->tv_sec = spec->tv_sec; val->tv_usec = spec->tv_nsec / 1000; } void timeval_to_spec(struct timespec *spec, const struct timeval *val) { spec->tv_sec = val->tv_sec; spec->tv_nsec = val->tv_usec * 1000; } void us_to_timeval(struct timeval *val, int64_t us) { lldiv_t tvdiv = lldiv(us, 1000000); val->tv_sec = tvdiv.quot; val->tv_usec = tvdiv.rem; } void us_to_timespec(struct timespec *spec, int64_t us) { lldiv_t tvdiv = lldiv(us, 1000000); spec->tv_sec = tvdiv.quot; spec->tv_nsec = tvdiv.rem * 1000; } void ms_to_timespec(struct timespec *spec, int64_t ms) { lldiv_t tvdiv = lldiv(ms, 1000); spec->tv_sec = tvdiv.quot; spec->tv_nsec = tvdiv.rem * 1000000; } void ms_to_timeval(struct timeval *val, int64_t ms) { lldiv_t tvdiv = lldiv(ms, 1000); val->tv_sec = tvdiv.quot; val->tv_usec = tvdiv.rem * 1000; } void timeraddspec(struct timespec *a, const struct timespec *b) { a->tv_sec += b->tv_sec; a->tv_nsec += b->tv_nsec; if (a->tv_nsec >= 1000000000) { a->tv_nsec -= 1000000000; a->tv_sec++; } } static int __maybe_unused timespec_to_ms(struct timespec *ts) { return ts->tv_sec * 1000 + ts->tv_nsec / 1000000; } /* Subtract b from a */ static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b) { a->tv_sec -= b->tv_sec; a->tv_nsec -= b->tv_nsec; if (a->tv_nsec < 0) { a->tv_nsec += 1000000000; a->tv_sec--; } } /* These are cgminer specific sleep functions that use an absolute nanosecond * resolution timer to avoid poor usleep accuracy and overruns. */ #ifdef WIN32 /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */ #define EPOCHFILETIME (116444736000000000LL) /* Return the system time as an lldiv_t in decimicroseconds. */ static void decius_time(lldiv_t *lidiv) { FILETIME ft; LARGE_INTEGER li; GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; li.QuadPart -= EPOCHFILETIME; /* SystemTime is in decimicroseconds so divide by an unusual number */ *lidiv = lldiv(li.QuadPart, 10000000); } /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday * with tz set to NULL, and windows' default resolution is only 15ms, this * gives us higher resolution times on windows. */ void cgtime(struct timeval *tv) { lldiv_t lidiv; decius_time(&lidiv); tv->tv_sec = lidiv.quot; tv->tv_usec = lidiv.rem / 10; } #else /* WIN32 */ void cgtime(struct timeval *tv) { gettimeofday(tv, NULL); } int cgtimer_to_ms(cgtimer_t *cgt) { return timespec_to_ms(cgt); } /* Subtracts b from a and stores it in res. */ void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res) { res->tv_sec = a->tv_sec - b->tv_sec; res->tv_nsec = a->tv_nsec - b->tv_nsec; if (res->tv_nsec < 0) { res->tv_nsec += 1000000000; res->tv_sec--; } } #endif /* WIN32 */ #ifdef CLOCK_MONOTONIC /* Essentially just linux */ void cgtimer_time(cgtimer_t *ts_start) { clock_gettime(CLOCK_MONOTONIC, ts_start); } static void nanosleep_abstime(struct timespec *ts_end) { int ret; do { ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL); } while (ret == EINTR); } /* Reentrant version of cgsleep functions allow start time to be set separately * from the beginning of the actual sleep, allowing scheduling delays to be * counted in the sleep. */ void cgsleep_ms_r(cgtimer_t *ts_start, int ms) { struct timespec ts_end; ms_to_timespec(&ts_end, ms); timeraddspec(&ts_end, ts_start); nanosleep_abstime(&ts_end); } void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { struct timespec ts_end; us_to_timespec(&ts_end, us); timeraddspec(&ts_end, ts_start); nanosleep_abstime(&ts_end); } #else /* CLOCK_MONOTONIC */ #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> void cgtimer_time(cgtimer_t *ts_start) { clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts_start->tv_sec = mts.tv_sec; ts_start->tv_nsec = mts.tv_nsec; } #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */ void cgtimer_time(cgtimer_t *ts_start) { struct timeval tv; cgtime(&tv); ts_start->tv_sec = tv->tv_sec; ts_start->tv_nsec = tv->tv_usec * 1000; } #endif /* __MACH__ */ #ifdef WIN32 /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t * typedef, allowing us to have sub-microsecond resolution for times, do simple * arithmetic for timer calculations, and use windows' own hTimers to get * accurate absolute timeouts. */ int cgtimer_to_ms(cgtimer_t *cgt) { return (int)(cgt->QuadPart / 10000LL); } /* Subtracts b from a and stores it in res. */ void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res) { res->QuadPart = a->QuadPart - b->QuadPart; } /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute * timeouts with hTimers. */ void cgtimer_time(cgtimer_t *ts_start) { FILETIME ft; GetSystemTimeAsFileTime(&ft); ts_start->LowPart = ft.dwLowDateTime; ts_start->HighPart = ft.dwHighDateTime; } static void liSleep(LARGE_INTEGER *li, int timeout) { HANDLE hTimer; DWORD ret; if (unlikely(timeout <= 0)) return; hTimer = CreateWaitableTimer(NULL, TRUE, NULL); if (unlikely(!hTimer)) quit(1, "Failed to create hTimer in liSleep"); ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0); if (unlikely(!ret)) quit(1, "Failed to SetWaitableTimer in liSleep"); /* We still use a timeout as a sanity check in case the system time * is changed while we're running */ ret = WaitForSingleObject(hTimer, timeout); if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT)) quit(1, "Failed to WaitForSingleObject in liSleep"); CloseHandle(hTimer); } void cgsleep_ms_r(cgtimer_t *ts_start, int ms) { LARGE_INTEGER li; li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL; liSleep(&li, ms); } void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { LARGE_INTEGER li; int ms; li.QuadPart = ts_start->QuadPart + us * 10LL; ms = us / 1000; if (!ms) ms = 1; liSleep(&li, ms); } #else /* WIN32 */ static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start) { struct timespec now; timeraddspec(ts_diff, ts_start); cgtimer_time(&now); timersubspec(ts_diff, &now); if (unlikely(ts_diff->tv_sec < 0)) return; nanosleep(ts_diff, NULL); } void cgsleep_ms_r(cgtimer_t *ts_start, int ms) { struct timespec ts_diff; ms_to_timespec(&ts_diff, ms); cgsleep_spec(&ts_diff, ts_start); } void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { struct timespec ts_diff; us_to_timespec(&ts_diff, us); cgsleep_spec(&ts_diff, ts_start); } #endif /* WIN32 */ #endif /* CLOCK_MONOTONIC */ void cgsleep_ms(int ms) { cgtimer_t ts_start; cgsleep_prepare_r(&ts_start); cgsleep_ms_r(&ts_start, ms); } void cgsleep_us(int64_t us) { cgtimer_t ts_start; cgsleep_prepare_r(&ts_start); cgsleep_us_r(&ts_start, us); } /* Returns the microseconds difference between end and start times as a double */ double us_tdiff(struct timeval *end, struct timeval *start) { /* Sanity check. We should only be using this for small differences so * limit the max to 60 seconds. */ if (unlikely(end->tv_sec - start->tv_sec > 60)) return 60000000; return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec); } /* Returns the milliseconds difference between end and start times */ int ms_tdiff(struct timeval *end, struct timeval *start) { /* Like us_tdiff, limit to 1 hour. */ if (unlikely(end->tv_sec - start->tv_sec > 3600)) return 3600000; return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000; } /* Returns the seconds difference between end and start times as a double */ double tdiff(struct timeval *end, struct timeval *start) { return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0; } bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; snprintf(url_address, 254, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; } enum send_ret { SEND_OK, SEND_SELECTFAIL, SEND_SENDFAIL, SEND_INACTIVE }; /* Send a single command across a socket, appending \n to it. This should all * be done under stratum lock except when first establishing the socket */ static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len) { SOCKETTYPE sock = pool->sock; ssize_t ssent = 0; strcat(s, "\n"); len++; while (len > 0 ) { struct timeval timeout = {1, 0}; ssize_t sent; fd_set wd; retry: FD_ZERO(&wd); FD_SET(sock, &wd); if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) { if (interrupted()) goto retry; return SEND_SELECTFAIL; } #ifdef __APPLE__ sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE); #elif WIN32 sent = send(pool->sock, s + ssent, len, 0); #else sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL); #endif if (sent < 0) { if (!sock_blocks()) return SEND_SENDFAIL; sent = 0; } ssent += sent; len -= sent; } pool->cgminer_pool_stats.times_sent++; pool->cgminer_pool_stats.bytes_sent += ssent; pool->cgminer_pool_stats.net_bytes_sent += ssent; return SEND_OK; } bool stratum_send(struct pool *pool, char *s, ssize_t len) { enum send_ret ret = SEND_INACTIVE; if (opt_protocol) applog(LOG_DEBUG, "SEND: %s", s); mutex_lock(&pool->stratum_lock); if (pool->stratum_active) ret = __stratum_send(pool, s, len); mutex_unlock(&pool->stratum_lock); /* This is to avoid doing applog under stratum_lock */ switch (ret) { default: case SEND_OK: break; case SEND_SELECTFAIL: applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no); suspend_stratum(pool); break; case SEND_SENDFAIL: applog(LOG_DEBUG, "Failed to send in stratum_send"); suspend_stratum(pool); break; case SEND_INACTIVE: applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active"); break; } return (ret == SEND_OK); } static bool socket_full(struct pool *pool, int wait) { SOCKETTYPE sock = pool->sock; struct timeval timeout; fd_set rd; if (unlikely(wait < 0)) wait = 0; FD_ZERO(&rd); FD_SET(sock, &rd); timeout.tv_usec = 0; timeout.tv_sec = wait; if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0) return true; return false; } /* Check to see if Santa's been good to you */ bool sock_full(struct pool *pool) { if (strlen(pool->sockbuf)) return true; return (socket_full(pool, 0)); } static void clear_sockbuf(struct pool *pool) { strcpy(pool->sockbuf, ""); } static void clear_sock(struct pool *pool) { ssize_t n; mutex_lock(&pool->stratum_lock); do { if (pool->sock) n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0); else n = 0; } while (n > 0); mutex_unlock(&pool->stratum_lock); clear_sockbuf(pool); } /* Realloc memory to new size and zero any extra memory added */ void _recalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line) { if (new == old) return; *ptr = realloc(*ptr, new); if (unlikely(!*ptr)) quitfrom(1, file, func, line, "Failed to realloc"); if (new > old) memset(*ptr + old, 0, new - old); } /* Make sure the pool sockbuf is large enough to cope with any coinbase size * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE * and zeroing the new memory */ static void recalloc_sock(struct pool *pool, size_t len) { size_t old, new; old = strlen(pool->sockbuf); new = old + len + 1; if (new < pool->sockbuf_size) return; new = new + (RBUFSIZE - (new % RBUFSIZE)); // Avoid potentially recursive locking // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new); pool->sockbuf = realloc(pool->sockbuf, new); if (!pool->sockbuf) quithere(1, "Failed to realloc pool sockbuf"); memset(pool->sockbuf + old, 0, new - old); pool->sockbuf_size = new; } /* Peeks at a socket to find the first end of line and then reads just that * from the socket and returns that as a malloced char */ char *recv_line(struct pool *pool) { char *tok, *sret = NULL; ssize_t len, buflen; int waited = 0; if (!strstr(pool->sockbuf, "\n")) { struct timeval rstart, now; cgtime(&rstart); if (!socket_full(pool, DEFAULT_SOCKWAIT)) { applog(LOG_DEBUG, "Timed out waiting for data on socket_full"); goto out; } do { char s[RBUFSIZE]; size_t slen; ssize_t n; memset(s, 0, RBUFSIZE); n = recv(pool->sock, s, RECVSIZE, 0); if (!n) { applog(LOG_DEBUG, "Socket closed waiting in recv_line"); suspend_stratum(pool); break; } cgtime(&now); waited = tdiff(&now, &rstart); if (n < 0) { if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) { applog(LOG_DEBUG, "Failed to recv sock in recv_line"); suspend_stratum(pool); break; } } else { slen = strlen(s); recalloc_sock(pool, slen); strcat(pool->sockbuf, s); } } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n")); } buflen = strlen(pool->sockbuf); tok = strtok(pool->sockbuf, "\n"); if (!tok) { applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line"); goto out; } sret = strdup(tok); len = strlen(sret); /* Copy what's left in the buffer after the \n, including the * terminating \0 */ if (buflen > len + 1) memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1); else strcpy(pool->sockbuf, ""); pool->cgminer_pool_stats.times_received++; pool->cgminer_pool_stats.bytes_received += len; pool->cgminer_pool_stats.net_bytes_received += len; out: if (!sret) clear_sock(pool); else if (opt_protocol) applog(LOG_DEBUG, "RECVD: %s", sret); return sret; } /* Extracts a string value from a json array with error checking. To be used * when the value of the string returned is only examined and not to be stored. * See json_array_string below */ static char *__json_array_string(json_t *val, unsigned int entry) { json_t *arr_entry; if (json_is_null(val)) return NULL; if (!json_is_array(val)) return NULL; if (entry > json_array_size(val)) return NULL; arr_entry = json_array_get(val, entry); if (!json_is_string(arr_entry)) return NULL; return (char *)json_string_value(arr_entry); } /* Creates a freshly malloced dup of __json_array_string */ static char *json_array_string(json_t *val, unsigned int entry) { char *buf = __json_array_string(val, entry); if (buf) return strdup(buf); return NULL; } static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000"; static bool parse_notify(struct pool *pool, json_t *val) { char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime, header[228]; unsigned char *cb1 = NULL, *cb2 = NULL; size_t cb1_len, cb2_len, alloc_len; bool clean, ret = false; int merkles, i; json_t *arr; arr = json_array_get(val, 4); if (!arr || !json_is_array(arr)) goto out; merkles = json_array_size(arr); job_id = json_array_string(val, 0); prev_hash = __json_array_string(val, 1); coinbase1 = json_array_string(val, 2); coinbase2 = json_array_string(val, 3); bbversion = __json_array_string(val, 5); nbit = __json_array_string(val, 6); ntime = __json_array_string(val, 7); clean = json_is_true(json_array_get(val, 8)); if (!valid_hex(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) || !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) || !valid_hex(ntime)) { /* Annoying but we must not leak memory */ free(job_id); free(coinbase1); free(coinbase2); goto out; } cg_wlock(&pool->data_lock); free(pool->swork.job_id); pool->swork.job_id = job_id; snprintf(pool->prev_hash, 65, "%s", prev_hash); cb1_len = strlen(coinbase1) / 2; cb2_len = strlen(coinbase2) / 2; snprintf(pool->bbversion, 9, "%s", bbversion); snprintf(pool->nbit, 9, "%s", nbit); snprintf(pool->ntime, 9, "%s", ntime); pool->swork.clean = clean; alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len; pool->nonce2_offset = cb1_len + pool->n1_len; for (i = 0; i < pool->merkles; i++) free(pool->swork.merkle_bin[i]); if (merkles) { pool->swork.merkle_bin = realloc(pool->swork.merkle_bin, sizeof(char *) * merkles + 1); for (i = 0; i < merkles; i++) { char *merkle = json_array_string(arr, i); pool->swork.merkle_bin[i] = malloc(32); if (unlikely(!pool->swork.merkle_bin[i])) quit(1, "Failed to malloc pool swork merkle_bin"); if (opt_protocol) applog(LOG_DEBUG, "merkle %d: %s", i, merkle); ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32); free(merkle); if (unlikely(!ret)) { applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify"); goto out_unlock; } } } pool->merkles = merkles; if (clean) pool->nonce2 = 0; #if 0 header_len = strlen(pool->bbversion) + strlen(pool->prev_hash); /* merkle_hash */ 32 + strlen(pool->ntime) + strlen(pool->nbit) + /* nonce */ 8 + /* workpadding */ 96; #endif snprintf(header, 225, "%s%s%s%s%s%s%s", pool->bbversion, pool->prev_hash, blank_merkle, pool->ntime, pool->nbit, "00000000", /* nonce */ workpadding); ret = hex2bin(pool->header_bin, header, 112); if (unlikely(!ret)) { applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify"); goto out_unlock; } cb1 = alloca(cb1_len); ret = hex2bin(cb1, coinbase1, cb1_len); if (unlikely(!ret)) { applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify"); goto out_unlock; } cb2 = alloca(cb2_len); ret = hex2bin(cb2, coinbase2, cb2_len); if (unlikely(!ret)) { applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify"); goto out_unlock; } free(pool->coinbase); align_len(&alloc_len); pool->coinbase = calloc(alloc_len, 1); if (unlikely(!pool->coinbase)) quit(1, "Failed to calloc pool coinbase in parse_notify"); memcpy(pool->coinbase, cb1, cb1_len); memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len); memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len); if (opt_debug) { char *cb = bin2hex(pool->coinbase, pool->coinbase_len); applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb); free(cb); } out_unlock: cg_wunlock(&pool->data_lock); if (opt_protocol) { applog(LOG_DEBUG, "job_id: %s", job_id); applog(LOG_DEBUG, "prev_hash: %s", prev_hash); applog(LOG_DEBUG, "coinbase1: %s", coinbase1); applog(LOG_DEBUG, "coinbase2: %s", coinbase2); applog(LOG_DEBUG, "bbversion: %s", bbversion); applog(LOG_DEBUG, "nbit: %s", nbit); applog(LOG_DEBUG, "ntime: %s", ntime); applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no"); } free(coinbase1); free(coinbase2); /* A notify message is the closest stratum gets to a getwork */ pool->getwork_requested++; total_getworks++; if (pool == current_pool()) opt_work_update = true; out: return ret; } static bool parse_diff(struct pool *pool, json_t *val) { double old_diff, diff; diff = json_number_value(json_array_get(val, 0)); if (diff == 0) return false; cg_wlock(&pool->data_lock); old_diff = pool->sdiff; pool->sdiff = diff; cg_wunlock(&pool->data_lock); if (old_diff != diff) { int idiff = diff; if ((double)idiff == diff) applog(LOG_NOTICE, "Pool %d difficulty changed to %d", pool->pool_no, idiff); else applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f", pool->pool_no, diff); } else applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff); return true; } static void __suspend_stratum(struct pool *pool) { clear_sockbuf(pool); pool->stratum_active = pool->stratum_notify = false; if (pool->sock) CLOSESOCKET(pool->sock); pool->sock = 0; } static bool parse_reconnect(struct pool *pool, json_t *val) { char *sockaddr_url, *stratum_port, *tmp; char *url, *port, address[256]; memset(address, 0, 255); url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; else { char *dot_pool, *dot_reconnect; dot_pool = strchr(pool->sockaddr_url, '.'); if (!dot_pool) { applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'", pool->sockaddr_url); return false; } dot_reconnect = strchr(url, '.'); if (!dot_reconnect) { applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'", url); return false; } if (strcmp(dot_pool, dot_reconnect)) { applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'", pool->sockaddr_url); return false; } } port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; snprintf(address, 254, "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; } static bool send_version(struct pool *pool, json_t *val) { char s[RBUFSIZE]; int id = json_integer_value(json_object_get(val, "id")); if (!id) return false; sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id); if (!stratum_send(pool, s, strlen(s))) return false; return true; } static bool show_message(struct pool *pool, json_t *val) { char *msg; if (!json_is_array(val)) return false; msg = (char *)json_string_value(json_array_get(val, 0)); if (!msg) return false; applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg); return true; } bool parse_method(struct pool *pool, char *s) { json_t *val = NULL, *method, *err_val, *params; json_error_t err; bool ret = false; char *buf; if (!s) goto out; val = JSON_LOADS(s, &err); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } method = json_object_get(val, "method"); if (!method) goto out_decref; err_val = json_object_get(val, "error"); params = json_object_get(val, "params"); if (err_val && !json_is_null(err_val)) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss); free(ss); goto out_decref; } buf = (char *)json_string_value(method); if (!buf) goto out_decref; if (!strncasecmp(buf, "mining.notify", 13)) { if (parse_notify(pool, params)) pool->stratum_notify = ret = true; else pool->stratum_notify = ret = false; goto out_decref; } if (!strncasecmp(buf, "mining.set_difficulty", 21)) { ret = parse_diff(pool, params); goto out_decref; } if (!strncasecmp(buf, "client.reconnect", 16)) { ret = parse_reconnect(pool, params); goto out_decref; } if (!strncasecmp(buf, "client.get_version", 18)) { ret = send_version(pool, val); goto out_decref; } if (!strncasecmp(buf, "client.show_message", 19)) { ret = show_message(pool, params); goto out_decref; } out_decref: json_decref(val); out: return ret; } bool auth_stratum(struct pool *pool) { json_t *val = NULL, *res_val, *err_val; char s[RBUFSIZE], *sret = NULL; json_error_t err; bool ret = false; sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}", swork_id++, pool->rpc_user, pool->rpc_pass); if (!stratum_send(pool, s, strlen(s))) return ret; /* Parse all data in the queue and anything left should be auth */ while (42) { sret = recv_line(pool); if (!sret) return ret; if (parse_method(pool, sret)) free(sret); else break; } val = JSON_LOADS(sret, &err); free(sret); res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss); free(ss); suspend_stratum(pool); goto out; } ret = true; applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no); pool->probed = true; successful_connect = true; out: json_decref(val); return ret; } static int recv_byte(int sockd) { char c; if (recv(sockd, &c, 1, 0) != -1) return c; return -1; } static bool http_negotiate(struct pool *pool, int sockd, bool http0) { char buf[1024]; int i, len; if (http0) { snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n", pool->sockaddr_url, pool->stratum_port); } else { snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n", pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url, pool->stratum_port); } applog(LOG_DEBUG, "Sending proxy %s:%s - %s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf); send(sockd, buf, strlen(buf), 0); len = recv(sockd, buf, 12, 0); if (len <= 0) { applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } buf[len] = '\0'; applog(LOG_DEBUG, "Received from proxy %s:%s - %s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf); if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) { applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf); return false; } /* Ignore unwanted headers till we get desired response */ for (i = 0; i < 4; i++) { buf[i] = recv_byte(sockd); if (buf[i] == (char)-1) { applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } } while (strncmp(buf, "\r\n\r\n", 4)) { for (i = 0; i < 3; i++) buf[i] = buf[i + 1]; buf[3] = recv_byte(sockd); if (buf[3] == (char)-1) { applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } } applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return true; } static bool socks5_negotiate(struct pool *pool, int sockd) { unsigned char atyp, uclen; unsigned short port; char buf[515]; int i, len; buf[0] = 0x05; buf[1] = 0x01; buf[2] = 0x00; applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); send(sockd, buf, 3, 0); if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) { applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); return false; } buf[0] = 0x05; buf[1] = 0x01; buf[2] = 0x00; buf[3] = 0x03; len = (strlen(pool->sockaddr_url)); if (len > 255) len = 255; uclen = len; buf[4] = (uclen & 0xff); memcpy(buf + 5, pool->sockaddr_url, len); port = atoi(pool->stratum_port); buf[5 + len] = (port >> 8); buf[6 + len] = (port & 0xff); send(sockd, buf, (7 + len), 0); if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) { applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); return false; } recv_byte(sockd); atyp = recv_byte(sockd); if (atyp == 0x01) { for (i = 0; i < 4; i++) recv_byte(sockd); } else if (atyp == 0x03) { len = recv_byte(sockd); for (i = 0; i < len; i++) recv_byte(sockd); } else { applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); return false; } for (i = 0; i < 2; i++) recv_byte(sockd); applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return true; } static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a) { unsigned short port; in_addr_t inp; char buf[515]; int i, len; buf[0] = 0x04; buf[1] = 0x01; port = atoi(pool->stratum_port); buf[2] = port >> 8; buf[3] = port & 0xff; sprintf(&buf[8], "CGMINER"); /* See if we've been given an IP address directly to avoid needing to * resolve it. */ inp = inet_addr(pool->sockaddr_url); inp = ntohl(inp); if ((int)inp != -1) socks4a = false; else { /* Try to extract the IP address ourselves first */ struct addrinfo servinfobase, *servinfo, hints; servinfo = &servinfobase; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; /* IPV4 only */ if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) { struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr; inp = ntohl(saddr_in->sin_addr.s_addr); socks4a = false; freeaddrinfo(servinfo); } } if (!socks4a) { if ((int)inp == -1) { applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s", pool->sockaddr_url); return false; } buf[4] = (inp >> 24) & 0xFF; buf[5] = (inp >> 16) & 0xFF; buf[6] = (inp >> 8) & 0xFF; buf[7] = (inp >> 0) & 0xFF; send(sockd, buf, 16, 0); } else { /* This appears to not be working but hopefully most will be * able to resolve IP addresses themselves. */ buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = 1; len = strlen(pool->sockaddr_url); if (len > 255) len = 255; memcpy(&buf[16], pool->sockaddr_url, len); len += 16; buf[len++] = '\0'; send(sockd, buf, len, 0); } if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) { applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } for (i = 0; i < 6; i++) recv_byte(sockd); return true; } static void noblock_socket(SOCKETTYPE fd) { #ifndef WIN32 int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, O_NONBLOCK | flags); #else u_long flags = 1; ioctlsocket(fd, FIONBIO, &flags); #endif } static void block_socket(SOCKETTYPE fd) { #ifndef WIN32 int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); #else u_long flags = 0; ioctlsocket(fd, FIONBIO, &flags); #endif } static bool sock_connecting(void) { #ifndef WIN32 return errno == EINPROGRESS; #else return WSAGetLastError() == WSAEWOULDBLOCK; #endif } static bool setup_stratum_socket(struct pool *pool) { struct addrinfo servinfobase, *servinfo, *hints, *p; char *sockaddr_url, *sockaddr_port; int sockd; mutex_lock(&pool->stratum_lock); pool->stratum_active = false; if (pool->sock) CLOSESOCKET(pool->sock); pool->sock = 0; mutex_unlock(&pool->stratum_lock); hints = &pool->stratum_hints; memset(hints, 0, sizeof(struct addrinfo)); hints->ai_family = AF_UNSPEC; hints->ai_socktype = SOCK_STREAM; servinfo = &servinfobase; if (!pool->rpc_proxy && opt_socks_proxy) { pool->rpc_proxy = opt_socks_proxy; extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port); pool->rpc_proxytype = PROXY_SOCKS5; } if (pool->rpc_proxy) { sockaddr_url = pool->sockaddr_proxy_url; sockaddr_port = pool->sockaddr_proxy_port; } else { sockaddr_url = pool->sockaddr_url; sockaddr_port = pool->stratum_port; } if (getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo) != 0) { if (!pool->probed) { applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s", sockaddr_url, sockaddr_port); pool->probed = true; } else { applog(LOG_INFO, "Failed to getaddrinfo for %s:%s", sockaddr_url, sockaddr_port); } return false; } for (p = servinfo; p != NULL; p = p->ai_next) { sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sockd == -1) { applog(LOG_DEBUG, "Failed socket"); continue; } /* Iterate non blocking over entries returned by getaddrinfo * to cope with round robin DNS entries, finding the first one * we can connect to quickly. */ noblock_socket(sockd); if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) { struct timeval tv_timeout = {1, 0}; int selret; fd_set rw; if (!sock_connecting()) { CLOSESOCKET(sockd); applog(LOG_DEBUG, "Failed sock connect"); continue; } retry: FD_ZERO(&rw); FD_SET(sockd, &rw); selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout); if (selret > 0 && FD_ISSET(sockd, &rw)) { socklen_t len; int err, n; len = sizeof(err); n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len); if (!n && !err) { applog(LOG_DEBUG, "Succeeded delayed connect"); block_socket(sockd); break; } } if (selret < 0 && interrupted()) goto retry; CLOSESOCKET(sockd); applog(LOG_DEBUG, "Select timeout/failed connect"); continue; } applog(LOG_WARNING, "Succeeded immediate connect"); block_socket(sockd); break; } if (p == NULL) { applog(LOG_INFO, "Failed to connect to stratum on %s:%s", sockaddr_url, sockaddr_port); freeaddrinfo(servinfo); return false; } freeaddrinfo(servinfo); if (pool->rpc_proxy) { switch (pool->rpc_proxytype) { case PROXY_HTTP_1_0: if (!http_negotiate(pool, sockd, true)) return false; break; case PROXY_HTTP: if (!http_negotiate(pool, sockd, false)) return false; break; case PROXY_SOCKS5: case PROXY_SOCKS5H: if (!socks5_negotiate(pool, sockd)) return false; break; case PROXY_SOCKS4: if (!socks4_negotiate(pool, sockd, false)) return false; break; case PROXY_SOCKS4A: if (!socks4_negotiate(pool, sockd, true)) return false; break; default: applog(LOG_WARNING, "Unsupported proxy type for %s:%s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; break; } } if (!pool->sockbuf) { pool->sockbuf = calloc(RBUFSIZE, 1); if (!pool->sockbuf) quithere(1, "Failed to calloc pool sockbuf"); pool->sockbuf_size = RBUFSIZE; } pool->sock = sockd; keep_sockalive(sockd); return true; } static char *get_sessionid(json_t *val) { char *ret = NULL; json_t *arr_val; int arrsize, i; arr_val = json_array_get(val, 0); if (!arr_val || !json_is_array(arr_val)) goto out; arrsize = json_array_size(arr_val); for (i = 0; i < arrsize; i++) { json_t *arr = json_array_get(arr_val, i); char *notify; if (!arr | !json_is_array(arr)) break; notify = __json_array_string(arr, 0); if (!notify) continue; if (!strncasecmp(notify, "mining.notify", 13)) { ret = json_array_string(arr, 1); break; } } out: return ret; } void suspend_stratum(struct pool *pool) { applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); mutex_unlock(&pool->stratum_lock); } bool initiate_stratum(struct pool *pool) { bool ret = false, recvd = false, noresume = false, sockd = false; char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid; json_t *val = NULL, *res_val, *err_val; json_error_t err; int n2size; resend: if (!setup_stratum_socket(pool)) { sockd = false; goto out; } sockd = true; if (recvd) { /* Get rid of any crap lying around if we're resending */ clear_sock(pool); sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++); } else { if (pool->sessionid) sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid); else sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++); } if (__stratum_send(pool, s, strlen(s)) != SEND_OK) { applog(LOG_DEBUG, "Failed to send s in initiate_stratum"); goto out; } if (!socket_full(pool, DEFAULT_SOCKWAIT)) { applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum"); goto out; } sret = recv_line(pool); if (!sret) goto out; recvd = true; val = JSON_LOADS(sret, &err); free(sret); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_null(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC decode failed: %s", ss); free(ss); goto out; } sessionid = get_sessionid(res_val); if (!sessionid) applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum"); nonce1 = json_array_string(res_val, 1); if (!valid_hex(nonce1)) { applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum"); free(sessionid); goto out; } n2size = json_integer_value(json_array_get(res_val, 2)); if (n2size < 2 || n2size > 16) { applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum"); free(sessionid); free(nonce1); goto out; } cg_wlock(&pool->data_lock); pool->sessionid = sessionid; pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; free(pool->nonce1bin); pool->nonce1bin = calloc(pool->n1_len, 1); if (unlikely(!pool->nonce1bin)) quithere(1, "Failed to calloc pool->nonce1bin"); hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len); pool->n2size = n2size; cg_wunlock(&pool->data_lock); if (sessionid) applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid); ret = true; out: if (ret) { if (!pool->stratum_url) pool->stratum_url = pool->sockaddr_url; pool->stratum_active = true; pool->sdiff = 1; if (opt_protocol) { applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d", pool->pool_no, pool->nonce1, pool->n2size); } } else { if (recvd && !noresume) { /* Reset the sessionid used for stratum resuming in case the pool * does not support it, or does not know how to respond to the * presence of the sessionid parameter. */ cg_wlock(&pool->data_lock); free(pool->sessionid); free(pool->nonce1); pool->sessionid = pool->nonce1 = NULL; cg_wunlock(&pool->data_lock); applog(LOG_DEBUG, "Failed to resume stratum, trying afresh"); noresume = true; json_decref(val); goto resend; } applog(LOG_DEBUG, "Initiate stratum failed"); if (sockd) suspend_stratum(pool); } json_decref(val); return ret; } bool restart_stratum(struct pool *pool) { if (pool->stratum_active) suspend_stratum(pool); if (!initiate_stratum(pool)) return false; if (!auth_stratum(pool)) return false; return true; } void dev_error(struct cgpu_info *dev, enum dev_reason reason) { dev->device_last_not_well = time(NULL); dev->device_not_well_reason = reason; switch (reason) { case REASON_THREAD_FAIL_INIT: dev->thread_fail_init_count++; break; case REASON_THREAD_ZERO_HASH: dev->thread_zero_hash_count++; break; case REASON_THREAD_FAIL_QUEUE: dev->thread_fail_queue_count++; break; case REASON_DEV_SICK_IDLE_60: dev->dev_sick_idle_60_count++; break; case REASON_DEV_DEAD_IDLE_600: dev->dev_dead_idle_600_count++; break; case REASON_DEV_NOSTART: dev->dev_nostart_count++; break; case REASON_DEV_OVER_HEAT: dev->dev_over_heat_count++; break; case REASON_DEV_THERMAL_CUTOFF: dev->dev_thermal_cutoff_count++; break; case REASON_DEV_COMMS_ERROR: dev->dev_comms_error_count++; break; case REASON_DEV_THROTTLE: dev->dev_throttle_count++; break; } } /* Realloc an existing string to fit an extra string s, appending s to it. */ void *realloc_strcat(char *ptr, char *s) { size_t old = 0, len = strlen(s); char *ret; if (!len) return ptr; if (ptr) old = strlen(ptr); len += old + 1; align_len(&len); ret = malloc(len); if (unlikely(!ret)) quithere(1, "Failed to malloc"); if (ptr) { sprintf(ret, "%s%s", ptr, s); free(ptr); } else sprintf(ret, "%s", s); return ret; } /* Make a text readable version of a string using 0xNN for < ' ' or > '~' * Including 0x00 at the end * You must free the result yourself */ void *str_text(char *ptr) { unsigned char *uptr; char *ret, *txt; if (ptr == NULL) { ret = strdup("(null)"); if (unlikely(!ret)) quithere(1, "Failed to malloc null"); } uptr = (unsigned char *)ptr; ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed if (unlikely(!txt)) quithere(1, "Failed to malloc txt"); do { if (*uptr < ' ' || *uptr > '~') { sprintf(txt, "0x%02x", *uptr); txt += 4; } else *(txt++) = *uptr; } while (*(uptr++)); *txt = '\0'; return ret; } void RenameThread(const char* name) { char buf[16]; snprintf(buf, sizeof(buf), "cg@%s", name); #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) prctl(PR_SET_NAME, buf, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__)) pthread_set_name_np(pthread_self(), buf); #elif defined(MAC_OSX) pthread_setname_np(buf); #else // Prevent warnings (void)buf; #endif } /* cgminer specific wrappers for true unnamed semaphore usage on platforms * that support them and for apple which does not. We use a single byte across * a pipe to emulate semaphore behaviour there. */ #ifdef __APPLE__ void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line) { int flags, fd, i; if (pipe(cgsem->pipefd) == -1) quitfrom(1, file, func, line, "Failed pipe errno=%d", errno); /* Make the pipes FD_CLOEXEC to allow them to close should we call * execv on restart. */ for (i = 0; i < 2; i++) { fd = cgsem->pipefd[i]; flags = fcntl(fd, F_GETFD, 0); flags |= FD_CLOEXEC; if (fcntl(fd, F_SETFD, flags) == -1) quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno); } } void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line) { const char buf = 1; int ret; retry: ret = write(cgsem->pipefd[1], &buf, 1); if (unlikely(ret == 0)) applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line); else if (unlikely(ret < 0 && interrupted)) goto retry; } void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line) { char buf; int ret; retry: ret = read(cgsem->pipefd[0], &buf, 1); if (unlikely(ret == 0)) applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line); else if (unlikely(ret < 0 && interrupted)) goto retry; } void cgsem_destroy(cgsem_t *cgsem) { close(cgsem->pipefd[1]); close(cgsem->pipefd[0]); } /* This is similar to sem_timedwait but takes a millisecond value */ int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line) { struct timeval timeout; int ret, fd; fd_set rd; char buf; retry: fd = cgsem->pipefd[0]; FD_ZERO(&rd); FD_SET(fd, &rd); ms_to_timeval(&timeout, ms); ret = select(fd + 1, &rd, NULL, NULL, &timeout); if (ret > 0) { ret = read(fd, &buf, 1); return 0; } if (likely(!ret)) return ETIMEDOUT; if (interrupted()) goto retry; quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem); /* We don't reach here */ return 0; } /* Reset semaphore count back to zero */ void cgsem_reset(cgsem_t *cgsem) { int ret, fd; fd_set rd; char buf; fd = cgsem->pipefd[0]; FD_ZERO(&rd); FD_SET(fd, &rd); do { struct timeval timeout = {0, 0}; ret = select(fd + 1, &rd, NULL, NULL, &timeout); if (ret > 0) ret = read(fd, &buf, 1); else if (unlikely(ret < 0 && interrupted())) ret = 1; } while (ret > 0); } #else void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line) { int ret; if ((ret = sem_init(cgsem, 0, 0))) quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno); } void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line) { if (unlikely(sem_post(cgsem))) quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem); } void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line) { retry: if (unlikely(sem_wait(cgsem))) { if (interrupted()) goto retry; quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem); } } int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line) { struct timespec abs_timeout, ts_now; struct timeval tv_now; int ret; cgtime(&tv_now); timeval_to_spec(&ts_now, &tv_now); ms_to_timespec(&abs_timeout, ms); retry: timeraddspec(&abs_timeout, &ts_now); ret = sem_timedwait(cgsem, &abs_timeout); if (ret) { if (likely(sock_timeout())) return ETIMEDOUT; if (interrupted()) goto retry; quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem); } return 0; } void cgsem_reset(cgsem_t *cgsem) { int ret; do { ret = sem_trywait(cgsem); if (unlikely(ret < 0 && interrupted())) ret = 0; } while (!ret); } void cgsem_destroy(cgsem_t *cgsem) { sem_destroy(cgsem); } #endif /* Provide a completion_timeout helper function for unreliable functions that * may die due to driver issues etc that time out if the function fails and * can then reliably return. */ struct cg_completion { cgsem_t cgsem; void (*fn)(void *fnarg); void *fnarg; }; void *completion_thread(void *arg) { struct cg_completion *cgc = (struct cg_completion *)arg; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); cgc->fn(cgc->fnarg); cgsem_post(&cgc->cgsem); return NULL; } bool cg_completion_timeout(void *fn, void *fnarg, int timeout) { struct cg_completion *cgc; pthread_t pthread; bool ret = false; cgc = malloc(sizeof(struct cg_completion)); if (unlikely(!cgc)) return ret; cgsem_init(&cgc->cgsem); cgc->fn = fn; cgc->fnarg = fnarg; pthread_create(&pthread, NULL, completion_thread, (void *)cgc); ret = cgsem_mswait(&cgc->cgsem, timeout); if (!ret) { pthread_join(pthread, NULL); free(cgc); } else pthread_cancel(pthread); return !ret; } void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line) { if (unlikely(n < 1 || n > (1ul << 31))) { applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d", n, file, func, line); return; } memcpy(dest, src, n); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2206_0
crossvul-cpp_data_bad_5733_9
/* * Copyright (c) 2011 Stefano Sabatini * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * filter for showing textual video frame information */ #include "libavutil/adler32.h" #include "libavutil/imgutils.h" #include "libavutil/internal.h" #include "libavutil/pixdesc.h" #include "libavutil/timestamp.h" #include "avfilter.h" #include "internal.h" #include "video.h" static int filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); uint32_t plane_checksum[4] = {0}, checksum = 0; int i, plane, vsub = desc->log2_chroma_h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane); uint8_t *data = frame->data[plane]; int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h; if (linesize < 0) return linesize; for (i = 0; i < h; i++) { plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize); checksum = av_adler32_update(checksum, data, linesize); data += frame->linesize[plane]; } } av_log(ctx, AV_LOG_INFO, "n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" " "fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c " "checksum:%08X plane_checksum:[%08X", inlink->frame_count, av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame), desc->name, frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den, frame->width, frame->height, !frame->interlaced_frame ? 'P' : /* Progressive */ frame->top_field_first ? 'T' : 'B', /* Top / Bottom */ frame->key_frame, av_get_picture_type_char(frame->pict_type), checksum, plane_checksum[0]); for (plane = 1; plane < 4 && frame->data[plane]; plane++) av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]); av_log(ctx, AV_LOG_INFO, "]\n"); return ff_filter_frame(inlink->dst->outputs[0], frame); } static const AVFilterPad avfilter_vf_showinfo_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .get_video_buffer = ff_null_get_video_buffer, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad avfilter_vf_showinfo_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO }, { NULL } }; AVFilter avfilter_vf_showinfo = { .name = "showinfo", .description = NULL_IF_CONFIG_SMALL("Show textual information for each video frame."), .inputs = avfilter_vf_showinfo_inputs, .outputs = avfilter_vf_showinfo_outputs, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_9
crossvul-cpp_data_bad_2197_1
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* lib/gssapi/krb5/k5unsealiov.c */ /* * Copyright 2008, 2009 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #include <assert.h> #include "k5-platform.h" /* for 64-bit support */ #include "k5-int.h" /* for zap() */ #include "gssapiP_krb5.h" #include <stdarg.h> static OM_uint32 kg_unseal_v1_iov(krb5_context context, OM_uint32 *minor_status, krb5_gss_ctx_id_rec *ctx, gss_iov_buffer_desc *iov, int iov_count, size_t token_wrapper_len, int *conf_state, gss_qop_t *qop_state, int toktype) { OM_uint32 code; gss_iov_buffer_t header; gss_iov_buffer_t trailer; unsigned char *ptr; int sealalg; int signalg; krb5_checksum cksum; krb5_checksum md5cksum; size_t cksum_len = 0; size_t conflen = 0; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; md5cksum.length = cksum.length = 0; md5cksum.contents = cksum.contents = NULL; header = kg_locate_header_iov(iov, iov_count, toktype); assert(header != NULL); trailer = kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); if (trailer != NULL && trailer->buffer.length != 0) { *minor_status = (OM_uint32)KRB5_BAD_MSIZE; return GSS_S_DEFECTIVE_TOKEN; } if (header->buffer.length < token_wrapper_len + 14) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } ptr = (unsigned char *)header->buffer.value + token_wrapper_len; signalg = ptr[0]; signalg |= ptr[1] << 8; sealalg = ptr[2]; sealalg |= ptr[3] << 8; if (ptr[4] != 0xFF || ptr[5] != 0xFF) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if (toktype != KG_TOK_WRAP_MSG && sealalg != 0xFFFF) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if (toktype == KG_TOK_WRAP_MSG && !(sealalg == 0xFFFF || sealalg == ctx->sealalg)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_WRAP_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ code = kg_get_seq_num(context, ctx->seq, ptr + 14, ptr + 6, &direction, &seqnum); if (code != 0) { *minor_status = code; return GSS_S_BAD_SIG; } /* decode the message, if SEAL */ if (toktype == KG_TOK_WRAP_MSG) { if (sealalg != 0xFFFF) { if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; size_t i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } assert(enc_key->length == 16); for (i = 0; i < enc_key->length; i++) ((char *)enc_key->contents)[i] ^= 0xF0; code = kg_arcfour_docrypt_iov(context, enc_key, 0, &bigend_seqnum[0], 4, iov, iov_count); krb5_free_keyblock(context, enc_key); } else { code = kg_decrypt_iov(context, 0, ((ctx->gss_flags & GSS_C_DCE_STYLE) != 0), 0 /*EC*/, 0 /*RRC*/, ctx->enc, KG_USAGE_SEAL, NULL, iov, iov_count); } if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } } conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); } if (header->buffer.length != token_wrapper_len + 14 + cksum_len + conflen) { retval = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } /* compute the checksum of the message */ /* initialize the checksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort(); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } md5cksum.length = sumlen; /* compute the checksum of the message */ code = kg_make_checksum_iov_v1(context, md5cksum.checksum_type, cksum_len, ctx->seq, ctx->enc, sign_usage, iov, iov_count, toktype, &md5cksum); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code != 0) { retval = GSS_S_FAILURE; goto cleanup; } cksum.length = cksum_len; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; default: code = 0; retval = GSS_S_DEFECTIVE_TOKEN; goto cleanup; break; } if (code != 0) { code = 0; retval = GSS_S_BAD_SIG; goto cleanup; } /* * For GSS_C_DCE_STYLE, the caller manages the padding, because the * pad length is in the RPC PDU. The value of the padding may be * uninitialized. For normal GSS, the last bytes of the decrypted * data contain the pad length. kg_fixup_padding_iov() will find * this and fixup the last data IOV appropriately. */ if (toktype == KG_TOK_WRAP_MSG && (ctx->gss_flags & GSS_C_DCE_STYLE) == 0) { retval = kg_fixup_padding_iov(&code, iov, iov_count); if (retval != GSS_S_COMPLETE) goto cleanup; } if (conf_state != NULL) *conf_state = (sealalg != 0xFFFF); if (qop_state != NULL) *qop_state = GSS_C_QOP_DEFAULT; if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { *minor_status = (OM_uint32)G_BAD_DIRECTION; retval = GSS_S_BAD_SIG; } code = 0; retval = g_order_check(&ctx->seqstate, (gssint_uint64)seqnum); cleanup: krb5_free_checksum_contents(context, &md5cksum); *minor_status = code; return retval; } /* * Caller must provide TOKEN | DATA | PADDING | TRAILER, except * for DCE in which case it can just provide TOKEN | DATA (must * guarantee that DATA is padded) */ static OM_uint32 kg_unseal_iov_token(OM_uint32 *minor_status, krb5_gss_ctx_id_rec *ctx, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_error_code code; krb5_context context = ctx->k5_context; unsigned char *ptr; gss_iov_buffer_t header; gss_iov_buffer_t padding; gss_iov_buffer_t trailer; size_t input_length; unsigned int bodysize; int toktype2; header = kg_locate_header_iov(iov, iov_count, toktype); if (header == NULL) { *minor_status = EINVAL; return GSS_S_FAILURE; } padding = kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING); trailer = kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER); ptr = (unsigned char *)header->buffer.value; input_length = header->buffer.length; if ((ctx->gss_flags & GSS_C_DCE_STYLE) == 0 && toktype == KG_TOK_WRAP_MSG) { size_t data_length, assoc_data_length; kg_iov_msglen(iov, iov_count, &data_length, &assoc_data_length); input_length += data_length - assoc_data_length; if (padding != NULL) input_length += padding->buffer.length; if (trailer != NULL) input_length += trailer->buffer.length; } code = g_verify_token_header(ctx->mech_used, &bodysize, &ptr, -1, input_length, 0); if (code != 0) { *minor_status = code; return GSS_S_DEFECTIVE_TOKEN; } if (bodysize < 2) { *minor_status = (OM_uint32)G_BAD_TOK_HEADER; return GSS_S_DEFECTIVE_TOKEN; } toktype2 = load_16_be(ptr); ptr += 2; bodysize -= 2; switch (toktype2) { case KG2_TOK_MIC_MSG: case KG2_TOK_WRAP_MSG: case KG2_TOK_DEL_CTX: code = gss_krb5int_unseal_v3_iov(context, minor_status, ctx, iov, iov_count, conf_state, qop_state, toktype); break; case KG_TOK_MIC_MSG: case KG_TOK_WRAP_MSG: case KG_TOK_DEL_CTX: code = kg_unseal_v1_iov(context, minor_status, ctx, iov, iov_count, (size_t)(ptr - (unsigned char *)header->buffer.value), conf_state, qop_state, toktype); break; default: *minor_status = (OM_uint32)G_BAD_TOK_HEADER; code = GSS_S_DEFECTIVE_TOKEN; break; } if (code != 0) save_error_info(*minor_status, context); return code; } /* * Split a STREAM | SIGN_DATA | DATA into * HEADER | SIGN_DATA | DATA | PADDING | TRAILER */ static OM_uint32 kg_unseal_stream_iov(OM_uint32 *minor_status, krb5_gss_ctx_id_rec *ctx, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { unsigned char *ptr; unsigned int bodysize; OM_uint32 code = 0, major_status = GSS_S_FAILURE; krb5_context context = ctx->k5_context; int conf_req_flag, toktype2; int i = 0, j; gss_iov_buffer_desc *tiov = NULL; gss_iov_buffer_t stream, data = NULL; gss_iov_buffer_t theader, tdata = NULL, tpadding, ttrailer; assert(toktype == KG_TOK_WRAP_MSG); if (toktype != KG_TOK_WRAP_MSG || (ctx->gss_flags & GSS_C_DCE_STYLE)) { code = EINVAL; goto cleanup; } stream = kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM); assert(stream != NULL); ptr = (unsigned char *)stream->buffer.value; code = g_verify_token_header(ctx->mech_used, &bodysize, &ptr, -1, stream->buffer.length, 0); if (code != 0) { major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } if (bodysize < 2) { *minor_status = (OM_uint32)G_BAD_TOK_HEADER; return GSS_S_DEFECTIVE_TOKEN; } toktype2 = load_16_be(ptr); ptr += 2; bodysize -= 2; tiov = (gss_iov_buffer_desc *)calloc((size_t)iov_count + 2, sizeof(gss_iov_buffer_desc)); if (tiov == NULL) { code = ENOMEM; goto cleanup; } /* HEADER */ theader = &tiov[i++]; theader->type = GSS_IOV_BUFFER_TYPE_HEADER; theader->buffer.value = stream->buffer.value; theader->buffer.length = ptr - (unsigned char *)stream->buffer.value; if (bodysize < 14 || stream->buffer.length != theader->buffer.length + bodysize) { major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } theader->buffer.length += 14; /* n[SIGN_DATA] | DATA | m[SIGN_DATA] */ for (j = 0; j < iov_count; j++) { OM_uint32 type = GSS_IOV_BUFFER_TYPE(iov[j].type); if (type == GSS_IOV_BUFFER_TYPE_DATA) { if (data != NULL) { /* only a single DATA buffer can appear */ code = EINVAL; goto cleanup; } data = &iov[j]; tdata = &tiov[i]; } if (type == GSS_IOV_BUFFER_TYPE_DATA || type == GSS_IOV_BUFFER_TYPE_SIGN_ONLY) tiov[i++] = iov[j]; } if (data == NULL) { /* a single DATA buffer must be present */ code = EINVAL; goto cleanup; } /* PADDING | TRAILER */ tpadding = &tiov[i++]; tpadding->type = GSS_IOV_BUFFER_TYPE_PADDING; tpadding->buffer.length = 0; tpadding->buffer.value = NULL; ttrailer = &tiov[i++]; ttrailer->type = GSS_IOV_BUFFER_TYPE_TRAILER; switch (toktype2) { case KG2_TOK_MIC_MSG: case KG2_TOK_WRAP_MSG: case KG2_TOK_DEL_CTX: { size_t ec, rrc; krb5_enctype enctype; unsigned int k5_headerlen = 0; unsigned int k5_trailerlen = 0; if (ctx->have_acceptor_subkey) enctype = ctx->acceptor_subkey->keyblock.enctype; else enctype = ctx->subkey->keyblock.enctype; conf_req_flag = ((ptr[0] & FLAG_WRAP_CONFIDENTIAL) != 0); ec = conf_req_flag ? load_16_be(ptr + 2) : 0; rrc = load_16_be(ptr + 4); if (rrc != 0) { if (!gss_krb5int_rotate_left((unsigned char *)stream->buffer.value + 16, stream->buffer.length - 16, rrc)) { code = ENOMEM; goto cleanup; } store_16_be(0, ptr + 4); /* set RRC to zero */ } if (conf_req_flag) { code = krb5_c_crypto_length(context, enctype, KRB5_CRYPTO_TYPE_HEADER, &k5_headerlen); if (code != 0) goto cleanup; theader->buffer.length += k5_headerlen; /* length validated later */ } /* no PADDING for CFX, EC is used instead */ code = krb5_c_crypto_length(context, enctype, conf_req_flag ? KRB5_CRYPTO_TYPE_TRAILER : KRB5_CRYPTO_TYPE_CHECKSUM, &k5_trailerlen); if (code != 0) goto cleanup; ttrailer->buffer.length = ec + (conf_req_flag ? 16 : 0 /* E(Header) */) + k5_trailerlen; ttrailer->buffer.value = (unsigned char *)stream->buffer.value + stream->buffer.length - ttrailer->buffer.length; break; } case KG_TOK_MIC_MSG: case KG_TOK_WRAP_MSG: case KG_TOK_DEL_CTX: theader->buffer.length += ctx->cksum_size + kg_confounder_size(context, ctx->enc->keyblock.enctype); /* * we can't set the padding accurately until decryption; * kg_fixup_padding_iov() will take care of this */ tpadding->buffer.length = 1; tpadding->buffer.value = (unsigned char *)stream->buffer.value + stream->buffer.length - 1; /* no TRAILER for pre-CFX */ ttrailer->buffer.length = 0; ttrailer->buffer.value = NULL; break; default: code = (OM_uint32)G_BAD_TOK_HEADER; major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; break; } /* IOV: -----------0-------------+---1---+--2--+----------------3--------------*/ /* Old: GSS-Header | Conf | Data | Pad | */ /* CFX: GSS-Header | Kerb-Header | Data | | EC | E(Header) | Kerb-Trailer */ /* GSS: -------GSS-HEADER--------+-DATA--+-PAD-+----------GSS-TRAILER----------*/ /* validate lengths */ if (stream->buffer.length < theader->buffer.length + tpadding->buffer.length + ttrailer->buffer.length) { code = (OM_uint32)KRB5_BAD_MSIZE; major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } /* setup data */ tdata->buffer.length = stream->buffer.length - ttrailer->buffer.length - tpadding->buffer.length - theader->buffer.length; assert(data != NULL); if (data->type & GSS_IOV_BUFFER_FLAG_ALLOCATE) { code = kg_allocate_iov(tdata, tdata->buffer.length); if (code != 0) goto cleanup; memcpy(tdata->buffer.value, (unsigned char *)stream->buffer.value + theader->buffer.length, tdata->buffer.length); } else tdata->buffer.value = (unsigned char *)stream->buffer.value + theader->buffer.length; assert(i <= iov_count + 2); major_status = kg_unseal_iov_token(&code, ctx, conf_state, qop_state, tiov, i, toktype); if (major_status == GSS_S_COMPLETE) *data = *tdata; else kg_release_iov(tdata, 1); cleanup: if (tiov != NULL) free(tiov); *minor_status = code; return major_status; } OM_uint32 kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (!ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; } OM_uint32 KRB5_CALLCONV krb5_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 major_status; major_status = kg_unseal_iov(minor_status, context_handle, conf_state, qop_state, iov, iov_count, KG_TOK_WRAP_MSG); return major_status; } OM_uint32 KRB5_CALLCONV krb5_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 major_status; major_status = kg_unseal_iov(minor_status, context_handle, NULL, qop_state, iov, iov_count, KG_TOK_MIC_MSG); return major_status; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2197_1
crossvul-cpp_data_bad_5813_0
/* * Quicktime Video (RPZA) Video Decoder * Copyright (C) 2003 the ffmpeg project * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * QT RPZA Video Decoder by Roberto Togni * For more information about the RPZA format, visit: * http://www.pcisys.net/~melanson/codecs/ * * The RPZA decoder outputs RGB555 colorspace data. * * Note that this decoder reads big endian RGB555 pixel values from the * bytestream, arranges them in the host's endian order, and outputs * them to the final rendered map in the same host endian order. This is * intended behavior as the libavcodec documentation states that RGB555 * pixels shall be stored in native CPU endianness. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "avcodec.h" #include "internal.h" typedef struct RpzaContext { AVCodecContext *avctx; AVFrame frame; const unsigned char *buf; int size; } RpzaContext; #define ADVANCE_BLOCK() \ { \ pixel_ptr += 4; \ if (pixel_ptr >= width) \ { \ pixel_ptr = 0; \ row_ptr += stride * 4; \ } \ total_blocks--; \ if (total_blocks < 0) \ { \ av_log(s->avctx, AV_LOG_ERROR, "warning: block counter just went negative (this should not happen)\n"); \ return; \ } \ } static void rpza_decode_stream(RpzaContext *s) { int width = s->avctx->width; int stride = s->frame.linesize[0] / 2; int row_inc = stride - 4; int stream_ptr = 0; int chunk_size; unsigned char opcode; int n_blocks; unsigned short colorA = 0, colorB; unsigned short color4[4]; unsigned char index, idx; unsigned short ta, tb; unsigned short *pixels = (unsigned short *)s->frame.data[0]; int row_ptr = 0; int pixel_ptr = 0; int block_ptr; int pixel_x, pixel_y; int total_blocks; /* First byte is always 0xe1. Warn if it's different */ if (s->buf[stream_ptr] != 0xe1) av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n", s->buf[stream_ptr]); /* Get chunk size, ingnoring first byte */ chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF; stream_ptr += 4; /* If length mismatch use size from MOV file and try to decode anyway */ if (chunk_size != s->size) av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n"); chunk_size = s->size; /* Number of 4x4 blocks in frame. */ total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4); /* Process chunk data */ while (stream_ptr < chunk_size) { opcode = s->buf[stream_ptr++]; /* Get opcode */ n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */ /* If opcode MSbit is 0, we need more data to decide what to do */ if ((opcode & 0x80) == 0) { colorA = (opcode << 8) | (s->buf[stream_ptr++]); opcode = 0; if ((s->buf[stream_ptr] & 0x80) != 0) { /* Must behave as opcode 110xxxxx, using colorA computed * above. Use fake opcode 0x20 to enter switch block at * the right place */ opcode = 0x20; n_blocks = 1; } } switch (opcode & 0xe0) { /* Skip blocks */ case 0x80: while (n_blocks--) { ADVANCE_BLOCK(); } break; /* Fill blocks with one color */ case 0xa0: colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; while (n_blocks--) { block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); } break; /* Fill blocks with 4 colors */ case 0xc0: colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; case 0x20: colorB = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; /* sort out the colors */ color4[0] = colorB; color4[1] = 0; color4[2] = 0; color4[3] = colorA; /* red components */ ta = (colorA >> 10) & 0x1F; tb = (colorB >> 10) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10; /* green components */ ta = (colorA >> 5) & 0x1F; tb = (colorB >> 5) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5; /* blue components */ ta = colorA & 0x1F; tb = colorB & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5); color4[2] |= ((21 * ta + 11 * tb) >> 5); if (s->size - stream_ptr < n_blocks * 4) return; while (n_blocks--) { block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { index = s->buf[stream_ptr++]; for (pixel_x = 0; pixel_x < 4; pixel_x++){ idx = (index >> (2 * (3 - pixel_x))) & 0x03; pixels[block_ptr] = color4[idx]; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); } break; /* Fill block with 16 colors */ case 0x00: if (s->size - stream_ptr < 16) return; block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ /* We already have color of upper left pixel */ if ((pixel_y != 0) || (pixel_x !=0)) { colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; } pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); break; /* Unknown opcode */ default: av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk." " Skip remaining %d bytes of chunk data.\n", opcode, chunk_size - stream_ptr); return; } /* Opcode switch */ } } static av_cold int rpza_decode_init(AVCodecContext *avctx) { RpzaContext *s = avctx->priv_data; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_RGB555; avcodec_get_frame_defaults(&s->frame); return 0; } static int rpza_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; RpzaContext *s = avctx->priv_data; int ret; s->buf = buf; s->size = buf_size; if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0) return ret; rpza_decode_stream(s); if ((ret = av_frame_ref(data, &s->frame)) < 0) return ret; *got_frame = 1; /* always report that the buffer was completely consumed */ return buf_size; } static av_cold int rpza_decode_end(AVCodecContext *avctx) { RpzaContext *s = avctx->priv_data; av_frame_unref(&s->frame); return 0; } AVCodec ff_rpza_decoder = { .name = "rpza", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_RPZA, .priv_data_size = sizeof(RpzaContext), .init = rpza_decode_init, .close = rpza_decode_end, .decode = rpza_decode_frame, .capabilities = CODEC_CAP_DR1, .long_name = NULL_IF_CONFIG_SMALL("QuickTime video (RPZA)"), };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5813_0
crossvul-cpp_data_bad_943_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % GGGG IIIII FFFFF % % G I F % % G GG I FFF % % G G I F % % GGG IIIII F % % % % % % Read/Write Compuserv Graphics Interchange Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/profile.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" /* Define declarations. */ #define MaximumLZWBits 12 #define MaximumLZWCode (1UL << MaximumLZWBits) /* Typdef declarations. */ typedef struct _LZWCodeInfo { unsigned char buffer[280]; size_t count, bit; MagickBooleanType eof; } LZWCodeInfo; typedef struct _LZWStack { size_t *codes, *index, *top; } LZWStack; typedef struct _LZWInfo { Image *image; LZWStack *stack; MagickBooleanType genesis; size_t data_size, maximum_data_value, clear_code, end_code, bits, first_code, last_code, maximum_code, slot, *table[2]; LZWCodeInfo code_info; } LZWInfo; /* Forward declarations. */ static inline int GetNextLZWCode(LZWInfo *,const size_t); static MagickBooleanType WriteGIFImage(const ImageInfo *,Image *); static ssize_t ReadBlobBlock(Image *,unsigned char *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage uncompresses an image via GIF-coding. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image,const ssize_t opacity) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o opacity: The colormap index associated with the transparent color. % */ static LZWInfo *RelinquishLZWInfo(LZWInfo *lzw_info) { if (lzw_info->table[0] != (size_t *) NULL) lzw_info->table[0]=(size_t *) RelinquishMagickMemory( lzw_info->table[0]); if (lzw_info->table[1] != (size_t *) NULL) lzw_info->table[1]=(size_t *) RelinquishMagickMemory( lzw_info->table[1]); if (lzw_info->stack != (LZWStack *) NULL) { if (lzw_info->stack->codes != (size_t *) NULL) lzw_info->stack->codes=(size_t *) RelinquishMagickMemory( lzw_info->stack->codes); lzw_info->stack=(LZWStack *) RelinquishMagickMemory(lzw_info->stack); } lzw_info=(LZWInfo *) RelinquishMagickMemory(lzw_info); return((LZWInfo *) NULL); } static inline void ResetLZWInfo(LZWInfo *lzw_info) { size_t one; lzw_info->bits=lzw_info->data_size+1; one=1; lzw_info->maximum_code=one << lzw_info->bits; lzw_info->slot=lzw_info->maximum_data_value+3; lzw_info->genesis=MagickTrue; } static LZWInfo *AcquireLZWInfo(Image *image,const size_t data_size) { LZWInfo *lzw_info; register ssize_t i; size_t one; lzw_info=(LZWInfo *) AcquireMagickMemory(sizeof(*lzw_info)); if (lzw_info == (LZWInfo *) NULL) return((LZWInfo *) NULL); (void) memset(lzw_info,0,sizeof(*lzw_info)); lzw_info->image=image; lzw_info->data_size=data_size; one=1; lzw_info->maximum_data_value=(one << data_size)-1; lzw_info->clear_code=lzw_info->maximum_data_value+1; lzw_info->end_code=lzw_info->maximum_data_value+2; lzw_info->table[0]=(size_t *) AcquireQuantumMemory(MaximumLZWCode, sizeof(**lzw_info->table)); lzw_info->table[1]=(size_t *) AcquireQuantumMemory(MaximumLZWCode, sizeof(**lzw_info->table)); if ((lzw_info->table[0] == (size_t *) NULL) || (lzw_info->table[1] == (size_t *) NULL)) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } (void) memset(lzw_info->table[0],0,MaximumLZWCode* sizeof(**lzw_info->table)); (void) memset(lzw_info->table[1],0,MaximumLZWCode* sizeof(**lzw_info->table)); for (i=0; i <= (ssize_t) lzw_info->maximum_data_value; i++) { lzw_info->table[0][i]=0; lzw_info->table[1][i]=(size_t) i; } ResetLZWInfo(lzw_info); lzw_info->code_info.buffer[0]='\0'; lzw_info->code_info.buffer[1]='\0'; lzw_info->code_info.count=2; lzw_info->code_info.bit=8*lzw_info->code_info.count; lzw_info->code_info.eof=MagickFalse; lzw_info->genesis=MagickTrue; lzw_info->stack=(LZWStack *) AcquireMagickMemory(sizeof(*lzw_info->stack)); if (lzw_info->stack == (LZWStack *) NULL) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } lzw_info->stack->codes=(size_t *) AcquireQuantumMemory(2UL* MaximumLZWCode,sizeof(*lzw_info->stack->codes)); if (lzw_info->stack->codes == (size_t *) NULL) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } lzw_info->stack->index=lzw_info->stack->codes; lzw_info->stack->top=lzw_info->stack->codes+2*MaximumLZWCode; return(lzw_info); } static inline int GetNextLZWCode(LZWInfo *lzw_info,const size_t bits) { int code; register ssize_t i; size_t one; while (((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) && (lzw_info->code_info.eof == MagickFalse)) { ssize_t count; lzw_info->code_info.buffer[0]=lzw_info->code_info.buffer[ lzw_info->code_info.count-2]; lzw_info->code_info.buffer[1]=lzw_info->code_info.buffer[ lzw_info->code_info.count-1]; lzw_info->code_info.bit-=8*(lzw_info->code_info.count-2); lzw_info->code_info.count=2; count=ReadBlobBlock(lzw_info->image,&lzw_info->code_info.buffer[ lzw_info->code_info.count]); if (count > 0) lzw_info->code_info.count+=count; else lzw_info->code_info.eof=MagickTrue; } if ((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) return(-1); code=0; one=1; for (i=0; i < (ssize_t) bits; i++) { code|=((lzw_info->code_info.buffer[lzw_info->code_info.bit/8] & (one << (lzw_info->code_info.bit % 8))) != 0) << i; lzw_info->code_info.bit++; } return(code); } static inline int PopLZWStack(LZWStack *stack_info) { if (stack_info->index <= stack_info->codes) return(-1); stack_info->index--; return((int) *stack_info->index); } static inline void PushLZWStack(LZWStack *stack_info,const size_t value) { if (stack_info->index >= stack_info->top) return; *stack_info->index=value; stack_info->index++; } static int ReadBlobLZWByte(LZWInfo *lzw_info) { int code; size_t one, value; ssize_t count; if (lzw_info->stack->index != lzw_info->stack->codes) return(PopLZWStack(lzw_info->stack)); if (lzw_info->genesis != MagickFalse) { lzw_info->genesis=MagickFalse; do { lzw_info->first_code=(size_t) GetNextLZWCode(lzw_info,lzw_info->bits); lzw_info->last_code=lzw_info->first_code; } while (lzw_info->first_code == lzw_info->clear_code); return((int) lzw_info->first_code); } code=GetNextLZWCode(lzw_info,lzw_info->bits); if (code < 0) return(code); if ((size_t) code == lzw_info->clear_code) { ResetLZWInfo(lzw_info); return(ReadBlobLZWByte(lzw_info)); } if ((size_t) code == lzw_info->end_code) return(-1); if ((size_t) code < lzw_info->slot) value=(size_t) code; else { PushLZWStack(lzw_info->stack,lzw_info->first_code); value=lzw_info->last_code; } count=0; while (value > lzw_info->maximum_data_value) { if ((size_t) count > MaximumLZWCode) return(-1); count++; if ((size_t) value > MaximumLZWCode) return(-1); PushLZWStack(lzw_info->stack,lzw_info->table[1][value]); value=lzw_info->table[0][value]; } lzw_info->first_code=lzw_info->table[1][value]; PushLZWStack(lzw_info->stack,lzw_info->first_code); one=1; if (lzw_info->slot < MaximumLZWCode) { lzw_info->table[0][lzw_info->slot]=lzw_info->last_code; lzw_info->table[1][lzw_info->slot]=lzw_info->first_code; lzw_info->slot++; if ((lzw_info->slot >= lzw_info->maximum_code) && (lzw_info->bits < MaximumLZWBits)) { lzw_info->bits++; lzw_info->maximum_code=one << lzw_info->bits; } } lzw_info->last_code=(size_t) code; return(PopLZWStack(lzw_info->stack)); } static MagickBooleanType DecodeImage(Image *image,const ssize_t opacity) { ExceptionInfo *exception; IndexPacket index; int c; LZWInfo *lzw_info; ssize_t offset, y; unsigned char data_size; size_t pass; /* Allocate decoder tables. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=(&image->exception); data_size=(unsigned char) ReadBlobByte(image); if (data_size > MaximumLZWBits) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); lzw_info=AcquireLZWInfo(image,data_size); if (lzw_info == (LZWInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pass=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { c=ReadBlobLZWByte(lzw_info); if (c < 0) break; index=ConstrainColormapIndex(image,(ssize_t) c); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); SetPixelOpacity(q,(ssize_t) index == opacity ? TransparentOpacity : OpaqueOpacity); x++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (x < (ssize_t) image->columns) break; if (image->interlace == NoInterlace) offset++; else { switch (pass) { case 0: default: { offset+=8; break; } case 1: { offset+=8; break; } case 2: { offset+=4; break; } case 3: { offset+=2; break; } } if ((pass == 0) && (offset >= (ssize_t) image->rows)) { pass++; offset=4; } if ((pass == 1) && (offset >= (ssize_t) image->rows)) { pass++; offset=2; } if ((pass == 2) && (offset >= (ssize_t) image->rows)) { pass++; offset=1; } } } lzw_info=RelinquishLZWInfo(lzw_info); if (y < (ssize_t) image->rows) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via GIF-coding. % % The format of the EncodeImage method is: % % MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image, % const size_t data_size) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the address of a structure of type Image. % % o data_size: The number of bits in the compressed packet. % */ static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image, const size_t data_size) { #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); \ } \ } IndexPacket 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 IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,offset,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); if (y == 0) { waiting_code=(short) (*indexes); p++; } for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++) { /* Probe hash table. */ index=(IndexPacket) ((size_t) GetPixelIndex(indexes+x) & 0xff); p++; 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); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s G I F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsGIF() returns MagickTrue if the image format type, identified by the % magick string, is GIF. % % The format of the IsGIF method is: % % MagickBooleanType IsGIF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsGIF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"GIF8",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d B l o b B l o c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadBlobBlock() reads data from the image file and returns it. The % amount of data is determined by first reading a count byte. The number % of bytes read is returned. % % The format of the ReadBlobBlock method is: % % ssize_t ReadBlobBlock(Image *image,unsigned char *data) % % A description of each parameter follows: % % o image: the image. % % o data: Specifies an area to place the information requested from % the file. % */ static ssize_t ReadBlobBlock(Image *image,unsigned char *data) { ssize_t count; unsigned char block_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(data != (unsigned char *) NULL); count=ReadBlob(image,1,&block_count); if (count != 1) return(0); count=ReadBlob(image,(size_t) block_count,data); if (count != (ssize_t) block_count) return(0); return(count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGIFImage() reads a Compuserve Graphics image file and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGIFImage method is: % % Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static void *DestroyGIFProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static MagickBooleanType PingGIFImage(Image *image) { unsigned char buffer[256], length, data_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (ReadBlob(image,1,&data_size) != 1) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); if (data_size > MaximumLZWBits) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); while (length != 0) { if (ReadBlob(image,length,buffer) != (ssize_t) length) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryImageException(CorruptImageError,"CorruptImage", image->filename); } return(MagickTrue); } static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BitSet(byte,bit) (((byte) & (bit)) == (bit)) #define LSBFirstOrder(x,y) (((y) << 8) | (x)) #define ThrowGIFException(exception,message) \ { \ if (profiles != (LinkedListInfo *) NULL) \ profiles=DestroyLinkedList(profiles,DestroyGIFProfile); \ if (global_colormap != (unsigned char *) NULL) \ global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); \ if (meta_image != (Image *) NULL) \ meta_image=DestroyImage(meta_image); \ ThrowReaderException((exception),(message)); \ } Image *image, *meta_image; LinkedListInfo *profiles; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t duration, global_colors, image_count, local_colors, one; ssize_t count, opacity; unsigned char background, buffer[257], c, flag, *global_colormap, magick[12]; /* 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 GIF file. */ count=ReadBlob(image,6,magick); if ((count != 6) || ((LocaleNCompare((char *) magick,"GIF87",5) != 0) && (LocaleNCompare((char *) magick,"GIF89",5) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) memset(buffer,0,sizeof(buffer)); meta_image=AcquireImage(image_info); /* metadata container */ meta_image->page.width=ReadBlobLSBShort(image); meta_image->page.height=ReadBlobLSBShort(image); meta_image->iterations=1; flag=(unsigned char) ReadBlobByte(image); background=(unsigned char) ReadBlobByte(image); c=(unsigned char) ReadBlobByte(image); /* reserved */ profiles=(LinkedListInfo *) NULL; one=1; global_colors=one << (((size_t) flag & 0x07)+1); global_colormap=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(global_colors,256),3UL*sizeof(*global_colormap)); if (global_colormap == (unsigned char *) NULL) ThrowGIFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(global_colormap,0,3*MagickMax(global_colors,256)* sizeof(*global_colormap)); if (BitSet((int) flag,0x80) != 0) { count=ReadBlob(image,(size_t) (3*global_colors),global_colormap); if (count != (ssize_t) (3*global_colors)) ThrowGIFException(CorruptImageError,"InsufficientImageDataInFile"); } duration=0; opacity=(-1); image_count=0; for ( ; ; ) { count=ReadBlob(image,1,&c); if (count != 1) break; if (c == (unsigned char) ';') break; /* terminator */ if (c == (unsigned char) '!') { /* GIF Extension block. */ count=ReadBlob(image,1,&c); if (count != 1) ThrowGIFException(CorruptImageError,"UnableToReadExtensionBlock"); (void) memset(buffer,0,sizeof(buffer)); switch (c) { case 0xf9: { /* Read graphics control extension. */ while (ReadBlobBlock(image,buffer) != 0) ; meta_image->dispose=(DisposeType) ((buffer[0] >> 2) & 0x07); meta_image->delay=((size_t) buffer[2] << 8) | buffer[1]; if ((ssize_t) (buffer[0] & 0x01) == 0x01) opacity=(ssize_t) buffer[3]; break; } case 0xfe: { char *comments; size_t extent, offset; comments=AcquireString((char *) NULL); extent=MagickPathExtent; for (offset=0; ; offset+=count) { count=ReadBlobBlock(image,buffer); if (count == 0) break; buffer[count]='\0'; if (((ssize_t) (count+offset+MagickPathExtent)) >= (ssize_t) extent) { extent<<=1; comments=(char *) ResizeQuantumMemory(comments,extent+ MagickPathExtent,sizeof(*comments)); if (comments == (char *) NULL) ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); } (void) CopyMagickString(&comments[offset],(char *) buffer,extent- offset); } (void) SetImageProperty(meta_image,"comment",comments); comments=DestroyString(comments); break; } case 0xff: { MagickBooleanType loop; /* Read Netscape Loop extension. */ loop=MagickFalse; if (ReadBlobBlock(image,buffer) != 0) loop=LocaleNCompare((char *) buffer,"NETSCAPE2.0",11) == 0 ? MagickTrue : MagickFalse; if (loop != MagickFalse) while (ReadBlobBlock(image,buffer) != 0) { meta_image->iterations=((size_t) buffer[2] << 8) | buffer[1]; if (meta_image->iterations != 0) meta_image->iterations++; } else { char name[MaxTextExtent]; int block_length, info_length, reserved_length; MagickBooleanType i8bim, icc, iptc, magick; StringInfo *profile; unsigned char *info; /* Store GIF application extension as a generic profile. */ icc=LocaleNCompare((char *) buffer,"ICCRGBG1012",11) == 0 ? MagickTrue : MagickFalse; magick=LocaleNCompare((char *) buffer,"ImageMagick",11) == 0 ? MagickTrue : MagickFalse; i8bim=LocaleNCompare((char *) buffer,"MGK8BIM0000",11) == 0 ? MagickTrue : MagickFalse; iptc=LocaleNCompare((char *) buffer,"MGKIPTC0000",11) == 0 ? MagickTrue : MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading GIF application extension"); info=(unsigned char *) AcquireQuantumMemory(255UL, sizeof(*info)); if (info == (unsigned char *) NULL) ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); (void) memset(info,0,255UL*sizeof(*info)); reserved_length=255; for (info_length=0; ; ) { block_length=(int) ReadBlobBlock(image,&info[info_length]); if (block_length == 0) break; info_length+=block_length; if (info_length > (reserved_length-255)) { reserved_length+=4096; info=(unsigned char *) ResizeQuantumMemory(info,(size_t) reserved_length,sizeof(*info)); if (info == (unsigned char *) NULL) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); } } } profile=BlobToStringInfo(info,(size_t) info_length); if (profile == (StringInfo *) NULL) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowGIFException(ResourceLimitError, "MemoryAllocationFailed"); } if (i8bim != MagickFalse) (void) CopyMagickString(name,"8bim",sizeof(name)); else if (icc != MagickFalse) (void) CopyMagickString(name,"icc",sizeof(name)); else if (iptc != MagickFalse) (void) CopyMagickString(name,"iptc",sizeof(name)); else if (magick != MagickFalse) { (void) CopyMagickString(name,"magick",sizeof(name)); meta_image->gamma=StringToDouble((char *) info+6, (char **) NULL); } else (void) FormatLocaleString(name,sizeof(name),"gif:%.11s", buffer); info=(unsigned char *) RelinquishMagickMemory(info); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " profile name=%s",name); if (magick != MagickFalse) profile=DestroyStringInfo(profile); else { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); SetStringInfoName(profile,name); (void) AppendValueToLinkedList(profiles,profile); } } break; } default: { while (ReadBlobBlock(image,buffer) != 0) ; break; } } } if (c != (unsigned char) ',') continue; if (image_count != 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); } image_count++; /* Read image attributes. */ meta_image->page.x=(ssize_t) ReadBlobLSBShort(image); meta_image->page.y=(ssize_t) ReadBlobLSBShort(image); meta_image->scene=image->scene; (void) CloneImageProperties(image,meta_image); DestroyImageProperties(meta_image); image->storage_class=PseudoClass; image->compression=LZWCompression; image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); image->depth=8; flag=(unsigned char) ReadBlobByte(image); image->interlace=BitSet((int) flag,0x40) != 0 ? GIFInterlace : NoInterlace; local_colors=BitSet((int) flag,0x80) == 0 ? global_colors : one << ((size_t) (flag & 0x07)+1); image->colors=local_colors; if (opacity >= (ssize_t) image->colors) { image->colors++; opacity=(-1); } image->ticks_per_second=100; image->matte=opacity >= 0 ? MagickTrue : MagickFalse; if ((image->columns == 0) || (image->rows == 0)) ThrowGIFException(CorruptImageError,"NegativeOrZeroImageSize"); /* Inititialize colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowGIFException(ResourceLimitError,"MemoryAllocationFailed"); if (BitSet((int) flag,0x80) == 0) { /* Use global colormap. */ p=global_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++); if (i == opacity) { image->colormap[i].opacity=(Quantum) TransparentOpacity; image->transparent_color=image->colormap[opacity]; } } image->background_color=image->colormap[MagickMin((ssize_t) background, (ssize_t) image->colors-1)]; } else { unsigned char *colormap; /* Read local colormap. */ colormap=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(local_colors,256),3UL*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowGIFException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(colormap,0,3*MagickMax(local_colors,256)* sizeof(*colormap)); count=ReadBlob(image,(3*local_colors)*sizeof(*colormap),colormap); if (count != (ssize_t) (3*local_colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowGIFException(CorruptImageError,"InsufficientImageDataInFile"); } p=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++); if (i == opacity) image->colormap[i].opacity=(Quantum) TransparentOpacity; } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } if (image->gamma == 1.0) { for (i=0; i < (ssize_t) image->colors; i++) if (IsGrayPixel(image->colormap+i) == MagickFalse) break; (void) SetImageColorspace(image,i == (ssize_t) image->colors ? LinearGRAYColorspace : RGBColorspace); } 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) { if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,DestroyGIFProfile); global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Decode image. */ if (image_info->ping != MagickFalse) status=PingGIFImage(image); else status=DecodeImage(image,opacity); InheritException(exception,&image->exception); if ((image_info->ping == MagickFalse) && (status == MagickFalse)) ThrowGIFException(CorruptImageError,"CorruptImage"); if (profiles != (LinkedListInfo *) NULL) { StringInfo *profile; /* Set image profiles. */ ResetLinkedListIterator(profiles); profile=(StringInfo *) GetNextValueInLinkedList(profiles); while (profile != (StringInfo *) NULL) { (void) SetImageProfile(image,GetStringInfoName(profile),profile); profile=(StringInfo *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,DestroyGIFProfile); } duration+=image->delay*image->iterations; if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; opacity=(-1); status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) image->scene- 1,image->scene); if (status == MagickFalse) break; } image->duration=duration; if (profiles != (LinkedListInfo *) NULL) profiles=DestroyLinkedList(profiles,DestroyGIFProfile); meta_image=DestroyImage(meta_image); global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterGIFImage() adds properties for the GIF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterGIFImage method is: % % size_t RegisterGIFImage(void) % */ ModuleExport size_t RegisterGIFImage(void) { MagickInfo *entry; entry=SetMagickInfo("GIF"); entry->decoder=(DecodeImageHandler *) ReadGIFImage; entry->encoder=(EncodeImageHandler *) WriteGIFImage; entry->magick=(IsImageFormatHandler *) IsGIF; entry->description=ConstantString("CompuServe graphics interchange format"); entry->mime_type=ConstantString("image/gif"); entry->module=ConstantString("GIF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("GIF87"); entry->decoder=(DecodeImageHandler *) ReadGIFImage; entry->encoder=(EncodeImageHandler *) WriteGIFImage; entry->magick=(IsImageFormatHandler *) IsGIF; entry->adjoin=MagickFalse; entry->description=ConstantString("CompuServe graphics interchange format"); entry->version=ConstantString("version 87a"); entry->mime_type=ConstantString("image/gif"); entry->module=ConstantString("GIF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterGIFImage() removes format registrations made by the % GIF module from the list of supported formats. % % The format of the UnregisterGIFImage method is: % % UnregisterGIFImage(void) % */ ModuleExport void UnregisterGIFImage(void) { (void) UnregisterMagickInfo("GIF"); (void) UnregisterMagickInfo("GIF87"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGIFImage() writes an image to a file in the Compuserve Graphics % image format. % % The format of the WriteGIFImage method is: % % MagickBooleanType WriteGIFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGIFImage(const ImageInfo *image_info,Image *image) { int c; ImageInfo *write_info; MagickBooleanType status; MagickOffsetType scene; RectangleInfo page; register ssize_t i; register unsigned char *q; size_t bits_per_pixel, delay, imageListLength, length, one; ssize_t j, opacity; unsigned char *colormap, *global_colormap; /* 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); /* Allocate colormap. */ global_colormap=(unsigned char *) AcquireQuantumMemory(768UL, sizeof(*global_colormap)); colormap=(unsigned char *) AcquireQuantumMemory(768UL,sizeof(*colormap)); if ((global_colormap == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) { if (global_colormap != (unsigned char *) NULL) global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); if (colormap != (unsigned char *) NULL) colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < 768; i++) colormap[i]=(unsigned char) 0; /* Write GIF header. */ write_info=CloneImageInfo(image_info); if (LocaleCompare(write_info->magick,"GIF87") != 0) (void) WriteBlob(image,6,(unsigned char *) "GIF89a"); else { (void) WriteBlob(image,6,(unsigned char *) "GIF87a"); write_info->adjoin=MagickFalse; } /* Determine image bounding box. */ page.width=image->columns; if (image->page.width > page.width) page.width=image->page.width; page.height=image->rows; if (image->page.height > page.height) page.height=image->page.height; page.x=image->page.x; page.y=image->page.y; (void) WriteBlobLSBShort(image,(unsigned short) page.width); (void) WriteBlobLSBShort(image,(unsigned short) page.height); /* Write images to file. */ if ((write_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) write_info->interlace=NoInterlace; scene=0; one=1; imageListLength=GetImageListLength(image); do { (void) TransformImageColorspace(image,sRGBColorspace); opacity=(-1); if (IsOpaqueImage(image,&image->exception) != MagickFalse) { if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteType); } else { double alpha, beta; /* Identify transparent colormap index. */ if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteBilevelMatteType); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].opacity != OpaqueOpacity) { if (opacity < 0) { opacity=i; continue; } alpha=fabs((double) image->colormap[i].opacity- TransparentOpacity); beta=fabs((double) image->colormap[opacity].opacity- TransparentOpacity); if (alpha < beta) opacity=i; } if (opacity == -1) { (void) SetImageType(image,PaletteBilevelMatteType); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].opacity != OpaqueOpacity) { if (opacity < 0) { opacity=i; continue; } alpha=fabs((double) image->colormap[i].opacity- TransparentOpacity); beta=fabs((double) image->colormap[opacity].opacity- TransparentOpacity); if (alpha < beta) opacity=i; } } if (opacity >= 0) { image->colormap[opacity].red=image->transparent_color.red; image->colormap[opacity].green=image->transparent_color.green; image->colormap[opacity].blue=image->transparent_color.blue; } } if ((image->storage_class == DirectClass) || (image->colors > 256)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (bits_per_pixel=1; bits_per_pixel < 8; bits_per_pixel++) if ((one << bits_per_pixel) >= image->colors) break; q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { *q++=ScaleQuantumToChar(image->colormap[i].red); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].blue); } for ( ; i < (ssize_t) (one << bits_per_pixel); i++) { *q++=(unsigned char) 0x0; *q++=(unsigned char) 0x0; *q++=(unsigned char) 0x0; } if ((GetPreviousImageInList(image) == (Image *) NULL) || (write_info->adjoin == MagickFalse)) { /* Write global colormap. */ c=0x80; c|=(8-1) << 4; /* color resolution */ c|=(bits_per_pixel-1); /* size of global colormap */ (void) WriteBlobByte(image,(unsigned char) c); for (j=0; j < (ssize_t) image->colors; j++) if (IsColorEqual(&image->background_color,image->colormap+j)) break; (void) WriteBlobByte(image,(unsigned char) (j == (ssize_t) image->colors ? 0 : j)); /* background color */ (void) WriteBlobByte(image,(unsigned char) 0x00); /* reserved */ length=(size_t) (3*(one << bits_per_pixel)); (void) WriteBlob(image,length,colormap); for (j=0; j < 768; j++) global_colormap[j]=colormap[j]; } if (LocaleCompare(write_info->magick,"GIF87") != 0) { const char *value; /* Write graphics control extension. */ (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xf9); (void) WriteBlobByte(image,(unsigned char) 0x04); c=image->dispose << 2; if (opacity >= 0) c|=0x01; (void) WriteBlobByte(image,(unsigned char) c); delay=(size_t) (100*image->delay/MagickMax((size_t) image->ticks_per_second,1)); (void) WriteBlobLSBShort(image,(unsigned short) delay); (void) WriteBlobByte(image,(unsigned char) (opacity >= 0 ? opacity : 0)); (void) WriteBlobByte(image,(unsigned char) 0x00); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; size_t count; /* Write comment extension. */ (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xfe); for (p=value; *p != '\0'; ) { count=MagickMin(strlen(p),255); (void) WriteBlobByte(image,(unsigned char) count); for (i=0; i < (ssize_t) count; i++) (void) WriteBlobByte(image,(unsigned char) *p++); } (void) WriteBlobByte(image,(unsigned char) 0x00); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write Netscape Loop extension. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","NETSCAPE2.0"); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); (void) WriteBlob(image,11,(unsigned char *) "NETSCAPE2.0"); (void) WriteBlobByte(image,(unsigned char) 0x03); (void) WriteBlobByte(image,(unsigned char) 0x01); (void) WriteBlobLSBShort(image,(unsigned short) (image->iterations ? image->iterations-1 : 0)); (void) WriteBlobByte(image,(unsigned char) 0x00); } if ((image->gamma != 1.0f/2.2f)) { char attributes[MaxTextExtent]; ssize_t count; /* Write ImageMagick extension. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","ImageMagick"); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); (void) WriteBlob(image,11,(unsigned char *) "ImageMagick"); count=FormatLocaleString(attributes,MaxTextExtent,"gamma=%g", image->gamma); (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlob(image,(size_t) count,(unsigned char *) attributes); (void) WriteBlobByte(image,(unsigned char) 0x00); } ResetImageProfileIterator(image); for ( ; ; ) { char *name; const StringInfo *profile; name=GetNextImageProfile(image); if (name == (const char *) NULL) break; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0) || (LocaleCompare(name,"IPTC") == 0) || (LocaleCompare(name,"8BIM") == 0) || (LocaleNCompare(name,"gif:",4) == 0)) { size_t length; ssize_t offset; unsigned char *datum; datum=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { /* Write ICC extension. */ (void) WriteBlob(image,11,(unsigned char *) "ICCRGBG1012"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","ICCRGBG1012"); } else if ((LocaleCompare(name,"IPTC") == 0)) { /* Write IPTC extension. */ (void) WriteBlob(image,11,(unsigned char *) "MGKIPTC0000"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","MGKIPTC0000"); } else if ((LocaleCompare(name,"8BIM") == 0)) { /* Write 8BIM extension. */ (void) WriteBlob(image,11,(unsigned char *) "MGK8BIM0000"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","MGK8BIM0000"); } else { char extension[MaxTextExtent]; /* Write generic extension. */ (void) CopyMagickString(extension,name+4, sizeof(extension)); (void) WriteBlob(image,11,(unsigned char *) extension); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s",name); } offset=0; while ((ssize_t) length > offset) { size_t block_length; if ((length-offset) < 255) block_length=length-offset; else block_length=255; (void) WriteBlobByte(image,(unsigned char) block_length); (void) WriteBlob(image,(size_t) block_length,datum+offset); offset+=(ssize_t) block_length; } (void) WriteBlobByte(image,(unsigned char) 0x00); } } } } (void) WriteBlobByte(image,','); /* image separator */ /* Write the image header. */ page.x=image->page.x; page.y=image->page.y; if ((image->page.width != 0) && (image->page.height != 0)) page=image->page; (void) WriteBlobLSBShort(image,(unsigned short) (page.x < 0 ? 0 : page.x)); (void) WriteBlobLSBShort(image,(unsigned short) (page.y < 0 ? 0 : page.y)); (void) WriteBlobLSBShort(image,(unsigned short) image->columns); (void) WriteBlobLSBShort(image,(unsigned short) image->rows); c=0x00; if (write_info->interlace != NoInterlace) c|=0x40; /* pixel data is interlaced */ for (j=0; j < (ssize_t) (3*image->colors); j++) if (colormap[j] != global_colormap[j]) break; if (j == (ssize_t) (3*image->colors)) (void) WriteBlobByte(image,(unsigned char) c); else { c|=0x80; c|=(bits_per_pixel-1); /* size of local colormap */ (void) WriteBlobByte(image,(unsigned char) c); length=(size_t) (3*(one << bits_per_pixel)); (void) WriteBlob(image,length,colormap); } /* Write the image data. */ c=(int) MagickMax(bits_per_pixel,2); (void) WriteBlobByte(image,(unsigned char) c); status=EncodeImage(write_info,image,(size_t) MagickMax(bits_per_pixel,2)+1); if (status == MagickFalse) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); write_info=DestroyImageInfo(write_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobByte(image,(unsigned char) 0x00); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); scene++; status=SetImageProgress(image,SaveImagesTag,scene,imageListLength); if (status == MagickFalse) break; } while (write_info->adjoin != MagickFalse); (void) WriteBlobByte(image,';'); /* terminator */ global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); write_info=DestroyImageInfo(write_info); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_943_0
crossvul-cpp_data_bad_5174_0
/* * Copyright (c) 2001 Paul Stewart * Copyright (c) 2001 Vojtech Pavlik * * HID char devices, giving access to raw HID device events. * */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Should you need to contact me, the author, you can do so either by * e-mail - mail your message to Paul Stewart <stewart@wetlogic.net> */ #include <linux/poll.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/input.h> #include <linux/usb.h> #include <linux/hid.h> #include <linux/hiddev.h> #include <linux/compat.h> #include <linux/vmalloc.h> #include "usbhid.h" #ifdef CONFIG_USB_DYNAMIC_MINORS #define HIDDEV_MINOR_BASE 0 #define HIDDEV_MINORS 256 #else #define HIDDEV_MINOR_BASE 96 #define HIDDEV_MINORS 16 #endif #define HIDDEV_BUFFER_SIZE 2048 struct hiddev { int exist; int open; struct mutex existancelock; wait_queue_head_t wait; struct hid_device *hid; struct list_head list; spinlock_t list_lock; }; struct hiddev_list { struct hiddev_usage_ref buffer[HIDDEV_BUFFER_SIZE]; int head; int tail; unsigned flags; struct fasync_struct *fasync; struct hiddev *hiddev; struct list_head node; struct mutex thread_lock; }; /* * Find a report, given the report's type and ID. The ID can be specified * indirectly by REPORT_ID_FIRST (which returns the first report of the given * type) or by (REPORT_ID_NEXT | old_id), which returns the next report of the * given type which follows old_id. */ static struct hid_report * hiddev_lookup_report(struct hid_device *hid, struct hiddev_report_info *rinfo) { unsigned int flags = rinfo->report_id & ~HID_REPORT_ID_MASK; unsigned int rid = rinfo->report_id & HID_REPORT_ID_MASK; struct hid_report_enum *report_enum; struct hid_report *report; struct list_head *list; if (rinfo->report_type < HID_REPORT_TYPE_MIN || rinfo->report_type > HID_REPORT_TYPE_MAX) return NULL; report_enum = hid->report_enum + (rinfo->report_type - HID_REPORT_TYPE_MIN); switch (flags) { case 0: /* Nothing to do -- report_id is already set correctly */ break; case HID_REPORT_ID_FIRST: if (list_empty(&report_enum->report_list)) return NULL; list = report_enum->report_list.next; report = list_entry(list, struct hid_report, list); rinfo->report_id = report->id; break; case HID_REPORT_ID_NEXT: report = report_enum->report_id_hash[rid]; if (!report) return NULL; list = report->list.next; if (list == &report_enum->report_list) return NULL; report = list_entry(list, struct hid_report, list); rinfo->report_id = report->id; break; default: return NULL; } return report_enum->report_id_hash[rinfo->report_id]; } /* * Perform an exhaustive search of the report table for a usage, given its * type and usage id. */ static struct hid_field * hiddev_lookup_usage(struct hid_device *hid, struct hiddev_usage_ref *uref) { int i, j; struct hid_report *report; struct hid_report_enum *report_enum; struct hid_field *field; if (uref->report_type < HID_REPORT_TYPE_MIN || uref->report_type > HID_REPORT_TYPE_MAX) return NULL; report_enum = hid->report_enum + (uref->report_type - HID_REPORT_TYPE_MIN); list_for_each_entry(report, &report_enum->report_list, list) { for (i = 0; i < report->maxfield; i++) { field = report->field[i]; for (j = 0; j < field->maxusage; j++) { if (field->usage[j].hid == uref->usage_code) { uref->report_id = report->id; uref->field_index = i; uref->usage_index = j; return field; } } } } return NULL; } static void hiddev_send_event(struct hid_device *hid, struct hiddev_usage_ref *uref) { struct hiddev *hiddev = hid->hiddev; struct hiddev_list *list; unsigned long flags; spin_lock_irqsave(&hiddev->list_lock, flags); list_for_each_entry(list, &hiddev->list, node) { if (uref->field_index != HID_FIELD_INDEX_NONE || (list->flags & HIDDEV_FLAG_REPORT) != 0) { list->buffer[list->head] = *uref; list->head = (list->head + 1) & (HIDDEV_BUFFER_SIZE - 1); kill_fasync(&list->fasync, SIGIO, POLL_IN); } } spin_unlock_irqrestore(&hiddev->list_lock, flags); wake_up_interruptible(&hiddev->wait); } /* * This is where hid.c calls into hiddev to pass an event that occurred over * the interrupt pipe */ void hiddev_hid_event(struct hid_device *hid, struct hid_field *field, struct hid_usage *usage, __s32 value) { unsigned type = field->report_type; struct hiddev_usage_ref uref; uref.report_type = (type == HID_INPUT_REPORT) ? HID_REPORT_TYPE_INPUT : ((type == HID_OUTPUT_REPORT) ? HID_REPORT_TYPE_OUTPUT : ((type == HID_FEATURE_REPORT) ? HID_REPORT_TYPE_FEATURE : 0)); uref.report_id = field->report->id; uref.field_index = field->index; uref.usage_index = (usage - field->usage); uref.usage_code = usage->hid; uref.value = value; hiddev_send_event(hid, &uref); } EXPORT_SYMBOL_GPL(hiddev_hid_event); void hiddev_report_event(struct hid_device *hid, struct hid_report *report) { unsigned type = report->type; struct hiddev_usage_ref uref; memset(&uref, 0, sizeof(uref)); uref.report_type = (type == HID_INPUT_REPORT) ? HID_REPORT_TYPE_INPUT : ((type == HID_OUTPUT_REPORT) ? HID_REPORT_TYPE_OUTPUT : ((type == HID_FEATURE_REPORT) ? HID_REPORT_TYPE_FEATURE : 0)); uref.report_id = report->id; uref.field_index = HID_FIELD_INDEX_NONE; hiddev_send_event(hid, &uref); } /* * fasync file op */ static int hiddev_fasync(int fd, struct file *file, int on) { struct hiddev_list *list = file->private_data; return fasync_helper(fd, file, on, &list->fasync); } /* * release file op */ static int hiddev_release(struct inode * inode, struct file * file) { struct hiddev_list *list = file->private_data; unsigned long flags; spin_lock_irqsave(&list->hiddev->list_lock, flags); list_del(&list->node); spin_unlock_irqrestore(&list->hiddev->list_lock, flags); mutex_lock(&list->hiddev->existancelock); if (!--list->hiddev->open) { if (list->hiddev->exist) { usbhid_close(list->hiddev->hid); usbhid_put_power(list->hiddev->hid); } else { mutex_unlock(&list->hiddev->existancelock); kfree(list->hiddev); vfree(list); return 0; } } mutex_unlock(&list->hiddev->existancelock); vfree(list); return 0; } /* * open file op */ static int hiddev_open(struct inode *inode, struct file *file) { struct hiddev_list *list; struct usb_interface *intf; struct hid_device *hid; struct hiddev *hiddev; int res; intf = usbhid_find_interface(iminor(inode)); if (!intf) return -ENODEV; hid = usb_get_intfdata(intf); hiddev = hid->hiddev; if (!(list = vzalloc(sizeof(struct hiddev_list)))) return -ENOMEM; mutex_init(&list->thread_lock); list->hiddev = hiddev; file->private_data = list; /* * no need for locking because the USB major number * is shared which usbcore guards against disconnect */ if (list->hiddev->exist) { if (!list->hiddev->open++) { res = usbhid_open(hiddev->hid); if (res < 0) { res = -EIO; goto bail; } } } else { res = -ENODEV; goto bail; } spin_lock_irq(&list->hiddev->list_lock); list_add_tail(&list->node, &hiddev->list); spin_unlock_irq(&list->hiddev->list_lock); mutex_lock(&hiddev->existancelock); if (!list->hiddev->open++) if (list->hiddev->exist) { struct hid_device *hid = hiddev->hid; res = usbhid_get_power(hid); if (res < 0) { res = -EIO; goto bail_unlock; } usbhid_open(hid); } mutex_unlock(&hiddev->existancelock); return 0; bail_unlock: mutex_unlock(&hiddev->existancelock); bail: file->private_data = NULL; vfree(list); return res; } /* * "write" file op */ static ssize_t hiddev_write(struct file * file, const char __user * buffer, size_t count, loff_t *ppos) { return -EINVAL; } /* * "read" file op */ static ssize_t hiddev_read(struct file * file, char __user * buffer, size_t count, loff_t *ppos) { DEFINE_WAIT(wait); struct hiddev_list *list = file->private_data; int event_size; int retval; event_size = ((list->flags & HIDDEV_FLAG_UREF) != 0) ? sizeof(struct hiddev_usage_ref) : sizeof(struct hiddev_event); if (count < event_size) return 0; /* lock against other threads */ retval = mutex_lock_interruptible(&list->thread_lock); if (retval) return -ERESTARTSYS; while (retval == 0) { if (list->head == list->tail) { prepare_to_wait(&list->hiddev->wait, &wait, TASK_INTERRUPTIBLE); while (list->head == list->tail) { if (signal_pending(current)) { retval = -ERESTARTSYS; break; } if (!list->hiddev->exist) { retval = -EIO; break; } if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } /* let O_NONBLOCK tasks run */ mutex_unlock(&list->thread_lock); schedule(); if (mutex_lock_interruptible(&list->thread_lock)) { finish_wait(&list->hiddev->wait, &wait); return -EINTR; } set_current_state(TASK_INTERRUPTIBLE); } finish_wait(&list->hiddev->wait, &wait); } if (retval) { mutex_unlock(&list->thread_lock); return retval; } while (list->head != list->tail && retval + event_size <= count) { if ((list->flags & HIDDEV_FLAG_UREF) == 0) { if (list->buffer[list->tail].field_index != HID_FIELD_INDEX_NONE) { struct hiddev_event event; event.hid = list->buffer[list->tail].usage_code; event.value = list->buffer[list->tail].value; if (copy_to_user(buffer + retval, &event, sizeof(struct hiddev_event))) { mutex_unlock(&list->thread_lock); return -EFAULT; } retval += sizeof(struct hiddev_event); } } else { if (list->buffer[list->tail].field_index != HID_FIELD_INDEX_NONE || (list->flags & HIDDEV_FLAG_REPORT) != 0) { if (copy_to_user(buffer + retval, list->buffer + list->tail, sizeof(struct hiddev_usage_ref))) { mutex_unlock(&list->thread_lock); return -EFAULT; } retval += sizeof(struct hiddev_usage_ref); } } list->tail = (list->tail + 1) & (HIDDEV_BUFFER_SIZE - 1); } } mutex_unlock(&list->thread_lock); return retval; } /* * "poll" file op * No kernel lock - fine */ static unsigned int hiddev_poll(struct file *file, poll_table *wait) { struct hiddev_list *list = file->private_data; poll_wait(file, &list->hiddev->wait, wait); if (list->head != list->tail) return POLLIN | POLLRDNORM; if (!list->hiddev->exist) return POLLERR | POLLHUP; return 0; } /* * "ioctl" file op */ static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct hiddev_report_info rinfo; struct hiddev_usage_ref_multi *uref_multi = NULL; struct hiddev_usage_ref *uref; struct hid_report *report; struct hid_field *field; int i; uref_multi = kmalloc(sizeof(struct hiddev_usage_ref_multi), GFP_KERNEL); if (!uref_multi) return -ENOMEM; uref = &uref_multi->uref; if (cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) { if (copy_from_user(uref_multi, user_arg, sizeof(*uref_multi))) goto fault; } else { if (copy_from_user(uref, user_arg, sizeof(*uref))) goto fault; } switch (cmd) { case HIDIOCGUCODE: rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (uref->usage_index >= field->maxusage) goto inval; uref->usage_code = field->usage[uref->usage_index].hid; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; default: if (cmd != HIDIOCGUSAGE && cmd != HIDIOCGUSAGES && uref->report_type == HID_REPORT_TYPE_INPUT) goto inval; if (uref->report_id == HID_REPORT_ID_UNKNOWN) { field = hiddev_lookup_usage(hid, uref); if (field == NULL) goto inval; } else { rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (cmd == HIDIOCGCOLLECTIONINDEX) { if (uref->usage_index >= field->maxusage) goto inval; } else if (uref->usage_index >= field->report_count) goto inval; else if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) && (uref_multi->num_values > HID_MAX_MULTI_USAGES || uref->usage_index + uref_multi->num_values > field->report_count)) goto inval; } switch (cmd) { case HIDIOCGUSAGE: uref->value = field->value[uref->usage_index]; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; case HIDIOCSUSAGE: field->value[uref->usage_index] = uref->value; goto goodreturn; case HIDIOCGCOLLECTIONINDEX: i = field->usage[uref->usage_index].collection_index; kfree(uref_multi); return i; case HIDIOCGUSAGES: for (i = 0; i < uref_multi->num_values; i++) uref_multi->values[i] = field->value[uref->usage_index + i]; if (copy_to_user(user_arg, uref_multi, sizeof(*uref_multi))) goto fault; goto goodreturn; case HIDIOCSUSAGES: for (i = 0; i < uref_multi->num_values; i++) field->value[uref->usage_index + i] = uref_multi->values[i]; goto goodreturn; } goodreturn: kfree(uref_multi); return 0; fault: kfree(uref_multi); return -EFAULT; inval: kfree(uref_multi); return -EINVAL; } } static noinline int hiddev_ioctl_string(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct usb_device *dev = hid_to_usb_dev(hid); int idx, len; char *buf; if (get_user(idx, (int __user *)user_arg)) return -EFAULT; if ((buf = kmalloc(HID_STRING_SIZE, GFP_KERNEL)) == NULL) return -ENOMEM; if ((len = usb_string(dev, idx, buf, HID_STRING_SIZE-1)) < 0) { kfree(buf); return -EINVAL; } if (copy_to_user(user_arg+sizeof(int), buf, len+1)) { kfree(buf); return -EFAULT; } kfree(buf); return len; } static long hiddev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct hiddev_list *list = file->private_data; struct hiddev *hiddev = list->hiddev; struct hid_device *hid; struct hiddev_collection_info cinfo; struct hiddev_report_info rinfo; struct hiddev_field_info finfo; struct hiddev_devinfo dinfo; struct hid_report *report; struct hid_field *field; void __user *user_arg = (void __user *)arg; int i, r = -EINVAL; /* Called without BKL by compat methods so no BKL taken */ mutex_lock(&hiddev->existancelock); if (!hiddev->exist) { r = -ENODEV; goto ret_unlock; } hid = hiddev->hid; switch (cmd) { case HIDIOCGVERSION: r = put_user(HID_VERSION, (int __user *)arg) ? -EFAULT : 0; break; case HIDIOCAPPLICATION: if (arg >= hid->maxapplication) break; for (i = 0; i < hid->maxcollection; i++) if (hid->collection[i].type == HID_COLLECTION_APPLICATION && arg-- == 0) break; if (i < hid->maxcollection) r = hid->collection[i].usage; break; case HIDIOCGDEVINFO: { struct usb_device *dev = hid_to_usb_dev(hid); struct usbhid_device *usbhid = hid->driver_data; memset(&dinfo, 0, sizeof(dinfo)); dinfo.bustype = BUS_USB; dinfo.busnum = dev->bus->busnum; dinfo.devnum = dev->devnum; dinfo.ifnum = usbhid->ifnum; dinfo.vendor = le16_to_cpu(dev->descriptor.idVendor); dinfo.product = le16_to_cpu(dev->descriptor.idProduct); dinfo.version = le16_to_cpu(dev->descriptor.bcdDevice); dinfo.num_applications = hid->maxapplication; r = copy_to_user(user_arg, &dinfo, sizeof(dinfo)) ? -EFAULT : 0; break; } case HIDIOCGFLAG: r = put_user(list->flags, (int __user *)arg) ? -EFAULT : 0; break; case HIDIOCSFLAG: { int newflags; if (get_user(newflags, (int __user *)arg)) { r = -EFAULT; break; } if ((newflags & ~HIDDEV_FLAGS) != 0 || ((newflags & HIDDEV_FLAG_REPORT) != 0 && (newflags & HIDDEV_FLAG_UREF) == 0)) break; list->flags = newflags; r = 0; break; } case HIDIOCGSTRING: r = hiddev_ioctl_string(hiddev, cmd, user_arg); break; case HIDIOCINITREPORT: usbhid_init_reports(hid); r = 0; break; case HIDIOCGREPORT: if (copy_from_user(&rinfo, user_arg, sizeof(rinfo))) { r = -EFAULT; break; } if (rinfo.report_type == HID_REPORT_TYPE_OUTPUT) break; report = hiddev_lookup_report(hid, &rinfo); if (report == NULL) break; hid_hw_request(hid, report, HID_REQ_GET_REPORT); hid_hw_wait(hid); r = 0; break; case HIDIOCSREPORT: if (copy_from_user(&rinfo, user_arg, sizeof(rinfo))) { r = -EFAULT; break; } if (rinfo.report_type == HID_REPORT_TYPE_INPUT) break; report = hiddev_lookup_report(hid, &rinfo); if (report == NULL) break; hid_hw_request(hid, report, HID_REQ_SET_REPORT); hid_hw_wait(hid); r = 0; break; case HIDIOCGREPORTINFO: if (copy_from_user(&rinfo, user_arg, sizeof(rinfo))) { r = -EFAULT; break; } report = hiddev_lookup_report(hid, &rinfo); if (report == NULL) break; rinfo.num_fields = report->maxfield; r = copy_to_user(user_arg, &rinfo, sizeof(rinfo)) ? -EFAULT : 0; break; case HIDIOCGFIELDINFO: if (copy_from_user(&finfo, user_arg, sizeof(finfo))) { r = -EFAULT; break; } rinfo.report_type = finfo.report_type; rinfo.report_id = finfo.report_id; report = hiddev_lookup_report(hid, &rinfo); if (report == NULL) break; if (finfo.field_index >= report->maxfield) break; field = report->field[finfo.field_index]; memset(&finfo, 0, sizeof(finfo)); finfo.report_type = rinfo.report_type; finfo.report_id = rinfo.report_id; finfo.field_index = field->report_count - 1; finfo.maxusage = field->maxusage; finfo.flags = field->flags; finfo.physical = field->physical; finfo.logical = field->logical; finfo.application = field->application; finfo.logical_minimum = field->logical_minimum; finfo.logical_maximum = field->logical_maximum; finfo.physical_minimum = field->physical_minimum; finfo.physical_maximum = field->physical_maximum; finfo.unit_exponent = field->unit_exponent; finfo.unit = field->unit; r = copy_to_user(user_arg, &finfo, sizeof(finfo)) ? -EFAULT : 0; break; case HIDIOCGUCODE: /* fall through */ case HIDIOCGUSAGE: case HIDIOCSUSAGE: case HIDIOCGUSAGES: case HIDIOCSUSAGES: case HIDIOCGCOLLECTIONINDEX: r = hiddev_ioctl_usage(hiddev, cmd, user_arg); break; case HIDIOCGCOLLECTIONINFO: if (copy_from_user(&cinfo, user_arg, sizeof(cinfo))) { r = -EFAULT; break; } if (cinfo.index >= hid->maxcollection) break; cinfo.type = hid->collection[cinfo.index].type; cinfo.usage = hid->collection[cinfo.index].usage; cinfo.level = hid->collection[cinfo.index].level; r = copy_to_user(user_arg, &cinfo, sizeof(cinfo)) ? -EFAULT : 0; break; default: if (_IOC_TYPE(cmd) != 'H' || _IOC_DIR(cmd) != _IOC_READ) break; if (_IOC_NR(cmd) == _IOC_NR(HIDIOCGNAME(0))) { int len = strlen(hid->name) + 1; if (len > _IOC_SIZE(cmd)) len = _IOC_SIZE(cmd); r = copy_to_user(user_arg, hid->name, len) ? -EFAULT : len; break; } if (_IOC_NR(cmd) == _IOC_NR(HIDIOCGPHYS(0))) { int len = strlen(hid->phys) + 1; if (len > _IOC_SIZE(cmd)) len = _IOC_SIZE(cmd); r = copy_to_user(user_arg, hid->phys, len) ? -EFAULT : len; break; } } ret_unlock: mutex_unlock(&hiddev->existancelock); return r; } #ifdef CONFIG_COMPAT static long hiddev_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return hiddev_ioctl(file, cmd, (unsigned long)compat_ptr(arg)); } #endif static const struct file_operations hiddev_fops = { .owner = THIS_MODULE, .read = hiddev_read, .write = hiddev_write, .poll = hiddev_poll, .open = hiddev_open, .release = hiddev_release, .unlocked_ioctl = hiddev_ioctl, .fasync = hiddev_fasync, #ifdef CONFIG_COMPAT .compat_ioctl = hiddev_compat_ioctl, #endif .llseek = noop_llseek, }; static char *hiddev_devnode(struct device *dev, umode_t *mode) { return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev)); } static struct usb_class_driver hiddev_class = { .name = "hiddev%d", .devnode = hiddev_devnode, .fops = &hiddev_fops, .minor_base = HIDDEV_MINOR_BASE, }; /* * This is where hid.c calls us to connect a hid device to the hiddev driver */ int hiddev_connect(struct hid_device *hid, unsigned int force) { struct hiddev *hiddev; struct usbhid_device *usbhid = hid->driver_data; int retval; if (!force) { unsigned int i; for (i = 0; i < hid->maxcollection; i++) if (hid->collection[i].type == HID_COLLECTION_APPLICATION && !IS_INPUT_APPLICATION(hid->collection[i].usage)) break; if (i == hid->maxcollection) return -1; } if (!(hiddev = kzalloc(sizeof(struct hiddev), GFP_KERNEL))) return -1; init_waitqueue_head(&hiddev->wait); INIT_LIST_HEAD(&hiddev->list); spin_lock_init(&hiddev->list_lock); mutex_init(&hiddev->existancelock); hid->hiddev = hiddev; hiddev->hid = hid; hiddev->exist = 1; retval = usb_register_dev(usbhid->intf, &hiddev_class); if (retval) { hid_err(hid, "Not able to get a minor for this device\n"); hid->hiddev = NULL; kfree(hiddev); return -1; } return 0; } /* * This is where hid.c calls us to disconnect a hiddev device from the * corresponding hid device (usually because the usb device has disconnected) */ static struct usb_class_driver hiddev_class; void hiddev_disconnect(struct hid_device *hid) { struct hiddev *hiddev = hid->hiddev; struct usbhid_device *usbhid = hid->driver_data; usb_deregister_dev(usbhid->intf, &hiddev_class); mutex_lock(&hiddev->existancelock); hiddev->exist = 0; if (hiddev->open) { mutex_unlock(&hiddev->existancelock); usbhid_close(hiddev->hid); wake_up_interruptible(&hiddev->wait); } else { mutex_unlock(&hiddev->existancelock); kfree(hiddev); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5174_0
crossvul-cpp_data_good_1064_0
/* * asn1.c: ASN.1 decoding functions (DER) * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <assert.h> #include <ctype.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "internal.h" #include "asn1.h" static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1, const u8 *in, size_t len, const u8 **newp, size_t *len_left, int choice, int depth); static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1, u8 **ptr, size_t *size, int depth); static int asn1_write_element(sc_context_t *ctx, unsigned int tag, const u8 * data, size_t datalen, u8 ** out, size_t * outlen); static const char *tag2str(unsigned int tag) { static const char *tags[] = { "EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", /* 0-4 */ "NULL", "OBJECT IDENTIFIER", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", /* 5-9 */ "ENUMERATED", "Universal 11", "UTF8String", "Universal 13", /* 10-13 */ "Universal 14", "Universal 15", "SEQUENCE", "SET", /* 15-17 */ "NumericString", "PrintableString", "T61String", /* 18-20 */ "VideotexString", "IA5String", "UTCTIME", "GENERALIZEDTIME", /* 21-24 */ "GraphicString", "VisibleString", "GeneralString", /* 25-27 */ "UniversalString", "Universal 29", "BMPString" /* 28-30 */ }; if (tag > 30) return "(unknown)"; return tags[tag]; } int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out, unsigned int *tag_out, size_t *taglen) { const u8 *p = *buf; size_t left = buflen, len; unsigned int cla, tag, i; *buf = NULL; if (left == 0) return SC_ERROR_INVALID_ASN1_OBJECT; if (*p == 0xff || *p == 0) { /* end of data reached */ *taglen = 0; *tag_out = SC_ASN1_TAG_EOC; return SC_SUCCESS; } /* parse tag byte(s) * Resulted tag is presented by integer that has not to be * confused with the 'tag number' part of ASN.1 tag. */ cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED); tag = *p & SC_ASN1_TAG_PRIMITIVE; p++; left--; if (tag == SC_ASN1_TAG_PRIMITIVE) { /* high tag number */ size_t n = SC_ASN1_TAGNUM_SIZE - 1; /* search the last tag octet */ do { if (left == 0 || n == 0) /* either an invalid tag or it doesn't fit in * unsigned int */ return SC_ERROR_INVALID_ASN1_OBJECT; tag <<= 8; tag |= *p; p++; left--; n--; } while (tag & 0x80); } /* parse length byte(s) */ if (left == 0) return SC_ERROR_INVALID_ASN1_OBJECT; len = *p; p++; left--; if (len & 0x80) { len &= 0x7f; unsigned int a = 0; if (len > sizeof a || len > left) return SC_ERROR_INVALID_ASN1_OBJECT; for (i = 0; i < len; i++) { a <<= 8; a |= *p; p++; left--; } len = a; } *cla_out = cla; *tag_out = tag; *taglen = len; *buf = p; if (len > left) return SC_ERROR_ASN1_END_OF_CONTENTS; return SC_SUCCESS; } void sc_format_asn1_entry(struct sc_asn1_entry *entry, void *parm, void *arg, int set_present) { entry->parm = parm; entry->arg = arg; if (set_present) entry->flags |= SC_ASN1_PRESENT; } void sc_copy_asn1_entry(const struct sc_asn1_entry *src, struct sc_asn1_entry *dest) { while (src->name != NULL) { *dest = *src; dest++; src++; } dest->name = NULL; } static void print_indent(size_t depth) { for (; depth > 0; depth--) { putchar(' '); } } static void print_hex(const u8 * buf, size_t buflen, size_t depth) { size_t lines_len = buflen * 5 + 128; char *lines = malloc(lines_len); char *line = lines; if (buf == NULL || buflen == 0 || lines == NULL) { free(lines); return; } sc_hex_dump(buf, buflen, lines, lines_len); while (*line != '\0') { char *line_end = strchr(line, '\n'); ptrdiff_t width = line_end - line; if (!line_end || width <= 1) { /* don't print empty lines */ break; } if (buflen > 8) { putchar('\n'); print_indent(depth); } else { printf(": "); } printf("%.*s", (int) width, line); line = line_end + 1; } free(lines); } static void print_ascii(const u8 * buf, size_t buflen) { for (; 0 < buflen; buflen--, buf++) { if (isprint(*buf)) printf("%c", *buf); else putchar('.'); } } static void sc_asn1_print_octet_string(const u8 * buf, size_t buflen, size_t depth) { print_hex(buf, buflen, depth); } static void sc_asn1_print_utf8string(const u8 * buf, size_t buflen) { /* FIXME UTF-8 is not ASCII */ print_ascii(buf, buflen); } static void sc_asn1_print_integer(const u8 * buf, size_t buflen) { size_t a = 0; if (buflen > sizeof(a)) { printf("0x%s", sc_dump_hex(buf, buflen)); } else { size_t i; for (i = 0; i < buflen; i++) { a <<= 8; a |= buf[i]; } printf("%"SC_FORMAT_LEN_SIZE_T"u", a); } } static void sc_asn1_print_boolean(const u8 * buf, size_t buflen) { if (!buflen) return; if (buf[0]) printf("true"); else printf("false"); } static void sc_asn1_print_bit_string(const u8 * buf, size_t buflen, size_t depth) { #ifndef _WIN32 long long a = 0; #else __int64 a = 0; #endif int r, i; if (buflen > sizeof(a) + 1) { print_hex(buf, buflen, depth); } else { r = sc_asn1_decode_bit_string(buf, buflen, &a, sizeof(a)); if (r < 0) { printf("decode error"); return; } for (i = r - 1; i >= 0; i--) { printf("%c", ((a >> i) & 1) ? '1' : '0'); } } } #ifdef ENABLE_OPENSSL #include <openssl/objects.h> static void openssl_print_object_sn(const char *s) { ASN1_OBJECT *obj = OBJ_txt2obj(s, 0); if (obj) { int nid = OBJ_obj2nid(obj); if (nid != NID_undef) { printf(", %s", OBJ_nid2sn(nid)); } ASN1_OBJECT_free(obj); } } #else static void openssl_print_object_sn(const char *s) { } #endif static void sc_asn1_print_object_id(const u8 * buf, size_t buflen) { struct sc_object_id oid; const char *sbuf; if (sc_asn1_decode_object_id(buf, buflen, &oid)) { printf("decode error"); return; } sbuf = sc_dump_oid(&oid); printf(" %s", sbuf); openssl_print_object_sn(sbuf); } static void sc_asn1_print_utctime(const u8 * buf, size_t buflen) { if (buflen < 8) { printf("Error in decoding.\n"); return; } print_ascii(buf, 2); /* YY */ putchar('-'); print_ascii(buf+2, 2); /* MM */ putchar('-'); print_ascii(buf+4, 2); /* DD */ putchar(' '); print_ascii(buf+6, 2); /* hh */ buf += 8; buflen -= 8; if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) { putchar(':'); print_ascii(buf, 2); /* mm */ buf += 2; buflen -= 2; } if (buflen >= 2 && isdigit(buf[0]) && isdigit(buf[1])) { putchar(':'); print_ascii(buf, 2); /* ss */ buf += 2; buflen -= 2; } if (buflen >= 4 && '.' == buf[0]) { print_ascii(buf, 4); /* fff */ buf += 4; buflen -= 4; } if (buflen >= 1 && 'Z' == buf[0]) { printf(" UTC"); } else if (buflen >= 5 && ('-' == buf[0] || '+' == buf[0])) { putchar(' '); print_ascii(buf, 3); /* +/-hh */ putchar(':'); print_ascii(buf+3, 2); /* mm */ } } static void sc_asn1_print_generalizedtime(const u8 * buf, size_t buflen) { if (buflen < 8) { printf("Error in decoding.\n"); return; } print_ascii(buf, 2); sc_asn1_print_utctime(buf + 2, buflen - 2); } static void print_tags_recursive(const u8 * buf0, const u8 * buf, size_t buflen, size_t depth) { int r; size_t i; size_t bytesleft = buflen; const char *classes[4] = { "Universal", "Application", "Context", "Private" }; const u8 *p = buf; while (bytesleft >= 2) { unsigned int cla = 0, tag = 0, hlen; const u8 *tagp = p; size_t len; r = sc_asn1_read_tag(&tagp, bytesleft, &cla, &tag, &len); if (r != SC_SUCCESS || tagp == NULL) { printf("Error in decoding.\n"); return; } hlen = tagp - p; if (cla == 0 && tag == 0) { printf("Zero tag, finishing\n"); break; } print_indent(depth); /* let i be the length of the tag in bytes */ for (i = 1; i < sizeof tag - 1; i++) { if (!(tag >> 8*i)) break; } printf("%02X", cla<<(i-1)*8 | tag); if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL) { printf(" %s", tag2str(tag)); } else { printf(" %s %-2u", classes[cla >> 6], i == 1 ? tag & SC_ASN1_TAG_PRIMITIVE : tag & (((unsigned int) ~0) >> (i-1)*8)); } if (!((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_UNIVERSAL && tag == SC_ASN1_TAG_NULL && len == 0)) { printf(" (%"SC_FORMAT_LEN_SIZE_T"u byte%s)", len, len != 1 ? "s" : ""); } if (len + hlen > bytesleft) { printf(" Illegal length!\n"); return; } p += hlen + len; bytesleft -= hlen + len; if (cla & SC_ASN1_TAG_CONSTRUCTED) { putchar('\n'); print_tags_recursive(buf0, tagp, len, depth + 2*i + 1); continue; } switch (tag) { case SC_ASN1_TAG_BIT_STRING: printf(": "); sc_asn1_print_bit_string(tagp, len, depth + 2*i + 1); break; case SC_ASN1_TAG_OCTET_STRING: sc_asn1_print_octet_string(tagp, len, depth + 2*i + 1); break; case SC_ASN1_TAG_OBJECT: printf(": "); sc_asn1_print_object_id(tagp, len); break; case SC_ASN1_TAG_INTEGER: case SC_ASN1_TAG_ENUMERATED: printf(": "); sc_asn1_print_integer(tagp, len); break; case SC_ASN1_TAG_IA5STRING: case SC_ASN1_TAG_PRINTABLESTRING: case SC_ASN1_TAG_T61STRING: case SC_ASN1_TAG_UTF8STRING: printf(": "); sc_asn1_print_utf8string(tagp, len); break; case SC_ASN1_TAG_BOOLEAN: printf(": "); sc_asn1_print_boolean(tagp, len); break; case SC_ASN1_GENERALIZEDTIME: printf(": "); sc_asn1_print_generalizedtime(tagp, len); break; case SC_ASN1_UTCTIME: printf(": "); sc_asn1_print_utctime(tagp, len); break; } if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_APPLICATION) { print_hex(tagp, len, depth + 2*i + 1); } if ((cla & SC_ASN1_TAG_CLASS) == SC_ASN1_TAG_CONTEXT) { print_hex(tagp, len, depth + 2*i + 1); } putchar('\n'); } } void sc_asn1_print_tags(const u8 * buf, size_t buflen) { print_tags_recursive(buf, buf, buflen, 0); } const u8 *sc_asn1_find_tag(sc_context_t *ctx, const u8 * buf, size_t buflen, unsigned int tag_in, size_t *taglen_in) { size_t left = buflen, taglen; const u8 *p = buf; *taglen_in = 0; while (left >= 2) { unsigned int cla = 0, tag, mask = 0xff00; buf = p; /* read a tag */ if (sc_asn1_read_tag(&p, left, &cla, &tag, &taglen) != SC_SUCCESS || p == NULL) return NULL; left -= (p - buf); /* we need to shift the class byte to the leftmost * byte of the tag */ while ((tag & mask) != 0) { cla <<= 8; mask <<= 8; } /* compare the read tag with the given tag */ if ((tag | cla) == tag_in) { /* we have a match => return length and value part */ if (taglen > left) return NULL; *taglen_in = taglen; return p; } /* otherwise continue reading tags */ left -= taglen; p += taglen; } return NULL; } const u8 *sc_asn1_skip_tag(sc_context_t *ctx, const u8 ** buf, size_t *buflen, unsigned int tag_in, size_t *taglen_out) { const u8 *p = *buf; size_t len = *buflen, taglen; unsigned int cla = 0, tag; if (sc_asn1_read_tag((const u8 **) &p, len, &cla, &tag, &taglen) != SC_SUCCESS || p == NULL) return NULL; switch (cla & 0xC0) { case SC_ASN1_TAG_UNIVERSAL: if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_UNI) return NULL; break; case SC_ASN1_TAG_APPLICATION: if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_APP) return NULL; break; case SC_ASN1_TAG_CONTEXT: if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_CTX) return NULL; break; case SC_ASN1_TAG_PRIVATE: if ((tag_in & SC_ASN1_CLASS_MASK) != SC_ASN1_PRV) return NULL; break; } if (cla & SC_ASN1_TAG_CONSTRUCTED) { if ((tag_in & SC_ASN1_CONS) == 0) return NULL; } else if (tag_in & SC_ASN1_CONS) return NULL; if ((tag_in & SC_ASN1_TAG_MASK) != tag) return NULL; len -= (p - *buf); /* header size */ if (taglen > len) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "too long ASN.1 object (size %"SC_FORMAT_LEN_SIZE_T"u while only %"SC_FORMAT_LEN_SIZE_T"u available)\n", taglen, len); return NULL; } *buflen -= (p - *buf) + taglen; *buf = p + taglen; /* point to next tag */ *taglen_out = taglen; return p; } const u8 *sc_asn1_verify_tag(sc_context_t *ctx, const u8 * buf, size_t buflen, unsigned int tag_in, size_t *taglen_out) { return sc_asn1_skip_tag(ctx, &buf, &buflen, tag_in, taglen_out); } static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen, int invert) { const u8 *in = inbuf; u8 *out = (u8 *) outbuf; int i, count = 0; int zero_bits; size_t octets_left; if (outlen < octets_left) return SC_ERROR_BUFFER_TOO_SMALL; if (inlen < 1) return SC_ERROR_INVALID_ASN1_OBJECT; zero_bits = *in & 0x07; octets_left = inlen - 1; in++; memset(outbuf, 0, outlen); while (octets_left) { /* 1st octet of input: ABCDEFGH, where A is the MSB */ /* 1st octet of output: HGFEDCBA, where A is the LSB */ /* first bit in bit string is the LSB in first resulting octet */ int bits_to_go; *out = 0; if (octets_left == 1) bits_to_go = 8 - zero_bits; else bits_to_go = 8; if (invert) for (i = 0; i < bits_to_go; i++) { *out |= ((*in >> (7 - i)) & 1) << i; } else { *out = *in; } out++; in++; octets_left--; count++; } return (count * 8) - zero_bits; } int sc_asn1_decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen) { return decode_bit_string(inbuf, inlen, outbuf, outlen, 1); } int sc_asn1_decode_bit_string_ni(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen) { return decode_bit_string(inbuf, inlen, outbuf, outlen, 0); } static int encode_bit_string(const u8 * inbuf, size_t bits_left, u8 **outbuf, size_t *outlen, int invert) { const u8 *in = inbuf; u8 *out; size_t bytes; int skipped = 0; bytes = (bits_left + 7)/8 + 1; *outbuf = out = malloc(bytes); if (out == NULL) return SC_ERROR_OUT_OF_MEMORY; *outlen = bytes; out += 1; while (bits_left) { int i, bits_to_go = 8; *out = 0; if (bits_left < 8) { bits_to_go = bits_left; skipped = 8 - bits_left; } if (invert) { for (i = 0; i < bits_to_go; i++) *out |= ((*in >> i) & 1) << (7 - i); } else { *out = *in; if (bits_left < 8) return SC_ERROR_NOT_SUPPORTED; /* FIXME */ } bits_left -= bits_to_go; out++, in++; } out = *outbuf; out[0] = skipped; return 0; } /* * Bitfields are just bit strings, stored in an unsigned int * (taking endianness into account) */ static int decode_bit_field(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen) { u8 data[sizeof(unsigned int)]; unsigned int field = 0; int i, n; if (outlen != sizeof(data)) return SC_ERROR_BUFFER_TOO_SMALL; n = decode_bit_string(inbuf, inlen, data, sizeof(data), 1); if (n < 0) return n; for (i = 0; i < n; i += 8) { field |= (data[i/8] << i); } memcpy(outbuf, &field, outlen); return 0; } static int encode_bit_field(const u8 *inbuf, size_t inlen, u8 **outbuf, size_t *outlen) { u8 data[sizeof(unsigned int)]; unsigned int field = 0; size_t i, bits; if (inlen != sizeof(data)) return SC_ERROR_BUFFER_TOO_SMALL; /* count the bits */ memcpy(&field, inbuf, inlen); for (bits = 0; field; bits++) field >>= 1; memcpy(&field, inbuf, inlen); for (i = 0; i < bits; i += 8) data[i/8] = field >> i; return encode_bit_string(data, bits, outbuf, outlen, 1); } int sc_asn1_decode_integer(const u8 * inbuf, size_t inlen, int *out) { int a = 0; size_t i; if (inlen > sizeof(int) || inlen == 0) return SC_ERROR_INVALID_ASN1_OBJECT; if (inbuf[0] & 0x80) a = -1; for (i = 0; i < inlen; i++) { a <<= 8; a |= *inbuf++; } *out = a; return 0; } static int asn1_encode_integer(int in, u8 ** obj, size_t * objsize) { int i = sizeof(in) * 8, skip_zero, skip_sign; u8 *p, b; if (in < 0) { skip_sign = 1; skip_zero= 0; } else { skip_sign = 0; skip_zero= 1; } *obj = p = malloc(sizeof(in)+1); if (*obj == NULL) return SC_ERROR_OUT_OF_MEMORY; do { i -= 8; b = in >> i; if (skip_sign) { if (b != 0xff) skip_sign = 0; if (b & 0x80) { *p = b; if (0xff == b) continue; } else { p++; skip_sign = 0; } } if (b == 0 && skip_zero) continue; if (skip_zero) { skip_zero = 0; /* prepend 0x00 if MSb is 1 and integer positive */ if ((b & 0x80) != 0 && in > 0) *p++ = 0; } *p++ = b; } while (i > 0); if (skip_sign) p++; *objsize = p - *obj; if (*objsize == 0) { *objsize = 1; (*obj)[0] = 0; } return 0; } int sc_asn1_decode_object_id(const u8 *inbuf, size_t inlen, struct sc_object_id *id) { int a; const u8 *p = inbuf; int *octet; if (inlen == 0 || inbuf == NULL || id == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(id); octet = id->value; a = *p; *octet++ = a / 40; *octet++ = a % 40; inlen--; while (inlen) { p++; a = *p & 0x7F; inlen--; while (inlen && *p & 0x80) { p++; a <<= 7; a |= *p & 0x7F; inlen--; } *octet++ = a; if (octet - id->value >= SC_MAX_OBJECT_ID_OCTETS) { sc_init_oid(id); return SC_ERROR_INVALID_ASN1_OBJECT; } }; return 0; } int sc_asn1_encode_object_id(u8 **buf, size_t *buflen, const struct sc_object_id *id) { u8 temp[SC_MAX_OBJECT_ID_OCTETS*5], *p = temp; int i; if (!buflen || !id) return SC_ERROR_INVALID_ARGUMENTS; /* an OID must have at least two components */ if (id->value[0] == -1 || id->value[1] == -1) return SC_ERROR_INVALID_ARGUMENTS; for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { unsigned int k, shift; if (id->value[i] == -1) break; k = id->value[i]; switch (i) { case 0: if (k > 2) return SC_ERROR_INVALID_ARGUMENTS; *p = k * 40; break; case 1: if (k > 39) return SC_ERROR_INVALID_ARGUMENTS; *p++ += k; break; default: shift = 28; while (shift && (k >> shift) == 0) shift -= 7; while (shift) { *p++ = 0x80 | ((k >> shift) & 0x7f); shift -= 7; } *p++ = k & 0x7F; break; } } *buflen = p - temp; if (buf) { *buf = malloc(*buflen); if (!*buf) return SC_ERROR_OUT_OF_MEMORY; memcpy(*buf, temp, *buflen); } return 0; } static int sc_asn1_decode_utf8string(const u8 *inbuf, size_t inlen, u8 *out, size_t *outlen) { if (inlen+1 > *outlen) return SC_ERROR_BUFFER_TOO_SMALL; *outlen = inlen+1; memcpy(out, inbuf, inlen); out[inlen] = 0; return 0; } int sc_asn1_put_tag(unsigned int tag, const u8 * data, size_t datalen, u8 * out, size_t outlen, u8 **ptr) { size_t c = 0; size_t tag_len; size_t ii; u8 *p = out; u8 tag_char[4] = {0, 0, 0, 0}; /* Check tag */ if (tag == 0 || tag > 0xFFFFFFFF) { /* A tag of 0x00 is not valid and at most 4-byte tag names are supported. */ return SC_ERROR_INVALID_DATA; } for (tag_len = 0; tag; tag >>= 8) { /* Note: tag char will be reversed order. */ tag_char[tag_len++] = tag & 0xFF; } if (tag_len > 1) { if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER) { /* First byte is not escape marker. */ return SC_ERROR_INVALID_DATA; } for (ii = 1; ii < tag_len - 1; ii++) { if ((tag_char[ii] & 0x80) != 0x80) { /* MS bit is not 'one'. */ return SC_ERROR_INVALID_DATA; } } if ((tag_char[0] & 0x80) != 0x00) { /* MS bit of the last byte is not 'zero'. */ return SC_ERROR_INVALID_DATA; } } /* Calculate the number of additional bytes necessary to encode the length. */ /* c+1 is the size of the length field. */ if (datalen > 127) { c = 1; while (datalen >> (c << 3)) c++; } if (outlen == 0 || out == NULL) { /* Caller only asks for the length that would be written. */ return tag_len + (c+1) + datalen; } /* We will write the tag, so check the length. */ if (outlen < tag_len + (c+1) + datalen) return SC_ERROR_BUFFER_TOO_SMALL; for (ii=0;ii<tag_len;ii++) *p++ = tag_char[tag_len - ii - 1]; if (c > 0) { *p++ = 0x80 | c; while (c--) *p++ = (datalen >> (c << 3)) & 0xFF; } else { *p++ = datalen & 0x7F; } if(data && datalen > 0) { memcpy(p, data, datalen); p += datalen; } if (ptr != NULL) *ptr = p; return 0; } int sc_asn1_write_element(sc_context_t *ctx, unsigned int tag, const u8 * data, size_t datalen, u8 ** out, size_t * outlen) { return asn1_write_element(ctx, tag, data, datalen, out, outlen); } static int asn1_write_element(sc_context_t *ctx, unsigned int tag, const u8 * data, size_t datalen, u8 ** out, size_t * outlen) { unsigned char t; unsigned char *buf, *p; int c = 0; unsigned short_tag; unsigned char tag_char[3] = {0, 0, 0}; size_t tag_len, ii; short_tag = tag & SC_ASN1_TAG_MASK; for (tag_len = 0; short_tag >> (8 * tag_len); tag_len++) tag_char[tag_len] = (short_tag >> (8 * tag_len)) & 0xFF; if (!tag_len) tag_len = 1; if (tag_len > 1) { if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER) SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "First byte of the long tag is not 'escape marker'"); for (ii = 1; ii < tag_len - 1; ii++) if (!(tag_char[ii] & 0x80)) SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit expected to be 'one'"); if (tag_char[0] & 0x80) SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit of the last byte expected to be 'zero'"); } t = tag_char[tag_len - 1] & 0x1F; switch (tag & SC_ASN1_CLASS_MASK) { case SC_ASN1_UNI: break; case SC_ASN1_APP: t |= SC_ASN1_TAG_APPLICATION; break; case SC_ASN1_CTX: t |= SC_ASN1_TAG_CONTEXT; break; case SC_ASN1_PRV: t |= SC_ASN1_TAG_PRIVATE; break; } if (tag & SC_ASN1_CONS) t |= SC_ASN1_TAG_CONSTRUCTED; if (datalen > 127) { c = 1; while (datalen >> (c << 3)) c++; } *outlen = tag_len + 1 + c + datalen; buf = malloc(*outlen); if (buf == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_OUT_OF_MEMORY); *out = p = buf; *p++ = t; for (ii=1;ii<tag_len;ii++) *p++ = tag_char[tag_len - ii - 1]; if (c) { *p++ = 0x80 | c; while (c--) *p++ = (datalen >> (c << 3)) & 0xFF; } else { *p++ = datalen & 0x7F; } memcpy(p, data, datalen); return SC_SUCCESS; } static const struct sc_asn1_entry c_asn1_path_ext[3] = { { "aid", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x0F, 0, NULL, NULL }, { "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static const struct sc_asn1_entry c_asn1_path[5] = { { "path", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { "index", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { "length", SC_ASN1_INTEGER, SC_ASN1_CTX | 0, SC_ASN1_OPTIONAL, NULL, NULL }, /* For some multi-applications PKCS#15 card the ODF records can hold the references to * the xDF files and objects placed elsewhere then under the application DF of the ODF itself. * In such a case the 'path' ASN1 data includes also the ID of the target application (AID). * This path extension do not make a part of PKCS#15 standard. */ { "pathExtended", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int asn1_decode_path(sc_context_t *ctx, const u8 *in, size_t len, sc_path_t *path, int depth) { int idx, count, r; struct sc_asn1_entry asn1_path_ext[3], asn1_path[5]; unsigned char path_value[SC_MAX_PATH_SIZE], aid_value[SC_MAX_AID_SIZE]; size_t path_len = sizeof(path_value), aid_len = sizeof(aid_value); memset(path, 0, sizeof(struct sc_path)); sc_copy_asn1_entry(c_asn1_path_ext, asn1_path_ext); sc_copy_asn1_entry(c_asn1_path, asn1_path); sc_format_asn1_entry(asn1_path_ext + 0, aid_value, &aid_len, 0); sc_format_asn1_entry(asn1_path_ext + 1, path_value, &path_len, 0); sc_format_asn1_entry(asn1_path + 0, path_value, &path_len, 0); sc_format_asn1_entry(asn1_path + 1, &idx, NULL, 0); sc_format_asn1_entry(asn1_path + 2, &count, NULL, 0); sc_format_asn1_entry(asn1_path + 3, asn1_path_ext, NULL, 0); r = asn1_decode(ctx, asn1_path, in, len, NULL, NULL, 0, depth + 1); if (r) return r; if (asn1_path[3].flags & SC_ASN1_PRESENT) { /* extended path present: set 'path' and 'aid' */ memcpy(path->aid.value, aid_value, aid_len); path->aid.len = aid_len; memcpy(path->value, path_value, path_len); path->len = path_len; } else if (asn1_path[0].flags & SC_ASN1_PRESENT) { /* path present: set 'path' */ memcpy(path->value, path_value, path_len); path->len = path_len; } else { /* failed if both 'path' and 'pathExtended' are absent */ return SC_ERROR_ASN1_OBJECT_NOT_FOUND; } if (path->len == 2) path->type = SC_PATH_TYPE_FILE_ID; else if (path->aid.len && path->len > 2) path->type = SC_PATH_TYPE_FROM_CURRENT; else path->type = SC_PATH_TYPE_PATH; if ((asn1_path[1].flags & SC_ASN1_PRESENT) && (asn1_path[2].flags & SC_ASN1_PRESENT)) { path->index = idx; path->count = count; } else { path->index = 0; path->count = -1; } return SC_SUCCESS; } static int asn1_encode_path(sc_context_t *ctx, const sc_path_t *path, u8 **buf, size_t *bufsize, int depth, unsigned int parent_flags) { int r; struct sc_asn1_entry asn1_path[5]; sc_path_t tpath = *path; sc_copy_asn1_entry(c_asn1_path, asn1_path); sc_format_asn1_entry(asn1_path + 0, (void *) &tpath.value, (void *) &tpath.len, 1); asn1_path[0].flags |= parent_flags; if (path->count > 0) { sc_format_asn1_entry(asn1_path + 1, (void *) &tpath.index, NULL, 1); sc_format_asn1_entry(asn1_path + 2, (void *) &tpath.count, NULL, 1); } r = asn1_encode(ctx, asn1_path, buf, bufsize, depth + 1); return r; } static const struct sc_asn1_entry c_asn1_se[2] = { { "seInfo", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static const struct sc_asn1_entry c_asn1_se_info[4] = { { "se", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL }, { "owner",SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_OPTIONAL, NULL, NULL }, { "aid", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int asn1_decode_se_info(sc_context_t *ctx, const u8 *obj, size_t objlen, sc_pkcs15_sec_env_info_t ***se, size_t *num, int depth) { struct sc_pkcs15_sec_env_info **ses; const unsigned char *ptr = obj; size_t idx, ptrlen = objlen; int ret; ses = calloc(SC_MAX_SE_NUM, sizeof(sc_pkcs15_sec_env_info_t *)); if (ses == NULL) return SC_ERROR_OUT_OF_MEMORY; for (idx=0; idx < SC_MAX_SE_NUM && ptrlen; ) { struct sc_asn1_entry asn1_se[2]; struct sc_asn1_entry asn1_se_info[4]; struct sc_pkcs15_sec_env_info si; sc_copy_asn1_entry(c_asn1_se, asn1_se); sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info); si.aid.len = sizeof(si.aid.value); sc_format_asn1_entry(asn1_se_info + 0, &si.se, NULL, 0); sc_format_asn1_entry(asn1_se_info + 1, &si.owner, NULL, 0); sc_format_asn1_entry(asn1_se_info + 2, &si.aid.value, &si.aid.len, 0); sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 0); ret = asn1_decode(ctx, asn1_se, ptr, ptrlen, &ptr, &ptrlen, 0, depth+1); if (ret != SC_SUCCESS) goto err; if (!(asn1_se_info[1].flags & SC_ASN1_PRESENT)) sc_init_oid(&si.owner); ses[idx] = calloc(1, sizeof(sc_pkcs15_sec_env_info_t)); if (ses[idx] == NULL) { ret = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(ses[idx], &si, sizeof(struct sc_pkcs15_sec_env_info)); idx++; } *se = ses; *num = idx; ret = SC_SUCCESS; err: if (ret != SC_SUCCESS) { size_t i; for (i = 0; i < idx; i++) if (ses[i]) free(ses[i]); free(ses); } return ret; } static int asn1_encode_se_info(sc_context_t *ctx, struct sc_pkcs15_sec_env_info **se, size_t se_num, unsigned char **buf, size_t *bufsize, int depth) { unsigned char *ptr = NULL, *out = NULL, *p; size_t ptrlen = 0, outlen = 0, idx; int ret; for (idx=0; idx < se_num; idx++) { struct sc_asn1_entry asn1_se[2]; struct sc_asn1_entry asn1_se_info[4]; sc_copy_asn1_entry(c_asn1_se, asn1_se); sc_copy_asn1_entry(c_asn1_se_info, asn1_se_info); sc_format_asn1_entry(asn1_se_info + 0, &se[idx]->se, NULL, 1); if (sc_valid_oid(&se[idx]->owner)) sc_format_asn1_entry(asn1_se_info + 1, &se[idx]->owner, NULL, 1); if (se[idx]->aid.len) sc_format_asn1_entry(asn1_se_info + 2, &se[idx]->aid.value, &se[idx]->aid.len, 1); sc_format_asn1_entry(asn1_se + 0, asn1_se_info, NULL, 1); ret = sc_asn1_encode(ctx, asn1_se, &ptr, &ptrlen); if (ret != SC_SUCCESS) goto err; if (!ptrlen) continue; p = (unsigned char *) realloc(out, outlen + ptrlen); if (!p) { ret = SC_ERROR_OUT_OF_MEMORY; goto err; } out = p; memcpy(out + outlen, ptr, ptrlen); outlen += ptrlen; free(ptr); ptr = NULL; ptrlen = 0; } *buf = out; *bufsize = outlen; ret = SC_SUCCESS; err: if (ret != SC_SUCCESS && out != NULL) free(out); return ret; } /* TODO: According to specification type of 'SecurityCondition' is 'CHOICE'. * Do it at least for SC_ASN1_PKCS15_ID(authId), SC_ASN1_STRUCT(authReference) and NULL(always). */ static const struct sc_asn1_entry c_asn1_access_control_rule[3] = { { "accessMode", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { "securityCondition", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; /* * in src/libopensc/pkcs15.h SC_PKCS15_MAX_ACCESS_RULES defined as 8 */ static const struct sc_asn1_entry c_asn1_access_control_rules[SC_PKCS15_MAX_ACCESS_RULES + 1] = { { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRule", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static const struct sc_asn1_entry c_asn1_com_obj_attr[6] = { { "label", SC_ASN1_UTF8STRING, SC_ASN1_TAG_UTF8STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { "flags", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { "authId", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, SC_ASN1_OPTIONAL, NULL, NULL }, { "userConsent", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { "accessControlRules", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static const struct sc_asn1_entry c_asn1_p15_obj[5] = { { "commonObjectAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL }, { "classAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL }, { "subClassAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 0 | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL }, { "typeAttributes", SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int asn1_decode_p15_object(sc_context_t *ctx, const u8 *in, size_t len, struct sc_asn1_pkcs15_object *obj, int depth) { struct sc_pkcs15_object *p15_obj = obj->p15_obj; struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5]; struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3]; size_t flags_len = sizeof(p15_obj->flags); size_t label_len = sizeof(p15_obj->label); size_t access_mode_len = sizeof(p15_obj->access_rules[0].access_mode); int r, ii; for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]); sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules); sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr); sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj); sc_format_asn1_entry(asn1_c_attr + 0, p15_obj->label, &label_len, 0); sc_format_asn1_entry(asn1_c_attr + 1, &p15_obj->flags, &flags_len, 0); sc_format_asn1_entry(asn1_c_attr + 2, &p15_obj->auth_id, NULL, 0); sc_format_asn1_entry(asn1_c_attr + 3, &p15_obj->user_consent, NULL, 0); for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) { sc_format_asn1_entry(asn1_ac_rule[ii] + 0, &p15_obj->access_rules[ii].access_mode, &access_mode_len, 0); sc_format_asn1_entry(asn1_ac_rule[ii] + 1, &p15_obj->access_rules[ii].auth_id, NULL, 0); sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 0); } sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 0); sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 0); sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 0); sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 0); sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 0); r = asn1_decode(ctx, asn1_p15_obj, in, len, NULL, NULL, 0, depth + 1); return r; } static int asn1_encode_p15_object(sc_context_t *ctx, const struct sc_asn1_pkcs15_object *obj, u8 **buf, size_t *bufsize, int depth) { struct sc_pkcs15_object p15_obj = *obj->p15_obj; struct sc_asn1_entry asn1_c_attr[6], asn1_p15_obj[5]; struct sc_asn1_entry asn1_ac_rules[SC_PKCS15_MAX_ACCESS_RULES + 1], asn1_ac_rule[SC_PKCS15_MAX_ACCESS_RULES][3]; size_t label_len = strlen(p15_obj.label); size_t flags_len; size_t access_mode_len; int r, ii; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encode p15 obj(type:0x%X,access_mode:0x%X)", p15_obj.type, p15_obj.access_rules[0].access_mode); if (p15_obj.access_rules[0].access_mode) { for (ii=0; ii<SC_PKCS15_MAX_ACCESS_RULES; ii++) { sc_copy_asn1_entry(c_asn1_access_control_rule, asn1_ac_rule[ii]); if (p15_obj.access_rules[ii].auth_id.len == 0) { asn1_ac_rule[ii][1].type = SC_ASN1_NULL; asn1_ac_rule[ii][1].tag = SC_ASN1_TAG_NULL; } } sc_copy_asn1_entry(c_asn1_access_control_rules, asn1_ac_rules); } sc_copy_asn1_entry(c_asn1_com_obj_attr, asn1_c_attr); sc_copy_asn1_entry(c_asn1_p15_obj, asn1_p15_obj); if (label_len != 0) sc_format_asn1_entry(asn1_c_attr + 0, (void *) p15_obj.label, &label_len, 1); if (p15_obj.flags) { flags_len = sizeof(p15_obj.flags); sc_format_asn1_entry(asn1_c_attr + 1, (void *) &p15_obj.flags, &flags_len, 1); } if (p15_obj.auth_id.len) sc_format_asn1_entry(asn1_c_attr + 2, (void *) &p15_obj.auth_id, NULL, 1); if (p15_obj.user_consent) sc_format_asn1_entry(asn1_c_attr + 3, (void *) &p15_obj.user_consent, NULL, 1); if (p15_obj.access_rules[0].access_mode) { for (ii=0; p15_obj.access_rules[ii].access_mode; ii++) { access_mode_len = sizeof(p15_obj.access_rules[ii].access_mode); sc_format_asn1_entry(asn1_ac_rule[ii] + 0, (void *) &p15_obj.access_rules[ii].access_mode, &access_mode_len, 1); sc_format_asn1_entry(asn1_ac_rule[ii] + 1, (void *) &p15_obj.access_rules[ii].auth_id, NULL, 1); sc_format_asn1_entry(asn1_ac_rules + ii, asn1_ac_rule[ii], NULL, 1); } sc_format_asn1_entry(asn1_c_attr + 4, asn1_ac_rules, NULL, 1); } sc_format_asn1_entry(asn1_p15_obj + 0, asn1_c_attr, NULL, 1); sc_format_asn1_entry(asn1_p15_obj + 1, obj->asn1_class_attr, NULL, 1); if (obj->asn1_subclass_attr != NULL && obj->asn1_subclass_attr->name) sc_format_asn1_entry(asn1_p15_obj + 2, obj->asn1_subclass_attr, NULL, 1); sc_format_asn1_entry(asn1_p15_obj + 3, obj->asn1_type_attr, NULL, 1); r = asn1_encode(ctx, asn1_p15_obj, buf, bufsize, depth + 1); return r; } static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry, const u8 *obj, size_t objlen, int depth) { void *parm = entry->parm; int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj, size_t nobjlen, int ndepth); size_t *len = (size_t *) entry->arg; int r = 0; callback_func = parm; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n", depth, depth, "", entry->name, sc_dump_hex(obj, objlen > 16 ? 16 : objlen), objlen > 16 ? "..." : ""); switch (entry->type) { case SC_ASN1_STRUCT: if (parm != NULL) r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj, objlen, NULL, NULL, 0, depth + 1); break; case SC_ASN1_NULL: break; case SC_ASN1_BOOLEAN: if (parm != NULL) { if (objlen != 1) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n", objlen); r = SC_ERROR_INVALID_ASN1_OBJECT; } else *((int *) parm) = obj[0] ? 1 : 0; } break; case SC_ASN1_INTEGER: case SC_ASN1_ENUMERATED: if (parm != NULL) { r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm); sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "", entry->name, *((int *) entry->parm)); } break; case SC_ASN1_BIT_STRING_NI: case SC_ASN1_BIT_STRING: if (parm != NULL) { int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0; assert(len != NULL); if (objlen < 1) { r = SC_ERROR_INVALID_ASN1_OBJECT; break; } if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen-1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen-1; parm = *buf; } r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert); if (r >= 0) { *len = r; r = 0; } } break; case SC_ASN1_BIT_FIELD: if (parm != NULL) r = decode_bit_field(obj, objlen, (u8 *) parm, *len); break; case SC_ASN1_OCTET_STRING: if (parm != NULL) { size_t c; assert(len != NULL); /* Strip off padding zero */ if ((entry->flags & SC_ASN1_UNSIGNED) && objlen > 1 && obj[0] == 0x00) { objlen--; obj++; } /* Allocate buffer if needed */ if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_GENERALIZEDTIME: if (parm != NULL) { size_t c; assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_OBJECT: if (parm != NULL) r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm); break; case SC_ASN1_PRINTABLESTRING: case SC_ASN1_UTF8STRING: if (parm != NULL) { assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen+1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen+1; parm = *buf; } r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len); if (entry->flags & SC_ASN1_ALLOC) { *len -= 1; } } break; case SC_ASN1_PATH: if (entry->parm != NULL) r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth); break; case SC_ASN1_PKCS15_ID: if (entry->parm != NULL) { struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm; size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen; memcpy(id->value, obj, c); id->len = c; } break; case SC_ASN1_PKCS15_OBJECT: if (entry->parm != NULL) r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth); break; case SC_ASN1_ALGORITHM_ID: if (entry->parm != NULL) r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth); break; case SC_ASN1_SE_INFO: if (entry->parm != NULL) r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth); break; case SC_ASN1_CALLBACK: if (entry->parm != NULL) r = callback_func(ctx, entry->arg, obj, objlen, depth); break; default: sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type); return SC_ERROR_INVALID_ASN1_OBJECT; } if (r) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name, sc_strerror(r)); return r; } entry->flags |= SC_ASN1_PRESENT; return 0; } static int asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1, const u8 *in, size_t len, const u8 **newp, size_t *len_left, int choice, int depth) { int r, idx = 0; const u8 *p = in, *obj; struct sc_asn1_entry *entry = asn1; size_t left = len, objlen; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*scalled, left=%"SC_FORMAT_LEN_SIZE_T"u, depth %d%s\n", depth, depth, "", left, depth, choice ? ", choice" : ""); if (!p) return SC_ERROR_ASN1_OBJECT_NOT_FOUND; if (left < 2) { while (asn1->name && (asn1->flags & SC_ASN1_OPTIONAL)) asn1++; /* If all elements were optional, there's nothing * to complain about */ if (asn1->name == NULL) return 0; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "End of ASN.1 stream, " "non-optional field \"%s\" not found\n", asn1->name); return SC_ERROR_ASN1_OBJECT_NOT_FOUND; } if (p[0] == 0 || p[0] == 0xFF || len == 0) return SC_ERROR_ASN1_END_OF_CONTENTS; for (idx = 0; asn1[idx].name != NULL; idx++) { entry = &asn1[idx]; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "Looking for '%s', tag 0x%x%s%s\n", entry->name, entry->tag, choice? ", CHOICE" : "", (entry->flags & SC_ASN1_OPTIONAL)? ", OPTIONAL": ""); /* Special case CHOICE has no tag */ if (entry->type == SC_ASN1_CHOICE) { r = asn1_decode(ctx, (struct sc_asn1_entry *) entry->parm, p, left, &p, &left, 1, depth + 1); if (r >= 0) r = 0; goto decode_ok; } obj = sc_asn1_skip_tag(ctx, &p, &left, entry->tag, &objlen); if (obj == NULL) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "'%s' not present\n", entry->name); if (choice) continue; if (entry->flags & SC_ASN1_OPTIONAL) continue; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "mandatory ASN.1 object '%s' not found\n", entry->name); if (left) { u8 line[128], *linep = line; size_t i; line[0] = 0; for (i = 0; i < 10 && i < left; i++) { sprintf((char *) linep, "%02X ", p[i]); linep += 3; } sc_debug(ctx, SC_LOG_DEBUG_ASN1, "next tag: %s\n", line); } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND); } r = asn1_decode_entry(ctx, entry, obj, objlen, depth); decode_ok: if (r) return r; if (choice) break; } if (choice && asn1[idx].name == NULL) /* No match */ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_ASN1_OBJECT_NOT_FOUND); if (newp != NULL) *newp = p; if (len_left != NULL) *len_left = left; if (choice) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, idx); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, 0); } int sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1, const u8 *in, size_t len, const u8 **newp, size_t *len_left) { return asn1_decode(ctx, asn1, in, len, newp, len_left, 0, 0); } int sc_asn1_decode_choice(sc_context_t *ctx, struct sc_asn1_entry *asn1, const u8 *in, size_t len, const u8 **newp, size_t *len_left) { return asn1_decode(ctx, asn1, in, len, newp, len_left, 1, 0); } static int asn1_encode_entry(sc_context_t *ctx, const struct sc_asn1_entry *entry, u8 **obj, size_t *objlen, int depth) { void *parm = entry->parm; int (*callback_func)(sc_context_t *nctx, void *arg, u8 **nobj, size_t *nobjlen, int ndepth); const size_t *len = (const size_t *) entry->arg; int r = 0; u8 * buf = NULL; size_t buflen = 0; callback_func = parm; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sencoding '%s'%s\n", depth, depth, "", entry->name, (entry->flags & SC_ASN1_PRESENT)? "" : " (not present)"); if (!(entry->flags & SC_ASN1_PRESENT)) goto no_object; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*stype=%d, tag=0x%02x, parm=%p, len=%"SC_FORMAT_LEN_SIZE_T"u\n", depth, depth, "", entry->type, entry->tag, parm, len ? *len : 0); if (entry->type == SC_ASN1_CHOICE) { const struct sc_asn1_entry *list, *choice = NULL; list = (const struct sc_asn1_entry *) parm; while (list->name != NULL) { if (list->flags & SC_ASN1_PRESENT) { if (choice) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "ASN.1 problem: more than " "one CHOICE when encoding %s: " "%s and %s both present\n", entry->name, choice->name, list->name); return SC_ERROR_INVALID_ASN1_OBJECT; } choice = list; } list++; } if (choice == NULL) goto no_object; return asn1_encode_entry(ctx, choice, obj, objlen, depth + 1); } if (entry->type != SC_ASN1_NULL && parm == NULL) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "unexpected parm == NULL\n"); return SC_ERROR_INVALID_ASN1_OBJECT; } switch (entry->type) { case SC_ASN1_STRUCT: r = asn1_encode(ctx, (const struct sc_asn1_entry *) parm, &buf, &buflen, depth + 1); break; case SC_ASN1_NULL: buf = NULL; buflen = 0; break; case SC_ASN1_BOOLEAN: buf = malloc(1); if (buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } buf[0] = *((int *) parm) ? 0xFF : 0; buflen = 1; break; case SC_ASN1_INTEGER: case SC_ASN1_ENUMERATED: r = asn1_encode_integer(*((int *) entry->parm), &buf, &buflen); break; case SC_ASN1_BIT_STRING_NI: case SC_ASN1_BIT_STRING: if (len != NULL) { if (entry->type == SC_ASN1_BIT_STRING) r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 1); else r = encode_bit_string((const u8 *) parm, *len, &buf, &buflen, 0); } else { r = SC_ERROR_INVALID_ARGUMENTS; } break; case SC_ASN1_BIT_FIELD: if (len != NULL) { r = encode_bit_field((const u8 *) parm, *len, &buf, &buflen); } else { r = SC_ERROR_INVALID_ARGUMENTS; } break; case SC_ASN1_PRINTABLESTRING: case SC_ASN1_OCTET_STRING: case SC_ASN1_UTF8STRING: if (len != NULL) { buf = malloc(*len + 1); if (buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } buflen = 0; /* If the integer is supposed to be unsigned, insert * a padding byte if the MSB is one */ if ((entry->flags & SC_ASN1_UNSIGNED) && (((u8 *) parm)[0] & 0x80)) { buf[buflen++] = 0x00; } memcpy(buf + buflen, parm, *len); buflen += *len; } else { r = SC_ERROR_INVALID_ARGUMENTS; } break; case SC_ASN1_GENERALIZEDTIME: if (len != NULL) { buf = malloc(*len); if (buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } memcpy(buf, parm, *len); buflen = *len; } else { r = SC_ERROR_INVALID_ARGUMENTS; } break; case SC_ASN1_OBJECT: r = sc_asn1_encode_object_id(&buf, &buflen, (struct sc_object_id *) parm); break; case SC_ASN1_PATH: r = asn1_encode_path(ctx, (const sc_path_t *) parm, &buf, &buflen, depth, entry->flags); break; case SC_ASN1_PKCS15_ID: { const struct sc_pkcs15_id *id = (const struct sc_pkcs15_id *) parm; buf = malloc(id->len); if (buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } memcpy(buf, id->value, id->len); buflen = id->len; } break; case SC_ASN1_PKCS15_OBJECT: r = asn1_encode_p15_object(ctx, (const struct sc_asn1_pkcs15_object *) parm, &buf, &buflen, depth); break; case SC_ASN1_ALGORITHM_ID: r = sc_asn1_encode_algorithm_id(ctx, &buf, &buflen, (const struct sc_algorithm_id *) parm, depth); break; case SC_ASN1_SE_INFO: if (!len) return SC_ERROR_INVALID_ASN1_OBJECT; r = asn1_encode_se_info(ctx, (struct sc_pkcs15_sec_env_info **)parm, *len, &buf, &buflen, depth); break; case SC_ASN1_CALLBACK: r = callback_func(ctx, entry->arg, &buf, &buflen, depth); break; default: sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type); return SC_ERROR_INVALID_ASN1_OBJECT; } if (r) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "encoding of ASN.1 object '%s' failed: %s\n", entry->name, sc_strerror(r)); if (buf) free(buf); return r; } /* Treatment of OPTIONAL elements: * - if the encoding has 0 length, and the element is OPTIONAL, * we don't write anything (unless it's an ASN1 NULL and the * SC_ASN1_PRESENT flag is set). * - if the encoding has 0 length, but the element is non-OPTIONAL, * constructed, we write a empty element (e.g. a SEQUENCE of * length 0). In case of an ASN1 NULL just write the tag and * length (i.e. 0x05,0x00). * - any other empty objects are considered bogus */ no_object: if (!buflen && entry->flags & SC_ASN1_OPTIONAL && !(entry->flags & SC_ASN1_PRESENT)) { /* This happens when we try to encode e.g. the * subClassAttributes, which may be empty */ *obj = NULL; *objlen = 0; r = 0; } else if (!buflen && (entry->flags & SC_ASN1_EMPTY_ALLOWED)) { *obj = NULL; *objlen = 0; r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen); if (r) sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n", sc_strerror(r)); } else if (buflen || entry->type == SC_ASN1_NULL || entry->tag & SC_ASN1_CONS) { r = asn1_write_element(ctx, entry->tag, buf, buflen, obj, objlen); if (r) sc_debug(ctx, SC_LOG_DEBUG_ASN1, "error writing ASN.1 tag and length: %s\n", sc_strerror(r)); } else if (!(entry->flags & SC_ASN1_PRESENT)) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode non-optional ASN.1 object: not given by caller\n"); r = SC_ERROR_INVALID_ASN1_OBJECT; } else { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "cannot encode empty non-optional ASN.1 object\n"); r = SC_ERROR_INVALID_ASN1_OBJECT; } if (buf) free(buf); if (r >= 0) sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*slength of encoded item=%"SC_FORMAT_LEN_SIZE_T"u\n", depth, depth, "", *objlen); return r; } static int asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1, u8 **ptr, size_t *size, int depth) { int r, idx = 0; u8 *obj = NULL, *buf = NULL, *tmp; size_t total = 0, objsize; for (idx = 0; asn1[idx].name != NULL; idx++) { r = asn1_encode_entry(ctx, &asn1[idx], &obj, &objsize, depth); if (r) { if (obj) free(obj); if (buf) free(buf); return r; } /* in case of an empty (optional) element continue with * the next asn1 element */ if (!objsize) continue; tmp = (u8 *) realloc(buf, total + objsize); if (!tmp) { if (obj) free(obj); if (buf) free(buf); return SC_ERROR_OUT_OF_MEMORY; } buf = tmp; memcpy(buf + total, obj, objsize); free(obj); obj = NULL; total += objsize; } *ptr = buf; *size = total; return 0; } int sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1, u8 **ptr, size_t *size) { return asn1_encode(ctx, asn1, ptr, size, 0); } int _sc_asn1_encode(sc_context_t *ctx, const struct sc_asn1_entry *asn1, u8 **ptr, size_t *size, int depth) { return asn1_encode(ctx, asn1, ptr, size, depth); } int _sc_asn1_decode(sc_context_t *ctx, struct sc_asn1_entry *asn1, const u8 *in, size_t len, const u8 **newp, size_t *left, int choice, int depth) { return asn1_decode(ctx, asn1, in, len, newp, left, choice, depth); } int sc_der_copy(sc_pkcs15_der_t *dst, const sc_pkcs15_der_t *src) { if (!dst) return SC_ERROR_INVALID_ARGUMENTS; memset(dst, 0, sizeof(*dst)); if (src->len) { dst->value = malloc(src->len); if (!dst->value) return SC_ERROR_OUT_OF_MEMORY; dst->len = src->len; memcpy(dst->value, src->value, src->len); } return SC_SUCCESS; } int sc_encode_oid (struct sc_context *ctx, struct sc_object_id *id, unsigned char **out, size_t *size) { static const struct sc_asn1_entry c_asn1_object_id[2] = { { "oid", SC_ASN1_OBJECT, SC_ASN1_TAG_OBJECT, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; struct sc_asn1_entry asn1_object_id[2]; int rv; sc_copy_asn1_entry(c_asn1_object_id, asn1_object_id); sc_format_asn1_entry(asn1_object_id + 0, id, NULL, 1); rv = _sc_asn1_encode(ctx, asn1_object_id, out, size, 1); LOG_TEST_RET(ctx, rv, "Cannot encode object ID"); return SC_SUCCESS; } #define C_ASN1_SIG_VALUE_SIZE 2 static struct sc_asn1_entry c_asn1_sig_value[C_ASN1_SIG_VALUE_SIZE] = { { "ECDSA-Sig-Value", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE 3 static struct sc_asn1_entry c_asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE] = { { "r", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL }, { "s", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_INTEGER, SC_ASN1_ALLOC|SC_ASN1_UNSIGNED, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; int sc_asn1_sig_value_rs_to_sequence(struct sc_context *ctx, unsigned char *in, size_t inlen, unsigned char **buf, size_t *buflen) { struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE]; struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE]; unsigned char *r = in, *s = in + inlen/2; size_t r_len = inlen/2, s_len = inlen/2; int rv; LOG_FUNC_CALLED(ctx); /* R/S are filled up with zeroes, we do not want that in sequence format */ while(r_len > 1 && *r == 0x00) { r++; r_len--; } while(s_len > 1 && *s == 0x00) { s++; s_len--; } sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value); sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 1); sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients); sc_format_asn1_entry(asn1_sig_value_coefficients + 0, r, &r_len, 1); sc_format_asn1_entry(asn1_sig_value_coefficients + 1, s, &s_len, 1); rv = sc_asn1_encode(ctx, asn1_sig_value, buf, buflen); LOG_TEST_RET(ctx, rv, "ASN.1 encoding ECDSA-SIg-Value failed"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } int sc_asn1_sig_value_sequence_to_rs(struct sc_context *ctx, const unsigned char *in, size_t inlen, unsigned char *buf, size_t buflen) { struct sc_asn1_entry asn1_sig_value[C_ASN1_SIG_VALUE_SIZE]; struct sc_asn1_entry asn1_sig_value_coefficients[C_ASN1_SIG_VALUE_COEFFICIENTS_SIZE]; unsigned char *r = NULL, *s = NULL; size_t r_len, s_len, halflen = buflen/2; int rv; LOG_FUNC_CALLED(ctx); if (!buf || !buflen) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_copy_asn1_entry(c_asn1_sig_value, asn1_sig_value); sc_format_asn1_entry(asn1_sig_value + 0, asn1_sig_value_coefficients, NULL, 0); sc_copy_asn1_entry(c_asn1_sig_value_coefficients, asn1_sig_value_coefficients); sc_format_asn1_entry(asn1_sig_value_coefficients + 0, &r, &r_len, 0); sc_format_asn1_entry(asn1_sig_value_coefficients + 1, &s, &s_len, 0); rv = sc_asn1_decode(ctx, asn1_sig_value, in, inlen, NULL, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "ASN.1 decoding ECDSA-Sig-Value failed"); if (halflen < r_len || halflen < s_len) { rv = SC_ERROR_BUFFER_TOO_SMALL; goto err; } memset(buf, 0, buflen); memcpy(buf + (halflen - r_len), r, r_len); memcpy(buf + (buflen - s_len), s, s_len); sc_log(ctx, "r(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen, sc_dump_hex(buf, halflen)); sc_log(ctx, "s(%"SC_FORMAT_LEN_SIZE_T"u): %s", halflen, sc_dump_hex(buf + halflen, halflen)); rv = SC_SUCCESS; err: free(r); free(s); LOG_FUNC_RETURN(ctx, rv); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1064_0
crossvul-cpp_data_good_5662_0
/* * net/key/af_key.c An implementation of PF_KEYv2 sockets. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Authors: Maxim Giryaev <gem@asplinux.ru> * David S. Miller <davem@redhat.com> * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * Kazunori MIYAZAWA / USAGI Project <miyazawa@linux-ipv6.org> * Derek Atkins <derek@ihtfp.com> */ #include <linux/capability.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/socket.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/slab.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/xfrm.h> #include <net/sock.h> #define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x)) #define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x)) static int pfkey_net_id __read_mostly; struct netns_pfkey { /* List of all pfkey sockets. */ struct hlist_head table; atomic_t socks_nr; }; static DEFINE_MUTEX(pfkey_mutex); #define DUMMY_MARK 0 static struct xfrm_mark dummy_mark = {0, 0}; struct pfkey_sock { /* struct sock must be the first member of struct pfkey_sock */ struct sock sk; int registered; int promisc; struct { uint8_t msg_version; uint32_t msg_portid; int (*dump)(struct pfkey_sock *sk); void (*done)(struct pfkey_sock *sk); union { struct xfrm_policy_walk policy; struct xfrm_state_walk state; } u; struct sk_buff *skb; } dump; }; static inline struct pfkey_sock *pfkey_sk(struct sock *sk) { return (struct pfkey_sock *)sk; } static int pfkey_can_dump(const struct sock *sk) { if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf) return 1; return 0; } static void pfkey_terminate_dump(struct pfkey_sock *pfk) { if (pfk->dump.dump) { if (pfk->dump.skb) { kfree_skb(pfk->dump.skb); pfk->dump.skb = NULL; } pfk->dump.done(pfk); pfk->dump.dump = NULL; pfk->dump.done = NULL; } } static void pfkey_sock_destruct(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_terminate_dump(pfkey_sk(sk)); skb_queue_purge(&sk->sk_receive_queue); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive pfkey socket: %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); atomic_dec(&net_pfkey->socks_nr); } static const struct proto_ops pfkey_ops; static void pfkey_insert(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); mutex_lock(&pfkey_mutex); sk_add_node_rcu(sk, &net_pfkey->table); mutex_unlock(&pfkey_mutex); } static void pfkey_remove(struct sock *sk) { mutex_lock(&pfkey_mutex); sk_del_node_init_rcu(sk); mutex_unlock(&pfkey_mutex); } static struct proto key_proto = { .name = "KEY", .owner = THIS_MODULE, .obj_size = sizeof(struct pfkey_sock), }; static int pfkey_create(struct net *net, struct socket *sock, int protocol, int kern) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; int err; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (protocol != PF_KEY_V2) return -EPROTONOSUPPORT; err = -ENOMEM; sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto); if (sk == NULL) goto out; sock->ops = &pfkey_ops; sock_init_data(sock, sk); sk->sk_family = PF_KEY; sk->sk_destruct = pfkey_sock_destruct; atomic_inc(&net_pfkey->socks_nr); pfkey_insert(sk); return 0; out: return err; } static int pfkey_release(struct socket *sock) { struct sock *sk = sock->sk; if (!sk) return 0; pfkey_remove(sk); sock_orphan(sk); sock->sk = NULL; skb_queue_purge(&sk->sk_write_queue); synchronize_rcu(); sock_put(sk); return 0; } static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2, gfp_t allocation, struct sock *sk) { int err = -ENOBUFS; sock_hold(sk); if (*skb2 == NULL) { if (atomic_read(&skb->users) != 1) { *skb2 = skb_clone(skb, allocation); } else { *skb2 = skb; atomic_inc(&skb->users); } } if (*skb2 != NULL) { if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) { skb_set_owner_r(*skb2, sk); skb_queue_tail(&sk->sk_receive_queue, *skb2); sk->sk_data_ready(sk, (*skb2)->len); *skb2 = NULL; err = 0; } } sock_put(sk); return err; } /* Send SKB to all pfkey sockets matching selected criteria. */ #define BROADCAST_ALL 0 #define BROADCAST_ONE 1 #define BROADCAST_REGISTERED 2 #define BROADCAST_PROMISC_ONLY 4 static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation, int broadcast_flags, struct sock *one_sk, struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; struct hlist_node *node; struct sk_buff *skb2 = NULL; int err = -ESRCH; /* XXX Do we need something like netlink_overrun? I think * XXX PF_KEY socket apps will not mind current behavior. */ if (!skb) return -ENOMEM; rcu_read_lock(); sk_for_each_rcu(sk, node, &net_pfkey->table) { struct pfkey_sock *pfk = pfkey_sk(sk); int err2; /* Yes, it means that if you are meant to receive this * pfkey message you receive it twice as promiscuous * socket. */ if (pfk->promisc) pfkey_broadcast_one(skb, &skb2, allocation, sk); /* the exact target will be processed later */ if (sk == one_sk) continue; if (broadcast_flags != BROADCAST_ALL) { if (broadcast_flags & BROADCAST_PROMISC_ONLY) continue; if ((broadcast_flags & BROADCAST_REGISTERED) && !pfk->registered) continue; if (broadcast_flags & BROADCAST_ONE) continue; } err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk); /* Error is cleare after succecful sending to at least one * registered KM */ if ((broadcast_flags & BROADCAST_REGISTERED) && err) err = err2; } rcu_read_unlock(); if (one_sk != NULL) err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk); kfree_skb(skb2); kfree_skb(skb); return err; } static int pfkey_do_dump(struct pfkey_sock *pfk) { struct sadb_msg *hdr; int rc; rc = pfk->dump.dump(pfk); if (rc == -ENOBUFS) return 0; if (pfk->dump.skb) { if (!pfkey_can_dump(&pfk->sk)) return 0; hdr = (struct sadb_msg *) pfk->dump.skb->data; hdr->sadb_msg_seq = 0; hdr->sadb_msg_errno = rc; pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = NULL; } pfkey_terminate_dump(pfk); return rc; } static inline void pfkey_hdr_dup(struct sadb_msg *new, const struct sadb_msg *orig) { *new = *orig; } static int pfkey_error(const struct sadb_msg *orig, int err, struct sock *sk) { struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL); struct sadb_msg *hdr; if (!skb) return -ENOBUFS; /* Woe be to the platform trying to support PFKEY yet * having normal errnos outside the 1-255 range, inclusive. */ err = -err; if (err == ERESTARTSYS || err == ERESTARTNOHAND || err == ERESTARTNOINTR) err = EINTR; if (err >= 512) err = EINVAL; BUG_ON(err <= 0 || err >= 256); hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = (uint8_t) err; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static u8 sadb_ext_min_len[] = { [SADB_EXT_RESERVED] = (u8) 0, [SADB_EXT_SA] = (u8) sizeof(struct sadb_sa), [SADB_EXT_LIFETIME_CURRENT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_HARD] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_SOFT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_ADDRESS_SRC] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_DST] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_PROXY] = (u8) sizeof(struct sadb_address), [SADB_EXT_KEY_AUTH] = (u8) sizeof(struct sadb_key), [SADB_EXT_KEY_ENCRYPT] = (u8) sizeof(struct sadb_key), [SADB_EXT_IDENTITY_SRC] = (u8) sizeof(struct sadb_ident), [SADB_EXT_IDENTITY_DST] = (u8) sizeof(struct sadb_ident), [SADB_EXT_SENSITIVITY] = (u8) sizeof(struct sadb_sens), [SADB_EXT_PROPOSAL] = (u8) sizeof(struct sadb_prop), [SADB_EXT_SUPPORTED_AUTH] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SUPPORTED_ENCRYPT] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SPIRANGE] = (u8) sizeof(struct sadb_spirange), [SADB_X_EXT_KMPRIVATE] = (u8) sizeof(struct sadb_x_kmprivate), [SADB_X_EXT_POLICY] = (u8) sizeof(struct sadb_x_policy), [SADB_X_EXT_SA2] = (u8) sizeof(struct sadb_x_sa2), [SADB_X_EXT_NAT_T_TYPE] = (u8) sizeof(struct sadb_x_nat_t_type), [SADB_X_EXT_NAT_T_SPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_DPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_OA] = (u8) sizeof(struct sadb_address), [SADB_X_EXT_SEC_CTX] = (u8) sizeof(struct sadb_x_sec_ctx), [SADB_X_EXT_KMADDRESS] = (u8) sizeof(struct sadb_x_kmaddress), }; /* Verify sadb_address_{len,prefixlen} against sa_family. */ static int verify_address_len(const void *p) { const struct sadb_address *sp = p; const struct sockaddr *addr = (const struct sockaddr *)(sp + 1); const struct sockaddr_in *sin; #if IS_ENABLED(CONFIG_IPV6) const struct sockaddr_in6 *sin6; #endif int len; switch (addr->sa_family) { case AF_INET: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 32) return -EINVAL; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 128) return -EINVAL; break; #endif default: /* It is user using kernel to keep track of security * associations for another protocol, such as * OSPF/RSVP/RIPV2/MIP. It is user's job to verify * lengths. * * XXX Actually, association/policy database is not yet * XXX able to cope with arbitrary sockaddr families. * XXX When it can, remove this -EINVAL. -DaveM */ return -EINVAL; break; } return 0; } static inline int pfkey_sec_ctx_len(const struct sadb_x_sec_ctx *sec_ctx) { return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) + sec_ctx->sadb_x_ctx_len, sizeof(uint64_t)); } static inline int verify_sec_ctx_len(const void *p) { const struct sadb_x_sec_ctx *sec_ctx = p; int len = sec_ctx->sadb_x_ctx_len; if (len > PAGE_SIZE) return -EINVAL; len = pfkey_sec_ctx_len(sec_ctx); if (sec_ctx->sadb_x_sec_len != len) return -EINVAL; return 0; } static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(const struct sadb_x_sec_ctx *sec_ctx) { struct xfrm_user_sec_ctx *uctx = NULL; int ctx_size = sec_ctx->sadb_x_ctx_len; uctx = kmalloc((sizeof(*uctx)+ctx_size), GFP_KERNEL); if (!uctx) return NULL; uctx->len = pfkey_sec_ctx_len(sec_ctx); uctx->exttype = sec_ctx->sadb_x_sec_exttype; uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi; uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg; uctx->ctx_len = sec_ctx->sadb_x_ctx_len; memcpy(uctx + 1, sec_ctx + 1, uctx->ctx_len); return uctx; } static int present_and_same_family(const struct sadb_address *src, const struct sadb_address *dst) { const struct sockaddr *s_addr, *d_addr; if (!src || !dst) return 0; s_addr = (const struct sockaddr *)(src + 1); d_addr = (const struct sockaddr *)(dst + 1); if (s_addr->sa_family != d_addr->sa_family) return 0; if (s_addr->sa_family != AF_INET #if IS_ENABLED(CONFIG_IPV6) && s_addr->sa_family != AF_INET6 #endif ) return 0; return 1; } static int parse_exthdrs(struct sk_buff *skb, const struct sadb_msg *hdr, void **ext_hdrs) { const char *p = (char *) hdr; int len = skb->len; len -= sizeof(*hdr); p += sizeof(*hdr); while (len > 0) { const struct sadb_ext *ehdr = (const struct sadb_ext *) p; uint16_t ext_type; int ext_len; ext_len = ehdr->sadb_ext_len; ext_len *= sizeof(uint64_t); ext_type = ehdr->sadb_ext_type; if (ext_len < sizeof(uint64_t) || ext_len > len || ext_type == SADB_EXT_RESERVED) return -EINVAL; if (ext_type <= SADB_EXT_MAX) { int min = (int) sadb_ext_min_len[ext_type]; if (ext_len < min) return -EINVAL; if (ext_hdrs[ext_type-1] != NULL) return -EINVAL; if (ext_type == SADB_EXT_ADDRESS_SRC || ext_type == SADB_EXT_ADDRESS_DST || ext_type == SADB_EXT_ADDRESS_PROXY || ext_type == SADB_X_EXT_NAT_T_OA) { if (verify_address_len(p)) return -EINVAL; } if (ext_type == SADB_X_EXT_SEC_CTX) { if (verify_sec_ctx_len(p)) return -EINVAL; } ext_hdrs[ext_type-1] = (void *) p; } p += ext_len; len -= ext_len; } return 0; } static uint16_t pfkey_satype2proto(uint8_t satype) { switch (satype) { case SADB_SATYPE_UNSPEC: return IPSEC_PROTO_ANY; case SADB_SATYPE_AH: return IPPROTO_AH; case SADB_SATYPE_ESP: return IPPROTO_ESP; case SADB_X_SATYPE_IPCOMP: return IPPROTO_COMP; break; default: return 0; } /* NOTREACHED */ } static uint8_t pfkey_proto2satype(uint16_t proto) { switch (proto) { case IPPROTO_AH: return SADB_SATYPE_AH; case IPPROTO_ESP: return SADB_SATYPE_ESP; case IPPROTO_COMP: return SADB_X_SATYPE_IPCOMP; break; default: return 0; } /* NOTREACHED */ } /* BTW, this scheme means that there is no way with PFKEY2 sockets to * say specifically 'just raw sockets' as we encode them as 255. */ static uint8_t pfkey_proto_to_xfrm(uint8_t proto) { return proto == IPSEC_PROTO_ANY ? 0 : proto; } static uint8_t pfkey_proto_from_xfrm(uint8_t proto) { return proto ? proto : IPSEC_PROTO_ANY; } static inline int pfkey_sockaddr_len(sa_family_t family) { switch (family) { case AF_INET: return sizeof(struct sockaddr_in); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return sizeof(struct sockaddr_in6); #endif } return 0; } static int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr) { switch (sa->sa_family) { case AF_INET: xaddr->a4 = ((struct sockaddr_in *)sa)->sin_addr.s_addr; return AF_INET; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: memcpy(xaddr->a6, &((struct sockaddr_in6 *)sa)->sin6_addr, sizeof(struct in6_addr)); return AF_INET6; #endif } return 0; } static int pfkey_sadb_addr2xfrm_addr(const struct sadb_address *addr, xfrm_address_t *xaddr) { return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1), xaddr); } static struct xfrm_state *pfkey_xfrm_state_lookup(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs) { const struct sadb_sa *sa; const struct sadb_address *addr; uint16_t proto; unsigned short family; xfrm_address_t *xaddr; sa = ext_hdrs[SADB_EXT_SA - 1]; if (sa == NULL) return NULL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return NULL; /* sadb_address_len should be checked by caller */ addr = ext_hdrs[SADB_EXT_ADDRESS_DST - 1]; if (addr == NULL) return NULL; family = ((const struct sockaddr *)(addr + 1))->sa_family; switch (family) { case AF_INET: xaddr = (xfrm_address_t *)&((const struct sockaddr_in *)(addr + 1))->sin_addr; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: xaddr = (xfrm_address_t *)&((const struct sockaddr_in6 *)(addr + 1))->sin6_addr; break; #endif default: xaddr = NULL; } if (!xaddr) return NULL; return xfrm_state_lookup(net, DUMMY_MARK, xaddr, sa->sadb_sa_spi, proto, family); } #define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1))) static int pfkey_sockaddr_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family)); } static inline int pfkey_mode_from_xfrm(int mode) { switch(mode) { case XFRM_MODE_TRANSPORT: return IPSEC_MODE_TRANSPORT; case XFRM_MODE_TUNNEL: return IPSEC_MODE_TUNNEL; case XFRM_MODE_BEET: return IPSEC_MODE_BEET; default: return -1; } } static inline int pfkey_mode_to_xfrm(int mode) { switch(mode) { case IPSEC_MODE_ANY: /*XXX*/ case IPSEC_MODE_TRANSPORT: return XFRM_MODE_TRANSPORT; case IPSEC_MODE_TUNNEL: return XFRM_MODE_TUNNEL; case IPSEC_MODE_BEET: return XFRM_MODE_BEET; default: return -1; } } static unsigned int pfkey_sockaddr_fill(const xfrm_address_t *xaddr, __be16 port, struct sockaddr *sa, unsigned short family) { switch (family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)sa; sin->sin_family = AF_INET; sin->sin_port = port; sin->sin_addr.s_addr = xaddr->a4; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); return 32; } #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; sin6->sin6_family = AF_INET6; sin6->sin6_port = port; sin6->sin6_flowinfo = 0; sin6->sin6_addr = *(struct in6_addr *)xaddr->a6; sin6->sin6_scope_id = 0; return 128; } #endif } return 0; } static struct sk_buff *__pfkey_xfrm_state2msg(const struct xfrm_state *x, int add_keys, int hsc) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_lifetime *lifetime; struct sadb_address *addr; struct sadb_key *key; struct sadb_x_sa2 *sa2; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; int size; int auth_key_size = 0; int encrypt_key_size = 0; int sockaddr_size; struct xfrm_encap_tmpl *natt = NULL; int mode; /* address family check */ sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return ERR_PTR(-EINVAL); /* base, SA, (lifetime (HSC),) address(SD), (address(P),) key(AE), (identity(SD),) (sensitivity)> */ size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) + sizeof(struct sadb_lifetime) + ((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) + ((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) + sizeof(struct sadb_address)*2 + sockaddr_size*2 + sizeof(struct sadb_x_sa2); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } /* identity & sensitivity */ if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family)) size += sizeof(struct sadb_address) + sockaddr_size; if (add_keys) { if (x->aalg && x->aalg->alg_key_len) { auth_key_size = PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8); size += sizeof(struct sadb_key) + auth_key_size; } if (x->ealg && x->ealg->alg_key_len) { encrypt_key_size = PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8); size += sizeof(struct sadb_key) + encrypt_key_size; } } if (x->encap) natt = x->encap; if (natt && natt->encap_type) { size += sizeof(struct sadb_x_nat_t_type); size += sizeof(struct sadb_x_nat_t_port); size += sizeof(struct sadb_x_nat_t_port); } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ hdr->sadb_msg_len = size / sizeof(uint64_t); /* sa */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = x->props.replay_window; switch (x->km.state) { case XFRM_STATE_VALID: sa->sadb_sa_state = x->km.dying ? SADB_SASTATE_DYING : SADB_SASTATE_MATURE; break; case XFRM_STATE_ACQ: sa->sadb_sa_state = SADB_SASTATE_LARVAL; break; default: sa->sadb_sa_state = SADB_SASTATE_DEAD; break; } sa->sadb_sa_auth = 0; if (x->aalg) { struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0); sa->sadb_sa_auth = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_encrypt = 0; BUG_ON(x->ealg && x->calg); if (x->ealg) { struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0); sa->sadb_sa_encrypt = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } /* KAME compatible: sadb_sa_encrypt is overloaded with calg id */ if (x->calg) { struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0); sa->sadb_sa_encrypt = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_flags = 0; if (x->props.flags & XFRM_STATE_NOECN) sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN; if (x->props.flags & XFRM_STATE_DECAP_DSCP) sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP; if (x->props.flags & XFRM_STATE_NOPMTUDISC) sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC; /* hard time */ if (hsc & 2) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds; } /* soft time */ if (hsc & 1) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds; } /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = x->curlft.packets; lifetime->sadb_lifetime_bytes = x->curlft.bytes; lifetime->sadb_lifetime_addtime = x->curlft.add_time; lifetime->sadb_lifetime_usetime = x->curlft.use_time; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; /* "if the ports are non-zero, then the sadb_address_proto field, normally zero, MUST be filled in with the transport protocol's number." - RFC2367 */ addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family)) { addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY; addr->sadb_address_proto = pfkey_proto_from_xfrm(x->sel.proto); addr->sadb_address_prefixlen = x->sel.prefixlen_s; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport, (struct sockaddr *) (addr + 1), x->props.family); } /* auth key */ if (add_keys && auth_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+auth_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_AUTH; key->sadb_key_bits = x->aalg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8); } /* encrypt key */ if (add_keys && encrypt_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+encrypt_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + encrypt_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT; key->sadb_key_bits = x->ealg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->ealg->alg_key, (x->ealg->alg_key_len+7)/8); } /* sa */ sa2 = (struct sadb_x_sa2 *) skb_put(skb, sizeof(struct sadb_x_sa2)); sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t); sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2; if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) { kfree_skb(skb); return ERR_PTR(-EINVAL); } sa2->sadb_x_sa2_mode = mode; sa2->sadb_x_sa2_reserved1 = 0; sa2->sadb_x_sa2_reserved2 = 0; sa2->sadb_x_sa2_sequence = 0; sa2->sadb_x_sa2_reqid = x->props.reqid; if (natt && natt->encap_type) { struct sadb_x_nat_t_type *n_type; struct sadb_x_nat_t_port *n_port; /* type */ n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type)); n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t); n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE; n_type->sadb_x_nat_t_type_type = natt->encap_type; n_type->sadb_x_nat_t_type_reserved[0] = 0; n_type->sadb_x_nat_t_type_reserved[1] = 0; n_type->sadb_x_nat_t_type_reserved[2] = 0; /* source port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* dest port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = natt->encap_dport; n_port->sadb_x_nat_t_port_reserved = 0; } /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg(const struct xfrm_state *x) { struct sk_buff *skb; skb = __pfkey_xfrm_state2msg(x, 1, 3); return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg_expire(const struct xfrm_state *x, int hsc) { return __pfkey_xfrm_state2msg(x, 0, hsc); } static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct xfrm_state *x; const struct sadb_lifetime *lifetime; const struct sadb_sa *sa; const struct sadb_key *key; const struct sadb_x_sec_ctx *sec_ctx; uint16_t proto; int err; sa = ext_hdrs[SADB_EXT_SA - 1]; if (!sa || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_ESP && !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_AH && !ext_hdrs[SADB_EXT_KEY_AUTH-1]) return ERR_PTR(-EINVAL); if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] != !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) return ERR_PTR(-EINVAL); proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return ERR_PTR(-EINVAL); /* default error is no buffer space */ err = -ENOBUFS; /* RFC2367: Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message. SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state. Therefore, the sadb_sa_state field of all submitted SAs MUST be SADB_SASTATE_MATURE and the kernel MUST return an error if this is not true. However, KAME setkey always uses SADB_SASTATE_LARVAL. Hence, we have to _ignore_ sadb_sa_state, which is also reasonable. */ if (sa->sadb_sa_auth > SADB_AALG_MAX || (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP && sa->sadb_sa_encrypt > SADB_X_CALG_MAX) || sa->sadb_sa_encrypt > SADB_EALG_MAX) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; if (key != NULL && sa->sadb_sa_auth != SADB_X_AALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key != NULL && sa->sadb_sa_encrypt != SADB_EALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); x = xfrm_state_alloc(net); if (x == NULL) return ERR_PTR(-ENOBUFS); x->id.proto = proto; x->id.spi = sa->sadb_sa_spi; x->props.replay_window = sa->sadb_sa_replay; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN) x->props.flags |= XFRM_STATE_NOECN; if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP) x->props.flags |= XFRM_STATE_DECAP_DSCP; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC) x->props.flags |= XFRM_STATE_NOPMTUDISC; lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1]; if (lifetime != NULL) { x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1]; if (lifetime != NULL) { x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) goto out; err = security_xfrm_state_alloc(x, uctx); kfree(uctx); if (err) goto out; } key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; if (sa->sadb_sa_auth) { int keysize = 0; struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } if (key) keysize = (key->sadb_key_bits + 7) / 8; x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL); if (!x->aalg) goto out; strcpy(x->aalg->alg_name, a->name); x->aalg->alg_key_len = 0; if (key) { x->aalg->alg_key_len = key->sadb_key_bits; memcpy(x->aalg->alg_key, key+1, keysize); } x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits; x->props.aalgo = sa->sadb_sa_auth; /* x->algo.flags = sa->sadb_sa_flags; */ } if (sa->sadb_sa_encrypt) { if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) { struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL); if (!x->calg) goto out; strcpy(x->calg->alg_name, a->name); x->props.calgo = sa->sadb_sa_encrypt; } else { int keysize = 0; struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key) keysize = (key->sadb_key_bits + 7) / 8; x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL); if (!x->ealg) goto out; strcpy(x->ealg->alg_name, a->name); x->ealg->alg_key_len = 0; if (key) { x->ealg->alg_key_len = key->sadb_key_bits; memcpy(x->ealg->alg_key, key+1, keysize); } x->props.ealgo = sa->sadb_sa_encrypt; } } /* x->algo.flags = sa->sadb_sa_flags; */ x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1], &x->props.saddr); if (!x->props.family) { err = -EAFNOSUPPORT; goto out; } pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1], &x->id.daddr); if (ext_hdrs[SADB_X_EXT_SA2-1]) { const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1]; int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) { err = -EINVAL; goto out; } x->props.mode = mode; x->props.reqid = sa2->sadb_x_sa2_reqid; } if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) { const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]; /* Nobody uses this, but we try. */ x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr); x->sel.prefixlen_s = addr->sadb_address_prefixlen; } if (!x->sel.family) x->sel.family = x->props.family; if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) { const struct sadb_x_nat_t_type* n_type; struct xfrm_encap_tmpl *natt; x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL); if (!x->encap) goto out; natt = x->encap; n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]; natt->encap_type = n_type->sadb_x_nat_t_type_type; if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) { const struct sadb_x_nat_t_port *n_port = ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]; natt->encap_sport = n_port->sadb_x_nat_t_port_port; } if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) { const struct sadb_x_nat_t_port *n_port = ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]; natt->encap_dport = n_port->sadb_x_nat_t_port_port; } memset(&natt->encap_oa, 0, sizeof(natt->encap_oa)); } err = xfrm_init_state(x); if (err) goto out; x->km.seq = hdr->sadb_msg_seq; return x; out: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); return ERR_PTR(err); } static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { return -EOPNOTSUPP; } static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct sk_buff *resp_skb; struct sadb_x_sa2 *sa2; struct sadb_address *saddr, *daddr; struct sadb_msg *out_hdr; struct sadb_spirange *range; struct xfrm_state *x = NULL; int mode; int err; u32 min_spi, max_spi; u32 reqid; u8 proto; unsigned short family; xfrm_address_t *xsaddr = NULL, *xdaddr = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) { mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) return -EINVAL; reqid = sa2->sadb_x_sa2_reqid; } else { mode = 0; reqid = 0; } saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1]; daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1]; family = ((struct sockaddr *)(saddr + 1))->sa_family; switch (family) { case AF_INET: xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr; break; #endif } if (hdr->sadb_msg_seq) { x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x && !xfrm_addr_equal(&x->id.daddr, xdaddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, &dummy_mark, mode, reqid, proto, xdaddr, xsaddr, 1, family); if (x == NULL) return -ENOENT; min_spi = 0x100; max_spi = 0x0fffffff; range = ext_hdrs[SADB_EXT_SPIRANGE-1]; if (range) { min_spi = range->sadb_spirange_min; max_spi = range->sadb_spirange_max; } err = xfrm_alloc_spi(x, min_spi, max_spi); resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x); if (IS_ERR(resp_skb)) { xfrm_state_put(x); return PTR_ERR(resp_skb); } out_hdr = (struct sadb_msg *) resp_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GETSPI; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; xfrm_state_put(x); pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net); return 0; } static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8) return -EOPNOTSUPP; if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0) return 0; x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x == NULL) return 0; spin_lock_bh(&x->lock); if (x->km.state == XFRM_STATE_ACQ) { x->km.state = XFRM_STATE_ERROR; wake_up(&net->xfrm.km_waitq); } spin_unlock_bh(&x->lock); xfrm_state_put(x); return 0; } static inline int event2poltype(int event) { switch (event) { case XFRM_MSG_DELPOLICY: return SADB_X_SPDDELETE; case XFRM_MSG_NEWPOLICY: return SADB_X_SPDADD; case XFRM_MSG_UPDPOLICY: return SADB_X_SPDUPDATE; case XFRM_MSG_POLEXPIRE: // return SADB_X_SPDEXPIRE; default: pr_err("pfkey: Unknown policy event %d\n", event); break; } return 0; } static inline int event2keytype(int event) { switch (event) { case XFRM_MSG_DELSA: return SADB_DELETE; case XFRM_MSG_NEWSA: return SADB_ADD; case XFRM_MSG_UPDSA: return SADB_UPDATE; case XFRM_MSG_EXPIRE: return SADB_EXPIRE; default: pr_err("pfkey: Unknown SA event %d\n", event); break; } return 0; } /* ADD/UPD/DEL */ static int key_notify_sa(struct xfrm_state *x, const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = pfkey_xfrm_state2msg(x); if (IS_ERR(skb)) return PTR_ERR(skb); hdr = (struct sadb_msg *) skb->data; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = event2keytype(c->event); hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x)); return 0; } static int pfkey_add(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; int err; struct km_event c; x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs); if (IS_ERR(x)) return PTR_ERR(x); xfrm_state_hold(x); if (hdr->sadb_msg_type == SADB_ADD) err = xfrm_state_add(x); else err = xfrm_state_update(x); xfrm_audit_state_add(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } if (hdr->sadb_msg_type == SADB_ADD) c.event = XFRM_MSG_NEWSA; else c.event = XFRM_MSG_UPDSA; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static int pfkey_delete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; struct km_event c; int err; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; if ((err = security_xfrm_state_delete(x))) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.event = XFRM_MSG_DELSA; km_state_notify(x, &c); out: xfrm_audit_state_delete(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); xfrm_state_put(x); return err; } static int pfkey_get(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); __u8 proto; struct sk_buff *out_skb; struct sadb_msg *out_hdr; struct xfrm_state *x; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; out_skb = pfkey_xfrm_state2msg(x); proto = x->id.proto; xfrm_state_put(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GET; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static struct sk_buff *compose_sadb_supported(const struct sadb_msg *orig, gfp_t allocation) { struct sk_buff *skb; struct sadb_msg *hdr; int len, auth_len, enc_len, i; auth_len = xfrm_count_pfkey_auth_supported(); if (auth_len) { auth_len *= sizeof(struct sadb_alg); auth_len += sizeof(struct sadb_supported); } enc_len = xfrm_count_pfkey_enc_supported(); if (enc_len) { enc_len *= sizeof(struct sadb_alg); enc_len += sizeof(struct sadb_supported); } len = enc_len + auth_len + sizeof(struct sadb_msg); skb = alloc_skb(len + 16, allocation); if (!skb) goto out_put_algs; hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = 0; hdr->sadb_msg_len = len / sizeof(uint64_t); if (auth_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, auth_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = auth_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH; for (i = 0; ; i++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg->available) *ap++ = aalg->desc; } } if (enc_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, enc_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = enc_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT; for (i = 0; ; i++) { struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (ealg->available) *ap++ = ealg->desc; } } out_put_algs: return skb; } static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; } static int unicast_flush_resp(struct sock *sk, const struct sadb_msg *ihdr) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memcpy(hdr, ihdr, sizeof(struct sadb_msg)); hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); } static int key_notify_sa_flush(const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto); hdr->sadb_msg_type = SADB_FLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_flush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); unsigned int proto; struct km_event c; struct xfrm_audit audit_info; int err, err2; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_state_flush(net, proto, &audit_info); err2 = unicast_flush_resp(sk, hdr); if (err || err2) { if (err == -ESRCH) /* empty table - go quietly */ err = 0; return err ? err : err2; } c.data.proto = proto; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.event = XFRM_MSG_FLUSHSA; c.net = net; km_state_notify(NULL, &c); return 0; } static int dump_sa(struct xfrm_state *x, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_state2msg(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_DUMP; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_portid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sa(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk); } static void pfkey_dump_sa_done(struct pfkey_sock *pfk) { xfrm_state_walk_done(&pfk->dump.u.state); } static int pfkey_dump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { u8 proto; struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_portid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sa; pfk->dump.done = pfkey_dump_sa_done; xfrm_state_walk_init(&pfk->dump.u.state, proto); return pfkey_do_dump(pfk); } static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); int satype = hdr->sadb_msg_satype; bool reset_errno = false; if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) { reset_errno = true; if (satype != 0 && satype != 1) return -EINVAL; pfk->promisc = satype; } if (reset_errno && skb_cloned(skb)) skb = skb_copy(skb, GFP_KERNEL); else skb = skb_clone(skb, GFP_KERNEL); if (reset_errno && skb) { struct sadb_msg *new_hdr = (struct sadb_msg *) skb->data; new_hdr->sadb_msg_errno = 0; } pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk)); return 0; } static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr) { int i; u32 reqid = *(u32*)ptr; for (i=0; i<xp->xfrm_nr; i++) { if (xp->xfrm_vec[i].reqid == reqid) return -EEXIST; } return 0; } static u32 gen_reqid(struct net *net) { struct xfrm_policy_walk walk; u32 start; int rc; static u32 reqid = IPSEC_MANUAL_REQID_MAX; start = reqid; do { ++reqid; if (reqid == 0) reqid = IPSEC_MANUAL_REQID_MAX+1; xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN); rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid); xfrm_policy_walk_done(&walk); if (rc != -EEXIST) return reqid; } while (reqid != start); return 0; } static int parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq) { struct net *net = xp_net(xp); struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr; int mode; if (xp->xfrm_nr >= XFRM_MAX_DEPTH) return -ELOOP; if (rq->sadb_x_ipsecrequest_mode == 0) return -EINVAL; t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */ if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; t->mode = mode; if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE) t->optional = 1; else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) { t->reqid = rq->sadb_x_ipsecrequest_reqid; if (t->reqid > IPSEC_MANUAL_REQID_MAX) t->reqid = 0; if (!t->reqid && !(t->reqid = gen_reqid(net))) return -ENOBUFS; } /* addresses present only in tunnel mode */ if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (u8 *) (rq + 1); int family, socklen; family = pfkey_sockaddr_extract((struct sockaddr *)sa, &t->saddr); if (!family) return -EINVAL; socklen = pfkey_sockaddr_len(family); if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen), &t->id.daddr) != family) return -EINVAL; t->encap_family = family; } else t->encap_family = xp->family; /* No way to set this via kame pfkey */ t->allalgs = 1; xp->xfrm_nr++; return 0; } static int parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol) { int err; int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy); struct sadb_x_ipsecrequest *rq = (void*)(pol+1); if (pol->sadb_x_policy_len * 8 < sizeof(struct sadb_x_policy)) return -EINVAL; while (len >= sizeof(struct sadb_x_ipsecrequest)) { if ((err = parse_ipsecrequest(xp, rq)) < 0) return err; len -= rq->sadb_x_ipsecrequest_len; rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len); } return 0; } static inline int pfkey_xfrm_policy2sec_ctx_size(const struct xfrm_policy *xp) { struct xfrm_sec_ctx *xfrm_ctx = xp->security; if (xfrm_ctx) { int len = sizeof(struct sadb_x_sec_ctx); len += xfrm_ctx->ctx_len; return PFKEY_ALIGN8(len); } return 0; } static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp) { const struct xfrm_tmpl *t; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = 0; int i; for (i=0; i<xp->xfrm_nr; i++) { t = xp->xfrm_vec + i; socklen += pfkey_sockaddr_len(t->encap_family); } return sizeof(struct sadb_msg) + (sizeof(struct sadb_lifetime) * 3) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy) + (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) + (socklen * 2) + pfkey_xfrm_policy2sec_ctx_size(xp); } static struct sk_buff * pfkey_xfrm_policy2msg_prep(const struct xfrm_policy *xp) { struct sk_buff *skb; int size; size = pfkey_xfrm_policy2msg_size(xp); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); return skb; } static int pfkey_xfrm_policy2msg(struct sk_buff *skb, const struct xfrm_policy *xp, int dir) { struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_lifetime *lifetime; struct sadb_x_policy *pol; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int i; int size; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = pfkey_sockaddr_len(xp->family); size = pfkey_xfrm_policy2msg_size(xp); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_s; addr->sadb_address_reserved = 0; if (!pfkey_sockaddr_fill(&xp->selector.saddr, xp->selector.sport, (struct sockaddr *) (addr + 1), xp->family)) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_d; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport, (struct sockaddr *) (addr + 1), xp->family); /* hard time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds; /* soft time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds; /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = xp->curlft.packets; lifetime->sadb_lifetime_bytes = xp->curlft.bytes; lifetime->sadb_lifetime_addtime = xp->curlft.add_time; lifetime->sadb_lifetime_usetime = xp->curlft.use_time; pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD; if (xp->action == XFRM_POLICY_ALLOW) { if (xp->xfrm_nr) pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; else pol->sadb_x_policy_type = IPSEC_POLICY_NONE; } pol->sadb_x_policy_dir = dir+1; pol->sadb_x_policy_id = xp->index; pol->sadb_x_policy_priority = xp->priority; for (i=0; i<xp->xfrm_nr; i++) { const struct xfrm_tmpl *t = xp->xfrm_vec + i; struct sadb_x_ipsecrequest *rq; int req_size; int mode; req_size = sizeof(struct sadb_x_ipsecrequest); if (t->mode == XFRM_MODE_TUNNEL) { socklen = pfkey_sockaddr_len(t->encap_family); req_size += socklen * 2; } else { size -= 2*socklen; } rq = (void*)skb_put(skb, req_size); pol->sadb_x_policy_len += req_size/8; memset(rq, 0, sizeof(*rq)); rq->sadb_x_ipsecrequest_len = req_size; rq->sadb_x_ipsecrequest_proto = t->id.proto; if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0) return -EINVAL; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE; if (t->reqid) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE; if (t->optional) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE; rq->sadb_x_ipsecrequest_reqid = t->reqid; if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (void *)(rq + 1); pfkey_sockaddr_fill(&t->saddr, 0, (struct sockaddr *)sa, t->encap_family); pfkey_sockaddr_fill(&t->id.daddr, 0, (struct sockaddr *) (sa + socklen), t->encap_family); } } /* security context */ if ((xfrm_ctx = xp->security)) { int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp); sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size); sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_reserved = atomic_read(&xp->refcnt); return 0; } static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; if (c->data.byid && c->event == XFRM_MSG_DELPOLICY) out_hdr->sadb_msg_type = SADB_X_SPDDELETE2; else out_hdr->sadb_msg_type = event2poltype(c->event); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = c->seq; out_hdr->sadb_msg_pid = c->portid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp)); return 0; } static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); int err = 0; struct sadb_lifetime *lifetime; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC) return -EINVAL; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; xp = xfrm_policy_alloc(net, GFP_KERNEL); if (xp == NULL) return -ENOBUFS; xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->priority = pol->sadb_x_policy_priority; sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr); if (!xp->family) { err = -EINVAL; goto out; } xp->selector.family = xp->family; xp->selector.prefixlen_s = sa->sadb_address_prefixlen; xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.sport) xp->selector.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr); xp->selector.prefixlen_d = sa->sadb_address_prefixlen; /* Amusing, we set this twice. KAME apps appear to set same value * in both addresses. */ xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.dport) xp->selector.dport_mask = htons(0xffff); sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) { err = -ENOBUFS; goto out; } err = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (err) goto out; } xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) { xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) { xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (err = parse_ipsecrequests(xp, pol)) < 0) goto out; err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp, hdr->sadb_msg_type != SADB_X_SPDUPDATE); xfrm_audit_policy_add(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; if (hdr->sadb_msg_type == SADB_X_SPDUPDATE) c.event = XFRM_MSG_UPDPOLICY; else c.event = XFRM_MSG_NEWPOLICY; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); xfrm_pol_put(xp); return 0; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return err; } static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); int err; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct xfrm_selector sel; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *pol_ctx = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; memset(&sel, 0, sizeof(sel)); sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) return -ENOMEM; err = security_xfrm_policy_alloc(&pol_ctx, uctx); kfree(uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN, pol->sadb_x_policy_dir - 1, &sel, pol_ctx, 1, &err); security_xfrm_policy_free(pol_ctx); if (xp == NULL) return -ENOENT; xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.data.byid = 0; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); out: xfrm_pol_put(xp); return err; } static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, const struct sadb_msg *hdr, int dir) { int err; struct sk_buff *out_skb; struct sadb_msg *out_hdr; err = 0; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) { err = PTR_ERR(out_skb); goto out; } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) goto out; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = hdr->sadb_msg_type; out_hdr->sadb_msg_satype = 0; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp)); err = 0; out: return err; } #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_sockaddr_pair_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2); } static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len, xfrm_address_t *saddr, xfrm_address_t *daddr, u16 *family) { int af, socklen; if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family)) return -EINVAL; af = pfkey_sockaddr_extract(sa, saddr); if (!af) return -EINVAL; socklen = pfkey_sockaddr_len(af); if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen), daddr) != af) return -EINVAL; *family = af; return 0; } static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len, struct xfrm_migrate *m) { int err; struct sadb_x_ipsecrequest *rq2; int mode; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq1->sadb_x_ipsecrequest_len) return -EINVAL; /* old endoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1), rq1->sadb_x_ipsecrequest_len, &m->old_saddr, &m->old_daddr, &m->old_family); if (err) return err; rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len); len -= rq1->sadb_x_ipsecrequest_len; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq2->sadb_x_ipsecrequest_len) return -EINVAL; /* new endpoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1), rq2->sadb_x_ipsecrequest_len, &m->new_saddr, &m->new_daddr, &m->new_family); if (err) return err; if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto || rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode || rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid) return -EINVAL; m->proto = rq1->sadb_x_ipsecrequest_proto; if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; m->mode = mode; m->reqid = rq1->sadb_x_ipsecrequest_reqid; return ((int)(rq1->sadb_x_ipsecrequest_len + rq2->sadb_x_ipsecrequest_len)); } static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { int i, len, ret, err = -EINVAL; u8 dir; struct sadb_address *sa; struct sadb_x_kmaddress *kma; struct sadb_x_policy *pol; struct sadb_x_ipsecrequest *rq; struct xfrm_selector sel; struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress k; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1], ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) || !ext_hdrs[SADB_X_EXT_POLICY - 1]) { err = -EINVAL; goto out; } kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1]; pol = ext_hdrs[SADB_X_EXT_POLICY - 1]; if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) { err = -EINVAL; goto out; } if (kma) { /* convert sadb_x_kmaddress to xfrm_kmaddress */ k.reserved = kma->sadb_x_kmaddress_reserved; ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1), 8*(kma->sadb_x_kmaddress_len) - sizeof(*kma), &k.local, &k.remote, &k.family); if (ret < 0) { err = ret; goto out; } } dir = pol->sadb_x_policy_dir - 1; memset(&sel, 0, sizeof(sel)); /* set source address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1]; sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); /* set destination address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); rq = (struct sadb_x_ipsecrequest *)(pol + 1); /* extract ipsecrequests */ i = 0; len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy); while (len > 0 && i < XFRM_MAX_DEPTH) { ret = ipsecrequests_to_migrate(rq, len, &m[i]); if (ret < 0) { err = ret; goto out; } else { rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret); len -= ret; i++; } } if (!i || len > 0) { err = -EINVAL; goto out; } return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i, kma ? &k : NULL); out: return err; } #else static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { return -ENOPROTOOPT; } #endif static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); unsigned int dir; int err = 0, delete; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL) return -EINVAL; dir = xfrm_policy_id2dir(pol->sadb_x_policy_id); if (dir >= XFRM_POLICY_MAX) return -EINVAL; delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2); xp = xfrm_policy_byid(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN, dir, pol->sadb_x_policy_id, delete, &err); if (xp == NULL) return -ENOENT; if (delete) { xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.data.byid = 1; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, dir, &c); } else { err = key_pol_get_resp(sk, xp, hdr, dir); } out: xfrm_pol_put(xp); return err; } static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_X_SPDDUMP; out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_portid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sp(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk); } static void pfkey_dump_sp_done(struct pfkey_sock *pfk) { xfrm_policy_walk_done(&pfk->dump.u.policy); } static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_portid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sp; pfk->dump.done = pfkey_dump_sp_done; xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN); return pfkey_do_dump(pfk); } static int key_notify_policy_flush(const struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct km_event c; struct xfrm_audit audit_info; int err, err2; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info); err2 = unicast_flush_resp(sk, hdr); if (err || err2) { if (err == -ESRCH) /* empty table - old silent behavior */ return 0; return err; } c.data.type = XFRM_POLICY_TYPE_MAIN; c.event = XFRM_MSG_FLUSHPOLICY; c.portid = hdr->sadb_msg_pid; c.seq = hdr->sadb_msg_seq; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs); static pfkey_handler pfkey_funcs[SADB_MAX + 1] = { [SADB_RESERVED] = pfkey_reserved, [SADB_GETSPI] = pfkey_getspi, [SADB_UPDATE] = pfkey_add, [SADB_ADD] = pfkey_add, [SADB_DELETE] = pfkey_delete, [SADB_GET] = pfkey_get, [SADB_ACQUIRE] = pfkey_acquire, [SADB_REGISTER] = pfkey_register, [SADB_EXPIRE] = NULL, [SADB_FLUSH] = pfkey_flush, [SADB_DUMP] = pfkey_dump, [SADB_X_PROMISC] = pfkey_promisc, [SADB_X_PCHANGE] = NULL, [SADB_X_SPDUPDATE] = pfkey_spdadd, [SADB_X_SPDADD] = pfkey_spdadd, [SADB_X_SPDDELETE] = pfkey_spddelete, [SADB_X_SPDGET] = pfkey_spdget, [SADB_X_SPDACQUIRE] = NULL, [SADB_X_SPDDUMP] = pfkey_spddump, [SADB_X_SPDFLUSH] = pfkey_spdflush, [SADB_X_SPDSETIDX] = pfkey_spdadd, [SADB_X_SPDDELETE2] = pfkey_spdget, [SADB_X_MIGRATE] = pfkey_migrate, }; static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr) { void *ext_hdrs[SADB_EXT_MAX]; int err; pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_PROMISC_ONLY, NULL, sock_net(sk)); memset(ext_hdrs, 0, sizeof(ext_hdrs)); err = parse_exthdrs(skb, hdr, ext_hdrs); if (!err) { err = -EOPNOTSUPP; if (pfkey_funcs[hdr->sadb_msg_type]) err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs); } return err; } static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp) { struct sadb_msg *hdr = NULL; if (skb->len < sizeof(*hdr)) { *errp = -EMSGSIZE; } else { hdr = (struct sadb_msg *) skb->data; if (hdr->sadb_msg_version != PF_KEY_V2 || hdr->sadb_msg_reserved != 0 || (hdr->sadb_msg_type <= SADB_RESERVED || hdr->sadb_msg_type > SADB_MAX)) { hdr = NULL; *errp = -EINVAL; } else if (hdr->sadb_msg_len != (skb->len / sizeof(uint64_t)) || hdr->sadb_msg_len < (sizeof(struct sadb_msg) / sizeof(uint64_t))) { hdr = NULL; *errp = -EMSGSIZE; } else { *errp = 0; } } return hdr; } static inline int aalg_tmpl_set(const struct xfrm_tmpl *t, const struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->aalgos) * 8) return 0; return (t->aalgos >> id) & 1; } static inline int ealg_tmpl_set(const struct xfrm_tmpl *t, const struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->ealgos) * 8) return 0; return (t->ealgos >> id) & 1; } static int count_ah_combs(const struct xfrm_tmpl *t) { int i, sz = 0; for (i = 0; ; i++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } return sz + sizeof(struct sadb_prop); } static int count_esp_combs(const struct xfrm_tmpl *t) { int i, k, sz = 0; for (i = 0; ; i++) { const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } } return sz + sizeof(struct sadb_prop); } static void dump_ah_combs(struct sk_buff *skb, const struct xfrm_tmpl *t) { struct sadb_prop *p; int i; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i = 0; ; i++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) { struct sadb_comb *c; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static void dump_esp_combs(struct sk_buff *skb, const struct xfrm_tmpl *t) { struct sadb_prop *p; int i, k; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i=0; ; i++) { const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { struct sadb_comb *c; const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (!(aalg_tmpl_set(t, aalg) && aalg->available)) continue; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_encrypt = ealg->desc.sadb_alg_id; c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits; c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static int key_notify_policy_expire(struct xfrm_policy *xp, const struct km_event *c) { return 0; } static int key_notify_sa_expire(struct xfrm_state *x, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int hard; int hsc; hard = c->data.hard; if (hard) hsc = 2; else hsc = 1; out_skb = pfkey_xfrm_state2msg_expire(x, hsc); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; out_hdr->sadb_msg_type = SADB_EXPIRE; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = 0; out_hdr->sadb_msg_pid = 0; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); return 0; } static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = x ? xs_net(x) : c->net; struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); if (atomic_read(&net_pfkey->socks_nr) == 0) return 0; switch (c->event) { case XFRM_MSG_EXPIRE: return key_notify_sa_expire(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_NEWSA: case XFRM_MSG_UPDSA: return key_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return key_notify_sa_flush(c); case XFRM_MSG_NEWAE: /* not yet supported */ break; default: pr_err("pfkey: Unknown SA event %d\n", c->event); break; } return 0; } static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { if (xp && xp->type != XFRM_POLICY_TYPE_MAIN) return 0; switch (c->event) { case XFRM_MSG_POLEXPIRE: return key_notify_policy_expire(xp, c); case XFRM_MSG_DELPOLICY: case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: return key_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: if (c->data.type != XFRM_POLICY_TYPE_MAIN) break; return key_notify_policy_flush(c); default: pr_err("pfkey: Unknown policy event %d\n", c->event); break; } return 0; } static u32 get_acqseq(void) { u32 res; static atomic_t acqseq; do { res = atomic_inc_return(&acqseq); } while (!res); return res; } static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_x_policy *pol; int sockaddr_size; int size; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; size = sizeof(struct sadb_msg) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy); if (x->id.proto == IPPROTO_AH) size += count_ah_combs(t); else if (x->id.proto == IPPROTO_ESP) size += count_esp_combs(t); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_ACQUIRE; hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = XFRM_POLICY_OUT + 1; pol->sadb_x_policy_id = xp->index; /* Set sadb_comb's. */ if (x->id.proto == IPPROTO_AH) dump_ah_combs(skb, t); else if (x->id.proto == IPPROTO_ESP) dump_esp_combs(skb, t); /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_policy *xp; struct sadb_x_policy *pol = (struct sadb_x_policy*)data; struct sadb_x_sec_ctx *sec_ctx; switch (sk->sk_family) { case AF_INET: if (opt != IP_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: if (opt != IPV6_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(struct sadb_x_policy) || pol->sadb_x_policy_len*8 > len || pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS || (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND)) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; xp->family = sk->sk_family; xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (*dir = parse_ipsecrequests(xp, pol)) < 0) goto out; /* security context too */ if (len >= (pol->sadb_x_policy_len*8 + sizeof(struct sadb_x_sec_ctx))) { char *p = (char *)pol; struct xfrm_user_sec_ctx *uctx; p += pol->sadb_x_policy_len*8; sec_ctx = (struct sadb_x_sec_ctx *)p; if (len < pol->sadb_x_policy_len*8 + sec_ctx->sadb_x_sec_len) { *dir = -EINVAL; goto out; } if ((*dir = verify_sec_ctx_len(p))) goto out; uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); *dir = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (*dir) goto out; } *dir = pol->sadb_x_policy_dir-1; return xp; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_address *addr; struct sadb_x_nat_t_port *n_port; int sockaddr_size; int size; __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0); struct xfrm_encap_tmpl *natt = NULL; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; if (!satype) return -EINVAL; if (!x->encap) return -EINVAL; natt = x->encap; /* Build an SADB_X_NAT_T_NEW_MAPPING message: * * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) | * ADDRESS_DST (new addr) | NAT_T_DPORT (new port) */ size = sizeof(struct sadb_msg) + sizeof(struct sadb_sa) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + (sizeof(struct sadb_x_nat_t_port) * 2); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING; hdr->sadb_msg_satype = satype; hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* SA */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = 0; sa->sadb_sa_state = 0; sa->sadb_sa_auth = 0; sa->sadb_sa_encrypt = 0; sa->sadb_sa_flags = 0; /* ADDRESS_SRC (old addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_SPORT (old port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* ADDRESS_DST (new addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(ipaddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_DPORT (new port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = sport; n_port->sadb_x_nat_t_port_reserved = 0; return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } #ifdef CONFIG_NET_KEY_MIGRATE static int set_sadb_address(struct sk_buff *skb, int sasize, int type, const struct xfrm_selector *sel) { struct sadb_address *addr; addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize); addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8; addr->sadb_address_exttype = type; addr->sadb_address_proto = sel->proto; addr->sadb_address_reserved = 0; switch (type) { case SADB_EXT_ADDRESS_SRC: addr->sadb_address_prefixlen = sel->prefixlen_s; pfkey_sockaddr_fill(&sel->saddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; case SADB_EXT_ADDRESS_DST: addr->sadb_address_prefixlen = sel->prefixlen_d; pfkey_sockaddr_fill(&sel->daddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; default: return -EINVAL; } return 0; } static int set_sadb_kmaddress(struct sk_buff *skb, const struct xfrm_kmaddress *k) { struct sadb_x_kmaddress *kma; u8 *sa; int family = k->family; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = (sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(family)); kma = (struct sadb_x_kmaddress *)skb_put(skb, size_req); memset(kma, 0, size_req); kma->sadb_x_kmaddress_len = size_req / 8; kma->sadb_x_kmaddress_exttype = SADB_X_EXT_KMADDRESS; kma->sadb_x_kmaddress_reserved = k->reserved; sa = (u8 *)(kma + 1); if (!pfkey_sockaddr_fill(&k->local, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(&k->remote, 0, (struct sockaddr *)(sa+socklen), family)) return -EINVAL; return 0; } static int set_ipsecrequest(struct sk_buff *skb, uint8_t proto, uint8_t mode, int level, uint32_t reqid, uint8_t family, const xfrm_address_t *src, const xfrm_address_t *dst) { struct sadb_x_ipsecrequest *rq; u8 *sa; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(family); rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req); memset(rq, 0, size_req); rq->sadb_x_ipsecrequest_len = size_req; rq->sadb_x_ipsecrequest_proto = proto; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = level; rq->sadb_x_ipsecrequest_reqid = reqid; sa = (u8 *) (rq + 1); if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family)) return -EINVAL; return 0; } #endif #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_bundles, const struct xfrm_kmaddress *k) { int i; int sasize_sel; int size = 0; int size_pol = 0; struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_x_policy *pol; const struct xfrm_migrate *mp; if (type != XFRM_POLICY_TYPE_MAIN) return 0; if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH) return -EINVAL; if (k != NULL) { /* addresses for KM */ size += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(k->family)); } /* selector */ sasize_sel = pfkey_sockaddr_size(sel->family); if (!sasize_sel) return -EINVAL; size += (sizeof(struct sadb_address) + sasize_sel) * 2; /* policy info */ size_pol += sizeof(struct sadb_x_policy); /* ipsecrequests */ for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->old_family); /* new locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->new_family); } size += sizeof(struct sadb_msg) + size_pol; /* alloc buffer */ skb = alloc_skb(size, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_MIGRATE; hdr->sadb_msg_satype = pfkey_proto2satype(m->proto); hdr->sadb_msg_len = size / 8; hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = 0; hdr->sadb_msg_pid = 0; /* Addresses to be used by KM for negotiation, if ext is available */ if (k != NULL && (set_sadb_kmaddress(skb, k) < 0)) goto err; /* selector src */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel); /* selector dst */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel); /* policy information */ pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = size_pol / 8; pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = dir + 1; pol->sadb_x_policy_id = 0; pol->sadb_x_policy_priority = 0; for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old ipsecrequest */ int mode = pfkey_mode_from_xfrm(mp->mode); if (mode < 0) goto err; if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->old_family, &mp->old_saddr, &mp->old_daddr) < 0) goto err; /* new ipsecrequest */ if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->new_family, &mp->new_saddr, &mp->new_daddr) < 0) goto err; } /* broadcast migrate message to sockets */ pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net); return 0; err: kfree_skb(skb); return -EINVAL; } #else static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_bundles, const struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif static int pfkey_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct sk_buff *skb = NULL; struct sadb_msg *hdr = NULL; int err; err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) goto out; err = -EMSGSIZE; if ((unsigned int)len > sk->sk_sndbuf - 32) goto out; err = -ENOBUFS; skb = alloc_skb(len, GFP_KERNEL); if (skb == NULL) goto out; err = -EFAULT; if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) goto out; hdr = pfkey_get_base_msg(skb, &err); if (!hdr) goto out; mutex_lock(&xfrm_cfg_mutex); err = pfkey_process(sk, skb, hdr); mutex_unlock(&xfrm_cfg_mutex); out: if (err && hdr && pfkey_error(hdr, err, sk) == 0) err = 0; kfree_skb(skb); return err ? : len; } static int pfkey_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *skb; int copied, err; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT)) goto out; msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_ts_and_drops(msg, sk, skb); err = (flags & MSG_TRUNC) ? skb->len : copied; if (pfk->dump.dump != NULL && 3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) pfkey_do_dump(pfk); out_free: skb_free_datagram(sk, skb); out: return err; } static const struct proto_ops pfkey_ops = { .family = PF_KEY, .owner = THIS_MODULE, /* Operations that make no sense on pfkey sockets. */ .bind = sock_no_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, /* Now the operations that really occur. */ .release = pfkey_release, .poll = datagram_poll, .sendmsg = pfkey_sendmsg, .recvmsg = pfkey_recvmsg, }; static const struct net_proto_family pfkey_family_ops = { .family = PF_KEY, .create = pfkey_create, .owner = THIS_MODULE, }; #ifdef CONFIG_PROC_FS static int pfkey_seq_show(struct seq_file *f, void *v) { struct sock *s = sk_entry(v); if (v == SEQ_START_TOKEN) seq_printf(f ,"sk RefCnt Rmem Wmem User Inode\n"); else seq_printf(f, "%pK %-6d %-6u %-6u %-6u %-6lu\n", s, atomic_read(&s->sk_refcnt), sk_rmem_alloc_get(s), sk_wmem_alloc_get(s), from_kuid_munged(seq_user_ns(f), sock_i_uid(s)), sock_i_ino(s) ); return 0; } static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos) __acquires(rcu) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); rcu_read_lock(); return seq_hlist_start_head_rcu(&net_pfkey->table, *ppos); } static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); return seq_hlist_next_rcu(v, &net_pfkey->table, ppos); } static void pfkey_seq_stop(struct seq_file *f, void *v) __releases(rcu) { rcu_read_unlock(); } static const struct seq_operations pfkey_seq_ops = { .start = pfkey_seq_start, .next = pfkey_seq_next, .stop = pfkey_seq_stop, .show = pfkey_seq_show, }; static int pfkey_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &pfkey_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations pfkey_proc_ops = { .open = pfkey_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init pfkey_init_proc(struct net *net) { struct proc_dir_entry *e; e = proc_create("pfkey", 0, net->proc_net, &pfkey_proc_ops); if (e == NULL) return -ENOMEM; return 0; } static void __net_exit pfkey_exit_proc(struct net *net) { remove_proc_entry("pfkey", net->proc_net); } #else static inline int pfkey_init_proc(struct net *net) { return 0; } static inline void pfkey_exit_proc(struct net *net) { } #endif static struct xfrm_mgr pfkeyv2_mgr = { .id = "pfkeyv2", .notify = pfkey_send_notify, .acquire = pfkey_send_acquire, .compile_policy = pfkey_compile_policy, .new_mapping = pfkey_send_new_mapping, .notify_policy = pfkey_send_policy_notify, .migrate = pfkey_send_migrate, }; static int __net_init pfkey_net_init(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); int rv; INIT_HLIST_HEAD(&net_pfkey->table); atomic_set(&net_pfkey->socks_nr, 0); rv = pfkey_init_proc(net); return rv; } static void __net_exit pfkey_net_exit(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_exit_proc(net); BUG_ON(!hlist_empty(&net_pfkey->table)); } static struct pernet_operations pfkey_net_ops = { .init = pfkey_net_init, .exit = pfkey_net_exit, .id = &pfkey_net_id, .size = sizeof(struct netns_pfkey), }; static void __exit ipsec_pfkey_exit(void) { xfrm_unregister_km(&pfkeyv2_mgr); sock_unregister(PF_KEY); unregister_pernet_subsys(&pfkey_net_ops); proto_unregister(&key_proto); } static int __init ipsec_pfkey_init(void) { int err = proto_register(&key_proto, 0); if (err != 0) goto out; err = register_pernet_subsys(&pfkey_net_ops); if (err != 0) goto out_unregister_key_proto; err = sock_register(&pfkey_family_ops); if (err != 0) goto out_unregister_pernet; err = xfrm_register_km(&pfkeyv2_mgr); if (err != 0) goto out_sock_unregister; out: return err; out_sock_unregister: sock_unregister(PF_KEY); out_unregister_pernet: unregister_pernet_subsys(&pfkey_net_ops); out_unregister_key_proto: proto_unregister(&key_proto); goto out; } module_init(ipsec_pfkey_init); module_exit(ipsec_pfkey_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_KEY);
./CrossVul/dataset_final_sorted/CWE-119/c/good_5662_0
crossvul-cpp_data_bad_5502_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Generic socket support routines. Memory allocators, socket lock/release * handler for protocols to use and generic option handler. * * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Fixes: * Alan Cox : Numerous verify_area() problems * Alan Cox : Connecting on a connecting socket * now returns an error for tcp. * Alan Cox : sock->protocol is set correctly. * and is not sometimes left as 0. * Alan Cox : connect handles icmp errors on a * connect properly. Unfortunately there * is a restart syscall nasty there. I * can't match BSD without hacking the C * library. Ideas urgently sought! * Alan Cox : Disallow bind() to addresses that are * not ours - especially broadcast ones!! * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, * instead they leave that for the DESTROY timer. * Alan Cox : Clean up error flag in accept * Alan Cox : TCP ack handling is buggy, the DESTROY timer * was buggy. Put a remove_sock() in the handler * for memory when we hit 0. Also altered the timer * code. The ACK stuff can wait and needs major * TCP layer surgery. * Alan Cox : Fixed TCP ack bug, removed remove sock * and fixed timer/inet_bh race. * Alan Cox : Added zapped flag for TCP * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... * Rick Sladkey : Relaxed UDP rules for matching packets. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support * Pauline Middelink : identd support * Alan Cox : Fixed connect() taking signals I think. * Alan Cox : SO_LINGER supported * Alan Cox : Error reporting fixes * Anonymous : inet_create tidied up (sk->reuse setting) * Alan Cox : inet sockets don't set sk->type! * Alan Cox : Split socket option code * Alan Cox : Callbacks * Alan Cox : Nagle flag for Charles & Johannes stuff * Alex : Removed restriction on inet fioctl * Alan Cox : Splitting INET from NET core * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code * Alan Cox : Split IP from generic code * Alan Cox : New kfree_skbmem() * Alan Cox : Make SO_DEBUG superuser only. * Alan Cox : Allow anyone to clear SO_DEBUG * (compatibility fix) * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. * Alan Cox : Allocator for a socket is settable. * Alan Cox : SO_ERROR includes soft errors. * Alan Cox : Allow NULL arguments on some SO_ opts * Alan Cox : Generic socket allocation to make hooks * easier (suggested by Craig Metz). * Michael Pall : SO_ERROR returns positive errno again * Steve Whitehouse: Added default destructor to free * protocol private data. * Steve Whitehouse: Added various other default routines * common to several socket families. * Chris Evans : Call suser() check last on F_SETOWN * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() * Andi Kleen : Fix write_space callback * Chris Evans : Security fixes - signedness again * Arnaldo C. Melo : cleanups, use skb_queue_purge * * To Fix: * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/capability.h> #include <linux/errno.h> #include <linux/errqueue.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/user_namespace.h> #include <linux/static_key.h> #include <linux/memcontrol.h> #include <linux/prefetch.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/request_sock.h> #include <net/sock.h> #include <linux/net_tstamp.h> #include <net/xfrm.h> #include <linux/ipsec.h> #include <net/cls_cgroup.h> #include <net/netprio_cgroup.h> #include <linux/sock_diag.h> #include <linux/filter.h> #include <net/sock_reuseport.h> #include <trace/events/sock.h> #ifdef CONFIG_INET #include <net/tcp.h> #endif #include <net/busy_poll.h> static DEFINE_MUTEX(proto_list_mutex); static LIST_HEAD(proto_list); /** * sk_ns_capable - General socket capability test * @sk: Socket to use a capability on or through * @user_ns: The user namespace of the capability to use * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in the user * namespace @user_ns. */ bool sk_ns_capable(const struct sock *sk, struct user_namespace *user_ns, int cap) { return file_ns_capable(sk->sk_socket->file, user_ns, cap) && ns_capable(user_ns, cap); } EXPORT_SYMBOL(sk_ns_capable); /** * sk_capable - Socket global capability test * @sk: Socket to use a capability on or through * @cap: The global capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in all user * namespaces. */ bool sk_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, &init_user_ns, cap); } EXPORT_SYMBOL(sk_capable); /** * sk_net_capable - Network namespace socket capability test * @sk: Socket to use a capability on or through * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was created * and the current process has the capability @cap over the network namespace * the socket is a member of. */ bool sk_net_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, sock_net(sk)->user_ns, cap); } EXPORT_SYMBOL(sk_net_capable); /* * Each address family might have different locking rules, so we have * one slock key per address family: */ static struct lock_class_key af_family_keys[AF_MAX]; static struct lock_class_key af_family_slock_keys[AF_MAX]; /* * Make lock validator output more readable. (we pre-construct these * strings build-time, so that runtime initialization of socket * locks is fast): */ static const char *const af_family_key_strings[AF_MAX+1] = { "sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" , "sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK", "sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" , "sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" , "sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" , "sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" , "sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" , "sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" , "sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" , "sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" , "sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" , "sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" , "sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" , "sk_lock-AF_NFC" , "sk_lock-AF_VSOCK" , "sk_lock-AF_KCM" , "sk_lock-AF_MAX" }; static const char *const af_family_slock_key_strings[AF_MAX+1] = { "slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" , "slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK", "slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" , "slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" , "slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" , "slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" , "slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" , "slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" , "slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" , "slock-27" , "slock-28" , "slock-AF_CAN" , "slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" , "slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" , "slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" , "slock-AF_NFC" , "slock-AF_VSOCK" ,"slock-AF_KCM" , "slock-AF_MAX" }; static const char *const af_family_clock_key_strings[AF_MAX+1] = { "clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" , "clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK", "clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" , "clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" , "clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" , "clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" , "clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" , "clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" , "clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" , "clock-27" , "clock-28" , "clock-AF_CAN" , "clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" , "clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" , "clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" , "clock-AF_NFC" , "clock-AF_VSOCK" , "clock-AF_KCM" , "clock-AF_MAX" }; /* * sk_callback_lock locking rules are per-address-family, * so split the lock classes by using a per-AF key: */ static struct lock_class_key af_callback_keys[AF_MAX]; /* Take into consideration the size of the struct sk_buff overhead in the * determination of these values, since that is non-constant across * platforms. This makes socket queueing behavior and performance * not depend upon such differences. */ #define _SK_MEM_PACKETS 256 #define _SK_MEM_OVERHEAD SKB_TRUESIZE(256) #define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) #define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) /* Run time adjustable parameters. */ __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX; EXPORT_SYMBOL(sysctl_wmem_max); __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX; EXPORT_SYMBOL(sysctl_rmem_max); __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX; /* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512); EXPORT_SYMBOL(sysctl_optmem_max); int sysctl_tstamp_allow_data __read_mostly = 1; struct static_key memalloc_socks = STATIC_KEY_INIT_FALSE; EXPORT_SYMBOL_GPL(memalloc_socks); /** * sk_set_memalloc - sets %SOCK_MEMALLOC * @sk: socket to set it on * * Set %SOCK_MEMALLOC on a socket for access to emergency reserves. * It's the responsibility of the admin to adjust min_free_kbytes * to meet the requirements */ void sk_set_memalloc(struct sock *sk) { sock_set_flag(sk, SOCK_MEMALLOC); sk->sk_allocation |= __GFP_MEMALLOC; static_key_slow_inc(&memalloc_socks); } EXPORT_SYMBOL_GPL(sk_set_memalloc); void sk_clear_memalloc(struct sock *sk) { sock_reset_flag(sk, SOCK_MEMALLOC); sk->sk_allocation &= ~__GFP_MEMALLOC; static_key_slow_dec(&memalloc_socks); /* * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward * progress of swapping. SOCK_MEMALLOC may be cleared while * it has rmem allocations due to the last swapfile being deactivated * but there is a risk that the socket is unusable due to exceeding * the rmem limits. Reclaim the reserves and obey rmem limits again. */ sk_mem_reclaim(sk); } EXPORT_SYMBOL_GPL(sk_clear_memalloc); int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb) { int ret; unsigned long pflags = current->flags; /* these should have been dropped before queueing */ BUG_ON(!sock_flag(sk, SOCK_MEMALLOC)); current->flags |= PF_MEMALLOC; ret = sk->sk_backlog_rcv(sk, skb); tsk_restore_flags(current, pflags, PF_MEMALLOC); return ret; } EXPORT_SYMBOL(__sk_backlog_rcv); static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen) { struct timeval tv; if (optlen < sizeof(tv)) return -EINVAL; if (copy_from_user(&tv, optval, sizeof(tv))) return -EFAULT; if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) return -EDOM; if (tv.tv_sec < 0) { static int warned __read_mostly; *timeo_p = 0; if (warned < 10 && net_ratelimit()) { warned++; pr_info("%s: `%s' (pid %d) tries to set negative timeout\n", __func__, current->comm, task_pid_nr(current)); } return 0; } *timeo_p = MAX_SCHEDULE_TIMEOUT; if (tv.tv_sec == 0 && tv.tv_usec == 0) return 0; if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1)) *timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ); return 0; } static void sock_warn_obsolete_bsdism(const char *name) { static int warned; static char warncomm[TASK_COMM_LEN]; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n", warncomm, name); warned++; } } static bool sock_needs_netstamp(const struct sock *sk) { switch (sk->sk_family) { case AF_UNSPEC: case AF_UNIX: return false; default: return true; } } static void sock_disable_timestamp(struct sock *sk, unsigned long flags) { if (sk->sk_flags & flags) { sk->sk_flags &= ~flags; if (sock_needs_netstamp(sk) && !(sk->sk_flags & SK_FLAGS_TIMESTAMP)) net_disable_timestamp(); } } int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) { atomic_inc(&sk->sk_drops); trace_sock_rcvqueue_full(sk, skb); return -ENOMEM; } if (!sk_rmem_schedule(sk, skb, skb->truesize)) { atomic_inc(&sk->sk_drops); return -ENOBUFS; } skb->dev = NULL; skb_set_owner_r(skb, sk); /* we escape from rcu protected region, make sure we dont leak * a norefcounted dst */ skb_dst_force(skb); spin_lock_irqsave(&list->lock, flags); sock_skb_set_dropcount(sk, skb); __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; } EXPORT_SYMBOL(__sock_queue_rcv_skb); int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; err = sk_filter(sk, skb); if (err) return err; return __sock_queue_rcv_skb(sk, skb); } EXPORT_SYMBOL(sock_queue_rcv_skb); int __sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested, unsigned int trim_cap, bool refcounted) { int rc = NET_RX_SUCCESS; if (sk_filter_trim_cap(sk, skb, trim_cap)) goto discard_and_relse; skb->dev = NULL; if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { atomic_inc(&sk->sk_drops); goto discard_and_relse; } if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: if (refcounted) sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } EXPORT_SYMBOL(__sk_receive_skb); struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_tx_queue_clear(sk); RCU_INIT_POINTER(sk->sk_dst_cache, NULL); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(__sk_dst_check); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(sk_dst_check); static int sock_setbindtodevice(struct sock *sk, char __user *optval, int optlen) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; int index; /* Sorry... */ ret = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_RAW)) goto out; ret = -EINVAL; if (optlen < 0) goto out; /* Bind this socket to a particular device like "eth0", * as specified in the passed interface name. If the * name is "" or the option length is zero the socket * is not bound. */ if (optlen > IFNAMSIZ - 1) optlen = IFNAMSIZ - 1; memset(devname, 0, sizeof(devname)); ret = -EFAULT; if (copy_from_user(devname, optval, optlen)) goto out; index = 0; if (devname[0] != '\0') { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, devname); if (dev) index = dev->ifindex; rcu_read_unlock(); ret = -ENODEV; if (!dev) goto out; } lock_sock(sk); sk->sk_bound_dev_if = index; sk_dst_reset(sk); release_sock(sk); ret = 0; out: #endif return ret; } static int sock_getbindtodevice(struct sock *sk, char __user *optval, int __user *optlen, int len) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; if (sk->sk_bound_dev_if == 0) { len = 0; goto zero; } ret = -EINVAL; if (len < IFNAMSIZ) goto out; ret = netdev_get_name(net, devname, sk->sk_bound_dev_if); if (ret) goto out; len = strlen(devname) + 1; ret = -EFAULT; if (copy_to_user(optval, devname, len)) goto out; zero: ret = -EFAULT; if (put_user(len, optlen)) goto out; ret = 0; out: #endif return ret; } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } bool sk_mc_loop(struct sock *sk) { if (dev_recursion_level()) return false; if (!sk) return true; switch (sk->sk_family) { case AF_INET: return inet_sk(sk)->mc_loop; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return inet6_sk(sk)->mc_loop; #endif } WARN_ON(1); return true; } EXPORT_SYMBOL(sk_mc_loop); /* * This is meant for all protocols to use and covers goings on * at the socket level. Everything here is generic. */ int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } EXPORT_SYMBOL(sock_setsockopt); static void cred_to_ucred(struct pid *pid, const struct cred *cred, struct ucred *ucred) { ucred->pid = pid_vnr(pid); ucred->uid = ucred->gid = -1; if (cred) { struct user_namespace *current_ns = current_user_ns(); ucred->uid = from_kuid_munged(current_ns, cred->euid); ucred->gid = from_kgid_munged(current_ns, cred->egid); } } int sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; memset(&v, 0, sizeof(v)); switch (optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_REUSEPORT: v.val = sk->sk_reuseport; break; case SO_KEEPALIVE: v.val = sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_PROTOCOL: v.val = sk->sk_protocol; break; case SO_DOMAIN: v.val = sk->sk_family; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val == 0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check_tx; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPING: v.val = sk->sk_tsflags; break; case SO_RCVTIMEO: lv = sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv = sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val = 1; break; case SO_PASSCRED: v.val = !!test_bit(SOCK_PASSCRED, &sock->flags); break; case SO_PEERCRED: { struct ucred peercred; if (len > sizeof(peercred)) len = sizeof(peercred); cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred); if (copy_to_user(optval, &peercred, len)) return -EFAULT; goto lenout; } case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = !!test_bit(SOCK_PASSSEC, &sock->flags); break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; case SO_RXQ_OVFL: v.val = sock_flag(sk, SOCK_RXQ_OVFL); break; case SO_WIFI_STATUS: v.val = sock_flag(sk, SOCK_WIFI_STATUS); break; case SO_PEEK_OFF: if (!sock->ops->set_peek_off) return -EOPNOTSUPP; v.val = sk->sk_peek_off; break; case SO_NOFCS: v.val = sock_flag(sk, SOCK_NOFCS); break; case SO_BINDTODEVICE: return sock_getbindtodevice(sk, optval, optlen, len); case SO_GET_FILTER: len = sk_get_filter(sk, (struct sock_filter __user *)optval, len); if (len < 0) return len; goto lenout; case SO_LOCK_FILTER: v.val = sock_flag(sk, SOCK_FILTER_LOCKED); break; case SO_BPF_EXTENSIONS: v.val = bpf_tell_extensions(); break; case SO_SELECT_ERR_QUEUE: v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: v.val = sk->sk_ll_usec; break; #endif case SO_MAX_PACING_RATE: v.val = sk->sk_max_pacing_rate; break; case SO_INCOMING_CPU: v.val = sk->sk_incoming_cpu; break; default: /* We implement the SO_SNDLOWAT etc to not be settable * (1003.1g 7). */ return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } /* * Initialize an sk_lock. * * (We also register the sk_lock with the lock validator.) */ static inline void sock_lock_init(struct sock *sk) { sock_lock_init_class_and_name(sk, af_family_slock_key_strings[sk->sk_family], af_family_slock_keys + sk->sk_family, af_family_key_strings[sk->sk_family], af_family_keys + sk->sk_family); } /* * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, * even temporarly, because of RCU lookups. sk_node should also be left as is. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end */ static void sock_copy(struct sock *nsk, const struct sock *osk) { #ifdef CONFIG_SECURITY_NETWORK void *sptr = nsk->sk_security; #endif memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end)); #ifdef CONFIG_SECURITY_NETWORK nsk->sk_security = sptr; security_sk_clone(osk, nsk); #endif } static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, int family) { struct sock *sk; struct kmem_cache *slab; slab = prot->slab; if (slab != NULL) { sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); if (!sk) return sk; if (priority & __GFP_ZERO) sk_prot_clear_nulls(sk, prot->obj_size); } else sk = kmalloc(prot->obj_size, priority); if (sk != NULL) { kmemcheck_annotate_bitfield(sk, flags); if (security_sk_alloc(sk, family, priority)) goto out_free; if (!try_module_get(prot->owner)) goto out_free_sec; sk_tx_queue_clear(sk); } return sk; out_free_sec: security_sk_free(sk); out_free: if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); return NULL; } static void sk_prot_free(struct proto *prot, struct sock *sk) { struct kmem_cache *slab; struct module *owner; owner = prot->owner; slab = prot->slab; cgroup_sk_free(&sk->sk_cgrp_data); mem_cgroup_sk_free(sk); security_sk_free(sk); if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); module_put(owner); } /** * sk_alloc - All socket objects are allocated here * @net: the applicable net namespace * @family: protocol family * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * @prot: struct proto associated with this new sock instance * @kern: is this to be a kernel socket? */ struct sock *sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot, int kern) { struct sock *sk; sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); if (sk) { sk->sk_family = family; /* * See comment in struct sock definition to understand * why we need sk_prot_creator -acme */ sk->sk_prot = sk->sk_prot_creator = prot; sock_lock_init(sk); sk->sk_net_refcnt = kern ? 0 : 1; if (likely(sk->sk_net_refcnt)) get_net(net); sock_net_set(sk, net); atomic_set(&sk->sk_wmem_alloc, 1); mem_cgroup_sk_alloc(sk); cgroup_sk_alloc(&sk->sk_cgrp_data); sock_update_classid(&sk->sk_cgrp_data); sock_update_netprioidx(&sk->sk_cgrp_data); } return sk; } EXPORT_SYMBOL(sk_alloc); /* Sockets having SOCK_RCU_FREE will call this function after one RCU * grace period. This is the case for UDP sockets and TCP listeners. */ static void __sk_destruct(struct rcu_head *head) { struct sock *sk = container_of(head, struct sock, sk_rcu); struct sk_filter *filter; if (sk->sk_destruct) sk->sk_destruct(sk); filter = rcu_dereference_check(sk->sk_filter, atomic_read(&sk->sk_wmem_alloc) == 0); if (filter) { sk_filter_uncharge(sk, filter); RCU_INIT_POINTER(sk->sk_filter, NULL); } if (rcu_access_pointer(sk->sk_reuseport_cb)) reuseport_detach_sock(sk); sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); if (atomic_read(&sk->sk_omem_alloc)) pr_debug("%s: optmem leakage (%d bytes) detected\n", __func__, atomic_read(&sk->sk_omem_alloc)); if (sk->sk_peer_cred) put_cred(sk->sk_peer_cred); put_pid(sk->sk_peer_pid); if (likely(sk->sk_net_refcnt)) put_net(sock_net(sk)); sk_prot_free(sk->sk_prot_creator, sk); } void sk_destruct(struct sock *sk) { if (sock_flag(sk, SOCK_RCU_FREE)) call_rcu(&sk->sk_rcu, __sk_destruct); else __sk_destruct(&sk->sk_rcu); } static void __sk_free(struct sock *sk) { if (unlikely(sock_diag_has_destroy_listeners(sk) && sk->sk_net_refcnt)) sock_diag_broadcast_destroy(sk); else sk_destruct(sk); } void sk_free(struct sock *sk) { /* * We subtract one from sk_wmem_alloc and can know if * some packets are still in some tx queue. * If not null, sock_wfree() will call __sk_free(sk) later */ if (atomic_dec_and_test(&sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sk_free); /** * sk_clone_lock - clone a socket, and lock its clone * @sk: the socket to clone * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority) { struct sock *newsk; bool is_charged = true; newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family); if (newsk != NULL) { struct sk_filter *filter; sock_copy(newsk, sk); /* SANITY */ if (likely(newsk->sk_net_refcnt)) get_net(sock_net(newsk)); sk_node_init(&newsk->sk_node); sock_lock_init(newsk); bh_lock_sock(newsk); newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; newsk->sk_backlog.len = 0; atomic_set(&newsk->sk_rmem_alloc, 0); /* * sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */ atomic_set(&newsk->sk_wmem_alloc, 1); atomic_set(&newsk->sk_omem_alloc, 0); skb_queue_head_init(&newsk->sk_receive_queue); skb_queue_head_init(&newsk->sk_write_queue); rwlock_init(&newsk->sk_callback_lock); lockdep_set_class_and_name(&newsk->sk_callback_lock, af_callback_keys + newsk->sk_family, af_family_clock_key_strings[newsk->sk_family]); newsk->sk_dst_cache = NULL; newsk->sk_wmem_queued = 0; newsk->sk_forward_alloc = 0; atomic_set(&newsk->sk_drops, 0); newsk->sk_send_head = NULL; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; sock_reset_flag(newsk, SOCK_DONE); skb_queue_head_init(&newsk->sk_error_queue); filter = rcu_dereference_protected(newsk->sk_filter, 1); if (filter != NULL) /* though it's an empty new sock, the charging may fail * if sysctl_optmem_max was changed between creation of * original socket and cloning */ is_charged = sk_filter_charge(newsk, filter); if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) { /* It is still raw copy of parent, so invalidate * destructor and make plain sk_free() */ newsk->sk_destruct = NULL; bh_unlock_sock(newsk); sk_free(newsk); newsk = NULL; goto out; } RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL); newsk->sk_err = 0; newsk->sk_err_soft = 0; newsk->sk_priority = 0; newsk->sk_incoming_cpu = raw_smp_processor_id(); atomic64_set(&newsk->sk_cookie, 0); mem_cgroup_sk_alloc(newsk); cgroup_sk_alloc(&newsk->sk_cgrp_data); /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&newsk->sk_refcnt, 2); /* * Increment the counter in the same struct proto as the master * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that * is the same as sk->sk_prot->socks, as this field was copied * with memcpy). * * This _changes_ the previous behaviour, where * tcp_create_openreq_child always was incrementing the * equivalent to tcp_prot->socks (inet_sock_nr), so this have * to be taken into account in all callers. -acme */ sk_refcnt_debug_inc(newsk); sk_set_socket(newsk, NULL); newsk->sk_wq = NULL; if (newsk->sk_prot->sockets_allocated) sk_sockets_allocated_inc(newsk); if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); } out: return newsk; } EXPORT_SYMBOL_GPL(sk_clone_lock); void sk_setup_caps(struct sock *sk, struct dst_entry *dst) { u32 max_segs = 1; sk_dst_set(sk, dst); sk->sk_route_caps = dst->dev->features; if (sk->sk_route_caps & NETIF_F_GSO) sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; sk->sk_route_caps &= ~sk->sk_route_nocaps; if (sk_can_gso(sk)) { if (dst->header_len) { sk->sk_route_caps &= ~NETIF_F_GSO_MASK; } else { sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; sk->sk_gso_max_size = dst->dev->gso_max_size; max_segs = max_t(u32, dst->dev->gso_max_segs, 1); } } sk->sk_gso_max_segs = max_segs; } EXPORT_SYMBOL_GPL(sk_setup_caps); /* * Simple resource managers for sockets. */ /* * Write buffer destructor automatically called from kfree_skb. */ void sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { /* * Keep a reference on sk_wmem_alloc, this will be released * after sk_write_space() call */ atomic_sub(len - 1, &sk->sk_wmem_alloc); sk->sk_write_space(sk); len = 1; } /* * if sk_wmem_alloc reaches 0, we must finish what sk_free() * could not do because of in-flight packets */ if (atomic_sub_and_test(len, &sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sock_wfree); /* This variant of sock_wfree() is used by TCP, * since it sets SOCK_USE_WRITE_QUEUE. */ void __sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; if (atomic_sub_and_test(skb->truesize, &sk->sk_wmem_alloc)) __sk_free(sk); } void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) { skb_orphan(skb); skb->sk = sk; #ifdef CONFIG_INET if (unlikely(!sk_fullsock(sk))) { skb->destructor = sock_edemux; sock_hold(sk); return; } #endif skb->destructor = sock_wfree; skb_set_hash_from_sk(skb, sk); /* * We used to take a refcount on sk, but following operation * is enough to guarantee sk_free() wont free this sock until * all in-flight packets are completed */ atomic_add(skb->truesize, &sk->sk_wmem_alloc); } EXPORT_SYMBOL(skb_set_owner_w); /* This helper is used by netem, as it can hold packets in its * delay queue. We want to allow the owner socket to send more * packets, as if they were already TX completed by a typical driver. * But we also want to keep skb->sk set because some packet schedulers * rely on it (sch_fq for example). So we set skb->truesize to a small * amount (1) and decrease sk_wmem_alloc accordingly. */ void skb_orphan_partial(struct sk_buff *skb) { /* If this skb is a TCP pure ACK or already went here, * we have nothing to do. 2 is already a very small truesize. */ if (skb->truesize <= 2) return; /* TCP stack sets skb->ooo_okay based on sk_wmem_alloc, * so we do not completely orphan skb, but transfert all * accounted bytes but one, to avoid unexpected reorders. */ if (skb->destructor == sock_wfree #ifdef CONFIG_INET || skb->destructor == tcp_wfree #endif ) { atomic_sub(skb->truesize - 1, &skb->sk->sk_wmem_alloc); skb->truesize = 1; } else { skb_orphan(skb); } } EXPORT_SYMBOL(skb_orphan_partial); /* * Read buffer destructor automatically called from kfree_skb. */ void sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; atomic_sub(len, &sk->sk_rmem_alloc); sk_mem_uncharge(sk, len); } EXPORT_SYMBOL(sock_rfree); /* * Buffer destructor for skbs that are not used directly in read or write * path, e.g. for error handler skbs. Automatically called from kfree_skb. */ void sock_efree(struct sk_buff *skb) { sock_put(skb->sk); } EXPORT_SYMBOL(sock_efree); kuid_t sock_i_uid(struct sock *sk) { kuid_t uid; read_lock_bh(&sk->sk_callback_lock); uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID; read_unlock_bh(&sk->sk_callback_lock); return uid; } EXPORT_SYMBOL(sock_i_uid); unsigned long sock_i_ino(struct sock *sk) { unsigned long ino; read_lock_bh(&sk->sk_callback_lock); ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0; read_unlock_bh(&sk->sk_callback_lock); return ino; } EXPORT_SYMBOL(sock_i_ino); /* * Allocate a skb from the socket's send buffer. */ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_w(skb, sk); return skb; } } return NULL; } EXPORT_SYMBOL(sock_wmalloc); /* * Allocate a memory block from the socket's option memory buffer. */ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) { if ((unsigned int)size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) { void *mem; /* First do the add, to avoid the race if kmalloc * might sleep. */ atomic_add(size, &sk->sk_omem_alloc); mem = kmalloc(size, priority); if (mem) return mem; atomic_sub(size, &sk->sk_omem_alloc); } return NULL; } EXPORT_SYMBOL(sock_kmalloc); /* Free an option memory block. Note, we actually want the inline * here as this allows gcc to detect the nullify and fold away the * condition entirely. */ static inline void __sock_kfree_s(struct sock *sk, void *mem, int size, const bool nullify) { if (WARN_ON_ONCE(!mem)) return; if (nullify) kzfree(mem); else kfree(mem); atomic_sub(size, &sk->sk_omem_alloc); } void sock_kfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, false); } EXPORT_SYMBOL(sock_kfree_s); void sock_kzfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, true); } EXPORT_SYMBOL(sock_kzfree_s); /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. I think, these locks should be removed for datagram sockets. */ static long sock_wait_for_wmem(struct sock *sk, long timeo) { DEFINE_WAIT(wait); sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); for (;;) { if (!timeo) break; if (signal_pending(current)) break; set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) break; if (sk->sk_shutdown & SEND_SHUTDOWN) break; if (sk->sk_err) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Generic send/receive buffer handlers */ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode, int max_page_order) { struct sk_buff *skb; long timeo; int err; timeo = sock_sndtimeo(sk, noblock); for (;;) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (sk_wmem_alloc_get(sk) < sk->sk_sndbuf) break; sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb = alloc_skb_with_frags(header_len, data_len, max_page_order, errcode, sk->sk_allocation); if (skb) skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } EXPORT_SYMBOL(sock_alloc_send_pskb); struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode) { return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0); } EXPORT_SYMBOL(sock_alloc_send_skb); int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg, struct sockcm_cookie *sockc) { u32 tsflags; switch (cmsg->cmsg_type) { case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; sockc->mark = *(u32 *)CMSG_DATA(cmsg); break; case SO_TIMESTAMPING: if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; tsflags = *(u32 *)CMSG_DATA(cmsg); if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) return -EINVAL; sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; sockc->tsflags |= tsflags; break; /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ case SCM_RIGHTS: case SCM_CREDENTIALS: break; default: return -EINVAL; } return 0; } EXPORT_SYMBOL(__sock_cmsg_send); int sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct sockcm_cookie *sockc) { struct cmsghdr *cmsg; int ret; for_each_cmsghdr(cmsg, msg) { if (!CMSG_OK(msg, cmsg)) return -EINVAL; if (cmsg->cmsg_level != SOL_SOCKET) continue; ret = __sock_cmsg_send(sk, msg, cmsg, sockc); if (ret) return ret; } return 0; } EXPORT_SYMBOL(sock_cmsg_send); /* On 32bit arches, an skb frag is limited to 2^15 */ #define SKB_FRAG_PAGE_ORDER get_order(32768) /** * skb_page_frag_refill - check that a page_frag contains enough room * @sz: minimum size of the fragment we want to get * @pfrag: pointer to page_frag * @gfp: priority for memory allocation * * Note: While this allocator tries to use high order pages, there is * no guarantee that allocations succeed. Therefore, @sz MUST be * less or equal than PAGE_SIZE. */ bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) { if (pfrag->page) { if (page_ref_count(pfrag->page) == 1) { pfrag->offset = 0; return true; } if (pfrag->offset + sz <= pfrag->size) return true; put_page(pfrag->page); } pfrag->offset = 0; if (SKB_FRAG_PAGE_ORDER) { /* Avoid direct reclaim but allow kswapd to wake */ pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY, SKB_FRAG_PAGE_ORDER); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER; return true; } } pfrag->page = alloc_page(gfp); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE; return true; } return false; } EXPORT_SYMBOL(skb_page_frag_refill); bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag) { if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation))) return true; sk_enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); return false; } EXPORT_SYMBOL(sk_page_frag_refill); static void __lock_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, TASK_UNINTERRUPTIBLE); spin_unlock_bh(&sk->sk_lock.slock); schedule(); spin_lock_bh(&sk->sk_lock.slock); if (!sock_owned_by_user(sk)) break; } finish_wait(&sk->sk_lock.wq, &wait); } static void __release_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { struct sk_buff *skb, *next; while ((skb = sk->sk_backlog.head) != NULL) { sk->sk_backlog.head = sk->sk_backlog.tail = NULL; spin_unlock_bh(&sk->sk_lock.slock); do { next = skb->next; prefetch(next); WARN_ON_ONCE(skb_dst_is_noref(skb)); skb->next = NULL; sk_backlog_rcv(sk, skb); cond_resched(); skb = next; } while (skb != NULL); spin_lock_bh(&sk->sk_lock.slock); } /* * Doing the zeroing here guarantee we can not loop forever * while a wild producer attempts to flood us. */ sk->sk_backlog.len = 0; } void __sk_flush_backlog(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); __release_sock(sk); spin_unlock_bh(&sk->sk_lock.slock); } /** * sk_wait_data - wait for data to arrive at sk_receive_queue * @sk: sock to wait on * @timeo: for how long * @skb: last skb seen on sk_receive_queue * * Now socket state including sk->sk_err is changed only under lock, * hence we may omit checks after joining wait queue. * We check receive queue before schedule() only as optimization; * it is very likely that release_sock() added new data. */ int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb); sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); finish_wait(sk_sleep(sk), &wait); return rc; } EXPORT_SYMBOL(sk_wait_data); /** * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated * @sk: socket * @size: memory size to allocate * @kind: allocation type * * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means * rmem allocation. This function assumes that protocols which have * memory_pressure use sk_wmem_queued as write buffer accounting. */ int __sk_mem_schedule(struct sock *sk, int size, int kind) { struct proto *prot = sk->sk_prot; int amt = sk_mem_pages(size); long allocated; sk->sk_forward_alloc += amt * SK_MEM_QUANTUM; allocated = sk_memory_allocated_add(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg && !mem_cgroup_charge_skmem(sk->sk_memcg, amt)) goto suppress_allocation; /* Under limit. */ if (allocated <= sk_prot_mem_limits(sk, 0)) { sk_leave_memory_pressure(sk); return 1; } /* Under pressure. */ if (allocated > sk_prot_mem_limits(sk, 1)) sk_enter_memory_pressure(sk); /* Over hard limit. */ if (allocated > sk_prot_mem_limits(sk, 2)) goto suppress_allocation; /* guarantee minimum buffer size under pressure */ if (kind == SK_MEM_RECV) { if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0]) return 1; } else { /* SK_MEM_SEND */ if (sk->sk_type == SOCK_STREAM) { if (sk->sk_wmem_queued < prot->sysctl_wmem[0]) return 1; } else if (atomic_read(&sk->sk_wmem_alloc) < prot->sysctl_wmem[0]) return 1; } if (sk_has_memory_pressure(sk)) { int alloc; if (!sk_under_memory_pressure(sk)) return 1; alloc = sk_sockets_allocated_read_positive(sk); if (sk_prot_mem_limits(sk, 2) > alloc * sk_mem_pages(sk->sk_wmem_queued + atomic_read(&sk->sk_rmem_alloc) + sk->sk_forward_alloc)) return 1; } suppress_allocation: if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { sk_stream_moderate_sndbuf(sk); /* Fail only if socket is _under_ its sndbuf. * In this case we cannot block, so that we have to fail. */ if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) return 1; } trace_sock_exceed_buf_limit(sk, prot, allocated); /* Alas. Undo changes. */ sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM; sk_memory_allocated_sub(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amt); return 0; } EXPORT_SYMBOL(__sk_mem_schedule); /** * __sk_mem_reclaim - reclaim memory_allocated * @sk: socket * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple) */ void __sk_mem_reclaim(struct sock *sk, int amount) { amount >>= SK_MEM_QUANTUM_SHIFT; sk_memory_allocated_sub(sk, amount); sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT; if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amount); if (sk_under_memory_pressure(sk) && (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) sk_leave_memory_pressure(sk); } EXPORT_SYMBOL(__sk_mem_reclaim); int sk_set_peek_off(struct sock *sk, int val) { if (val < 0) return -EINVAL; sk->sk_peek_off = val; return 0; } EXPORT_SYMBOL_GPL(sk_set_peek_off); /* * Set of default routines for initialising struct proto_ops when * the protocol does not support a particular function. In certain * cases where it makes no sense for a protocol to have a "do nothing" * function, some default processing is provided. */ int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_bind); int sock_no_connect(struct socket *sock, struct sockaddr *saddr, int len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_connect); int sock_no_socketpair(struct socket *sock1, struct socket *sock2) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_socketpair); int sock_no_accept(struct socket *sock, struct socket *newsock, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_accept); int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getname); unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt) { return 0; } EXPORT_SYMBOL(sock_no_poll); int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_ioctl); int sock_no_listen(struct socket *sock, int backlog) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_listen); int sock_no_shutdown(struct socket *sock, int how) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_shutdown); int sock_no_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_setsockopt); int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getsockopt); int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_sendmsg); int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_recvmsg); int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) { /* Mirror missing mmap method error code */ return -ENODEV; } EXPORT_SYMBOL(sock_no_mmap); ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { ssize_t res; struct msghdr msg = {.msg_flags = flags}; struct kvec iov; char *kaddr = kmap(page); iov.iov_base = kaddr + offset; iov.iov_len = size; res = kernel_sendmsg(sock, &msg, &iov, 1, size); kunmap(page); return res; } EXPORT_SYMBOL(sock_no_sendpage); /* * Default Socket Callbacks */ static void sock_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); rcu_read_unlock(); } static void sock_def_error_report(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_poll(&wq->wait, POLLERR); sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); rcu_read_unlock(); } static void sock_def_readable(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static void sock_def_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); /* Do not wake up a writer until he can make "significant" * progress. --DaveM */ if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) { wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLWRNORM | POLLWRBAND); /* Should agree with poll, otherwise some programs break */ if (sock_writeable(sk)) sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void sock_def_destruct(struct sock *sk) { } void sk_send_sigurg(struct sock *sk) { if (sk->sk_socket && sk->sk_socket->file) if (send_sigurg(&sk->sk_socket->file->f_owner)) sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); } EXPORT_SYMBOL(sk_send_sigurg); void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires) { if (!mod_timer(timer, expires)) sock_hold(sk); } EXPORT_SYMBOL(sk_reset_timer); void sk_stop_timer(struct sock *sk, struct timer_list* timer) { if (del_timer(timer)) __sock_put(sk); } EXPORT_SYMBOL(sk_stop_timer); void sock_init_data(struct socket *sock, struct sock *sk) { skb_queue_head_init(&sk->sk_receive_queue); skb_queue_head_init(&sk->sk_write_queue); skb_queue_head_init(&sk->sk_error_queue); sk->sk_send_head = NULL; init_timer(&sk->sk_timer); sk->sk_allocation = GFP_KERNEL; sk->sk_rcvbuf = sysctl_rmem_default; sk->sk_sndbuf = sysctl_wmem_default; sk->sk_state = TCP_CLOSE; sk_set_socket(sk, sock); sock_set_flag(sk, SOCK_ZAPPED); if (sock) { sk->sk_type = sock->type; sk->sk_wq = sock->wq; sock->sk = sk; } else sk->sk_wq = NULL; rwlock_init(&sk->sk_callback_lock); lockdep_set_class_and_name(&sk->sk_callback_lock, af_callback_keys + sk->sk_family, af_family_clock_key_strings[sk->sk_family]); sk->sk_state_change = sock_def_wakeup; sk->sk_data_ready = sock_def_readable; sk->sk_write_space = sock_def_write_space; sk->sk_error_report = sock_def_error_report; sk->sk_destruct = sock_def_destruct; sk->sk_frag.page = NULL; sk->sk_frag.offset = 0; sk->sk_peek_off = -1; sk->sk_peer_pid = NULL; sk->sk_peer_cred = NULL; sk->sk_write_pending = 0; sk->sk_rcvlowat = 1; sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_stamp = ktime_set(-1L, 0); #ifdef CONFIG_NET_RX_BUSY_POLL sk->sk_napi_id = 0; sk->sk_ll_usec = sysctl_net_busy_read; #endif sk->sk_max_pacing_rate = ~0U; sk->sk_pacing_rate = ~0U; sk->sk_incoming_cpu = -1; /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&sk->sk_refcnt, 1); atomic_set(&sk->sk_drops, 0); } EXPORT_SYMBOL(sock_init_data); void lock_sock_nested(struct sock *sk, int subclass) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_lock.owned) __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); local_bh_enable(); } EXPORT_SYMBOL(lock_sock_nested); void release_sock(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_backlog.tail) __release_sock(sk); /* Warning : release_cb() might need to release sk ownership, * ie call sock_release_ownership(sk) before us. */ if (sk->sk_prot->release_cb) sk->sk_prot->release_cb(sk); sock_release_ownership(sk); if (waitqueue_active(&sk->sk_lock.wq)) wake_up(&sk->sk_lock.wq); spin_unlock_bh(&sk->sk_lock.slock); } EXPORT_SYMBOL(release_sock); /** * lock_sock_fast - fast version of lock_sock * @sk: socket * * This version should be used for very small section, where process wont block * return false if fast path is taken * sk_lock.slock locked, owned = 0, BH disabled * return true if slow path is taken * sk_lock.slock unlocked, owned = 1, BH enabled */ bool lock_sock_fast(struct sock *sk) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (!sk->sk_lock.owned) /* * Note : We must disable BH */ return false; __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_); local_bh_enable(); return true; } EXPORT_SYMBOL(lock_sock_fast); int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct timeval tv; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); tv = ktime_to_timeval(sk->sk_stamp); if (tv.tv_sec == -1) return -ENOENT; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestamp); int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct timespec ts; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); ts = ktime_to_timespec(sk->sk_stamp); if (ts.tv_sec == -1) return -ENOENT; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestampns); void sock_enable_timestamp(struct sock *sk, int flag) { if (!sock_flag(sk, flag)) { unsigned long previous_flags = sk->sk_flags; sock_set_flag(sk, flag); /* * we just set one of the two flags which require net * time stamping, but time stamping might have been on * already because of the other one */ if (sock_needs_netstamp(sk) && !(previous_flags & SK_FLAGS_TIMESTAMP)) net_enable_timestamp(); } } int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, int level, int type) { struct sock_exterr_skb *serr; struct sk_buff *skb; int copied, err; err = -EAGAIN; skb = sock_dequeue_err_skb(sk); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_msg(skb, 0, msg, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); serr = SKB_EXT_ERR(skb); put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee); msg->msg_flags |= MSG_ERRQUEUE; err = copied; out_free_skb: kfree_skb(skb); out: return err; } EXPORT_SYMBOL(sock_recv_errqueue); /* * Get a socket option on an socket. * * FIX: POSIX 1003.1g is very ambiguous here. It states that * asynchronous errors should be reported by getsockopt. We assume * this means if you specify SO_ERROR (otherwise whats the point of it). */ int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_getsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_getsockopt != NULL) return sk->sk_prot->compat_getsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_getsockopt); #endif int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(sock_common_recvmsg); /* * Set socket options on an inet socket. */ int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_setsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_setsockopt != NULL) return sk->sk_prot->compat_setsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_setsockopt); #endif void sk_common_release(struct sock *sk) { if (sk->sk_prot->destroy) sk->sk_prot->destroy(sk); /* * Observation: when sock_common_release is called, processes have * no access to socket. But net still has. * Step one, detach it from networking: * * A. Remove from hash tables. */ sk->sk_prot->unhash(sk); /* * In this point socket cannot receive new packets, but it is possible * that some packets are in flight because some CPU runs receiver and * did hash table lookup before we unhashed socket. They will achieve * receive queue and will be purged by socket destructor. * * Also we still have packets pending on receive queue and probably, * our own packets waiting in device queues. sock_destroy will drain * receive queue, but transmitted packets will delay socket destruction * until the last reference will be released. */ sock_orphan(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); if (sk->sk_frag.page) { put_page(sk->sk_frag.page); sk->sk_frag.page = NULL; } sock_put(sk); } EXPORT_SYMBOL(sk_common_release); #ifdef CONFIG_PROC_FS #define PROTO_INUSE_NR 64 /* should be enough for the first time */ struct prot_inuse { int val[PROTO_INUSE_NR]; }; static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); #ifdef CONFIG_NET_NS void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(net->core.inuse->val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu_ptr(net->core.inuse, cpu)->val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); static int __net_init sock_inuse_init_net(struct net *net) { net->core.inuse = alloc_percpu(struct prot_inuse); return net->core.inuse ? 0 : -ENOMEM; } static void __net_exit sock_inuse_exit_net(struct net *net) { free_percpu(net->core.inuse); } static struct pernet_operations net_inuse_ops = { .init = sock_inuse_init_net, .exit = sock_inuse_exit_net, }; static __init int net_inuse_init(void) { if (register_pernet_subsys(&net_inuse_ops)) panic("Cannot initialize net inuse counters"); return 0; } core_initcall(net_inuse_init); #else static DEFINE_PER_CPU(struct prot_inuse, prot_inuse); void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(prot_inuse.val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu(prot_inuse, cpu).val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); #endif static void assign_proto_idx(struct proto *prot) { prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) { pr_err("PROTO_INUSE_NR exhausted\n"); return; } set_bit(prot->inuse_idx, proto_inuse_idx); } static void release_proto_idx(struct proto *prot) { if (prot->inuse_idx != PROTO_INUSE_NR - 1) clear_bit(prot->inuse_idx, proto_inuse_idx); } #else static inline void assign_proto_idx(struct proto *prot) { } static inline void release_proto_idx(struct proto *prot) { } #endif static void req_prot_cleanup(struct request_sock_ops *rsk_prot) { if (!rsk_prot) return; kfree(rsk_prot->slab_name); rsk_prot->slab_name = NULL; kmem_cache_destroy(rsk_prot->slab); rsk_prot->slab = NULL; } static int req_prot_init(const struct proto *prot) { struct request_sock_ops *rsk_prot = prot->rsk_prot; if (!rsk_prot) return 0; rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name); if (!rsk_prot->slab_name) return -ENOMEM; rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name, rsk_prot->obj_size, 0, prot->slab_flags, NULL); if (!rsk_prot->slab) { pr_crit("%s: Can't create request sock SLAB cache!\n", prot->name); return -ENOMEM; } return 0; } int proto_register(struct proto *prot, int alloc_slab) { if (alloc_slab) { prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->slab == NULL) { pr_crit("%s: Can't create sock SLAB cache!\n", prot->name); goto out; } if (req_prot_init(prot)) goto out_free_request_sock_slab; if (prot->twsk_prot != NULL) { prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name); if (prot->twsk_prot->twsk_slab_name == NULL) goto out_free_request_sock_slab; prot->twsk_prot->twsk_slab = kmem_cache_create(prot->twsk_prot->twsk_slab_name, prot->twsk_prot->twsk_obj_size, 0, prot->slab_flags, NULL); if (prot->twsk_prot->twsk_slab == NULL) goto out_free_timewait_sock_slab_name; } } mutex_lock(&proto_list_mutex); list_add(&prot->node, &proto_list); assign_proto_idx(prot); mutex_unlock(&proto_list_mutex); return 0; out_free_timewait_sock_slab_name: kfree(prot->twsk_prot->twsk_slab_name); out_free_request_sock_slab: req_prot_cleanup(prot->rsk_prot); kmem_cache_destroy(prot->slab); prot->slab = NULL; out: return -ENOBUFS; } EXPORT_SYMBOL(proto_register); void proto_unregister(struct proto *prot) { mutex_lock(&proto_list_mutex); release_proto_idx(prot); list_del(&prot->node); mutex_unlock(&proto_list_mutex); kmem_cache_destroy(prot->slab); prot->slab = NULL; req_prot_cleanup(prot->rsk_prot); if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) { kmem_cache_destroy(prot->twsk_prot->twsk_slab); kfree(prot->twsk_prot->twsk_slab_name); prot->twsk_prot->twsk_slab = NULL; } } EXPORT_SYMBOL(proto_unregister); #ifdef CONFIG_PROC_FS static void *proto_seq_start(struct seq_file *seq, loff_t *pos) __acquires(proto_list_mutex) { mutex_lock(&proto_list_mutex); return seq_list_start_head(&proto_list, *pos); } static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &proto_list, pos); } static void proto_seq_stop(struct seq_file *seq, void *v) __releases(proto_list_mutex) { mutex_unlock(&proto_list_mutex); } static char proto_method_implemented(const void *method) { return method == NULL ? 'n' : 'y'; } static long sock_prot_memory_allocated(struct proto *proto) { return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; } static char *sock_prot_memory_pressure(struct proto *proto) { return proto->memory_pressure != NULL ? proto_memory_pressure(proto) ? "yes" : "no" : "NI"; } static void proto_seq_printf(struct seq_file *seq, struct proto *proto) { seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", proto->name, proto->obj_size, sock_prot_inuse_get(seq_file_net(seq), proto), sock_prot_memory_allocated(proto), sock_prot_memory_pressure(proto), proto->max_header, proto->slab == NULL ? "no" : "yes", module_name(proto->owner), proto_method_implemented(proto->close), proto_method_implemented(proto->connect), proto_method_implemented(proto->disconnect), proto_method_implemented(proto->accept), proto_method_implemented(proto->ioctl), proto_method_implemented(proto->init), proto_method_implemented(proto->destroy), proto_method_implemented(proto->shutdown), proto_method_implemented(proto->setsockopt), proto_method_implemented(proto->getsockopt), proto_method_implemented(proto->sendmsg), proto_method_implemented(proto->recvmsg), proto_method_implemented(proto->sendpage), proto_method_implemented(proto->bind), proto_method_implemented(proto->backlog_rcv), proto_method_implemented(proto->hash), proto_method_implemented(proto->unhash), proto_method_implemented(proto->get_port), proto_method_implemented(proto->enter_memory_pressure)); } static int proto_seq_show(struct seq_file *seq, void *v) { if (v == &proto_list) seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", "protocol", "size", "sockets", "memory", "press", "maxhdr", "slab", "module", "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n"); else proto_seq_printf(seq, list_entry(v, struct proto, node)); return 0; } static const struct seq_operations proto_seq_ops = { .start = proto_seq_start, .next = proto_seq_next, .stop = proto_seq_stop, .show = proto_seq_show, }; static int proto_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &proto_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations proto_seq_fops = { .owner = THIS_MODULE, .open = proto_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static __net_init int proto_init_net(struct net *net) { if (!proc_create("protocols", S_IRUGO, net->proc_net, &proto_seq_fops)) return -ENOMEM; return 0; } static __net_exit void proto_exit_net(struct net *net) { remove_proc_entry("protocols", net->proc_net); } static __net_initdata struct pernet_operations proto_net_ops = { .init = proto_init_net, .exit = proto_exit_net, }; static int __init proto_init(void) { return register_pernet_subsys(&proto_net_ops); } subsys_initcall(proto_init); #endif /* PROC_FS */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5502_0
crossvul-cpp_data_good_5360_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "bsdtar_platform.h" __FBSDID("$FreeBSD: src/usr.bin/tar/util.c,v 1.23 2008/12/15 06:00:25 kientzle Exp $"); #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> /* Linux doesn't define mode_t, etc. in sys/stat.h. */ #endif #include <ctype.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_IO_H #include <io.h> #endif #ifdef HAVE_STDARG_H #include <stdarg.h> #endif #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include <stdio.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_WCTYPE_H #include <wctype.h> #else /* If we don't have wctype, we need to hack up some version of iswprint(). */ #define iswprint isprint #endif #include "bsdtar.h" #include "err.h" #include "passphrase.h" static size_t bsdtar_expand_char(char *, size_t, char); static const char *strip_components(const char *path, int elements); #if defined(_WIN32) && !defined(__CYGWIN__) #define read _read #endif /* TODO: Hack up a version of mbtowc for platforms with no wide * character support at all. I think the following might suffice, * but it needs careful testing. * #if !HAVE_MBTOWC * #define mbtowc(wcp, p, n) ((*wcp = *p), 1) * #endif */ /* * Print a string, taking care with any non-printable characters. * * Note that we use a stack-allocated buffer to receive the formatted * string if we can. This is partly performance (avoiding a call to * malloc()), partly out of expedience (we have to call vsnprintf() * before malloc() anyway to find out how big a buffer we need; we may * as well point that first call at a small local buffer in case it * works), but mostly for safety (so we can use this to print messages * about out-of-memory conditions). */ void safe_fprintf(FILE *f, const char *fmt, ...) { char fmtbuff_stack[256]; /* Place to format the printf() string. */ char outbuff[256]; /* Buffer for outgoing characters. */ char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */ char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */ int fmtbuff_length; int length, n; va_list ap; const char *p; unsigned i; wchar_t wc; char try_wc; /* Use a stack-allocated buffer if we can, for speed and safety. */ fmtbuff_heap = NULL; fmtbuff_length = sizeof(fmtbuff_stack); fmtbuff = fmtbuff_stack; /* Try formatting into the stack buffer. */ va_start(ap, fmt); length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap); va_end(ap); /* If the result was too large, allocate a buffer on the heap. */ while (length < 0 || length >= fmtbuff_length) { if (length >= fmtbuff_length) fmtbuff_length = length+1; else if (fmtbuff_length < 8192) fmtbuff_length *= 2; else if (fmtbuff_length < 1000000) fmtbuff_length += fmtbuff_length / 4; else { length = fmtbuff_length; fmtbuff_heap[length-1] = '\0'; break; } free(fmtbuff_heap); fmtbuff_heap = malloc(fmtbuff_length); /* Reformat the result into the heap buffer if we can. */ if (fmtbuff_heap != NULL) { fmtbuff = fmtbuff_heap; va_start(ap, fmt); length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap); va_end(ap); } else { /* Leave fmtbuff pointing to the truncated * string in fmtbuff_stack. */ length = sizeof(fmtbuff_stack) - 1; break; } } /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit * more portable, so we use that here instead. */ if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */ /* mbtowc() should never fail in practice, but * handle the theoretical error anyway. */ free(fmtbuff_heap); return; } /* Write data, expanding unprintable characters. */ p = fmtbuff; i = 0; try_wc = 1; while (*p != '\0') { /* Convert to wide char, test if the wide * char is printable in the current locale. */ if (try_wc && (n = mbtowc(&wc, p, length)) != -1) { length -= n; if (iswprint(wc) && wc != L'\\') { /* Printable, copy the bytes through. */ while (n-- > 0) outbuff[i++] = *p++; } else { /* Not printable, format the bytes. */ while (n-- > 0) i += (unsigned)bsdtar_expand_char( outbuff, i, *p++); } } else { /* After any conversion failure, don't bother * trying to convert the rest. */ i += (unsigned)bsdtar_expand_char(outbuff, i, *p++); try_wc = 0; } /* If our output buffer is full, dump it and keep going. */ if (i > (sizeof(outbuff) - 128)) { outbuff[i] = '\0'; fprintf(f, "%s", outbuff); i = 0; } } outbuff[i] = '\0'; fprintf(f, "%s", outbuff); /* If we allocated a heap-based formatting buffer, free it now. */ free(fmtbuff_heap); } /* * Render an arbitrary sequence of bytes into printable ASCII characters. */ static size_t bsdtar_expand_char(char *buff, size_t offset, char c) { size_t i = offset; if (isprint((unsigned char)c) && c != '\\') buff[i++] = c; else { buff[i++] = '\\'; switch (c) { case '\a': buff[i++] = 'a'; break; case '\b': buff[i++] = 'b'; break; case '\f': buff[i++] = 'f'; break; case '\n': buff[i++] = 'n'; break; #if '\r' != '\n' /* On some platforms, \n and \r are the same. */ case '\r': buff[i++] = 'r'; break; #endif case '\t': buff[i++] = 't'; break; case '\v': buff[i++] = 'v'; break; case '\\': buff[i++] = '\\'; break; default: sprintf(buff + i, "%03o", 0xFF & (int)c); i += 3; } } return (i - offset); } int yes(const char *fmt, ...) { char buff[32]; char *p; ssize_t l; va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, " (y/N)? "); fflush(stderr); l = read(2, buff, sizeof(buff) - 1); if (l < 0) { fprintf(stderr, "Keyboard read failed\n"); exit(1); } if (l == 0) return (0); buff[l] = 0; for (p = buff; *p != '\0'; p++) { if (isspace((unsigned char)*p)) continue; switch(*p) { case 'y': case 'Y': return (1); case 'n': case 'N': return (0); default: return (0); } } return (0); } /*- * The logic here for -C <dir> attempts to avoid * chdir() as long as possible. For example: * "-C /foo -C /bar file" needs chdir("/bar") but not chdir("/foo") * "-C /foo -C bar file" needs chdir("/foo/bar") * "-C /foo -C bar /file1" does not need chdir() * "-C /foo -C bar /file1 file2" needs chdir("/foo/bar") before file2 * * The only correct way to handle this is to record a "pending" chdir * request and combine multiple requests intelligently until we * need to process a non-absolute file. set_chdir() adds the new dir * to the pending list; do_chdir() actually executes any pending chdir. * * This way, programs that build tar command lines don't have to worry * about -C with non-existent directories; such requests will only * fail if the directory must be accessed. * */ void set_chdir(struct bsdtar *bsdtar, const char *newdir) { #if defined(_WIN32) && !defined(__CYGWIN__) if (newdir[0] == '/' || newdir[0] == '\\' || /* Detect this type, for example, "C:\" or "C:/" */ (((newdir[0] >= 'a' && newdir[0] <= 'z') || (newdir[0] >= 'A' && newdir[0] <= 'Z')) && newdir[1] == ':' && (newdir[2] == '/' || newdir[2] == '\\'))) { #else if (newdir[0] == '/') { #endif /* The -C /foo -C /bar case; dump first one. */ free(bsdtar->pending_chdir); bsdtar->pending_chdir = NULL; } if (bsdtar->pending_chdir == NULL) /* Easy case: no previously-saved dir. */ bsdtar->pending_chdir = strdup(newdir); else { /* The -C /foo -C bar case; concatenate */ char *old_pending = bsdtar->pending_chdir; size_t old_len = strlen(old_pending); bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2); if (old_pending[old_len - 1] == '/') old_pending[old_len - 1] = '\0'; if (bsdtar->pending_chdir != NULL) sprintf(bsdtar->pending_chdir, "%s/%s", old_pending, newdir); free(old_pending); } if (bsdtar->pending_chdir == NULL) lafe_errc(1, errno, "No memory"); } void do_chdir(struct bsdtar *bsdtar) { if (bsdtar->pending_chdir == NULL) return; if (chdir(bsdtar->pending_chdir) != 0) { lafe_errc(1, 0, "could not chdir to '%s'\n", bsdtar->pending_chdir); } free(bsdtar->pending_chdir); bsdtar->pending_chdir = NULL; } static const char * strip_components(const char *p, int elements) { /* Skip as many elements as necessary. */ while (elements > 0) { switch (*p++) { case '/': #if defined(_WIN32) && !defined(__CYGWIN__) case '\\': /* Support \ path sep on Windows ONLY. */ #endif elements--; break; case '\0': /* Path is too short, skip it. */ return (NULL); } } /* Skip any / characters. This handles short paths that have * additional / termination. This also handles the case where * the logic above stops in the middle of a duplicate // * sequence (which would otherwise get converted to an * absolute path). */ for (;;) { switch (*p) { case '/': #if defined(_WIN32) && !defined(__CYGWIN__) case '\\': /* Support \ path sep on Windows ONLY. */ #endif ++p; break; case '\0': return (NULL); default: return (p); } } } static void warn_strip_leading_char(struct bsdtar *bsdtar, const char *c) { if (!bsdtar->warned_lead_slash) { lafe_warnc(0, "Removing leading '%c' from member names", c[0]); bsdtar->warned_lead_slash = 1; } } static void warn_strip_drive_letter(struct bsdtar *bsdtar) { if (!bsdtar->warned_lead_slash) { lafe_warnc(0, "Removing leading drive letter from " "member names"); bsdtar->warned_lead_slash = 1; } } /* * Convert absolute path to non-absolute path by skipping leading * absolute path prefixes. */ static const char* strip_absolute_path(struct bsdtar *bsdtar, const char *p) { const char *rp; /* Remove leading "//./" or "//?/" or "//?/UNC/" * (absolute path prefixes used by Windows API) */ if ((p[0] == '/' || p[0] == '\\') && (p[1] == '/' || p[1] == '\\') && (p[2] == '.' || p[2] == '?') && (p[3] == '/' || p[3] == '\\')) { if (p[2] == '?' && (p[4] == 'U' || p[4] == 'u') && (p[5] == 'N' || p[5] == 'n') && (p[6] == 'C' || p[6] == 'c') && (p[7] == '/' || p[7] == '\\')) p += 8; else p += 4; warn_strip_drive_letter(bsdtar); } /* Remove multiple leading slashes and Windows drive letters. */ do { rp = p; if (((p[0] >= 'a' && p[0] <= 'z') || (p[0] >= 'A' && p[0] <= 'Z')) && p[1] == ':') { p += 2; warn_strip_drive_letter(bsdtar); } /* Remove leading "/../", "/./", "//", etc. */ while (p[0] == '/' || p[0] == '\\') { if (p[1] == '.' && p[2] == '.' && (p[3] == '/' || p[3] == '\\')) { p += 3; /* Remove "/..", leave "/" for next pass. */ } else if (p[1] == '.' && (p[2] == '/' || p[2] == '\\')) { p += 2; /* Remove "/.", leave "/" for next pass. */ } else p += 1; /* Remove "/". */ warn_strip_leading_char(bsdtar, rp); } } while (rp != p); return (p); } /* * Handle --strip-components and any future path-rewriting options. * Returns non-zero if the pathname should not be extracted. * * Note: The rewrites are applied uniformly to pathnames and hardlink * names but not to symlink bodies. This is deliberate: Symlink * bodies are not necessarily filenames. Even when they are, they * need to be interpreted relative to the directory containing them, * so simple rewrites like this are rarely appropriate. * * TODO: Support pax-style regex path rewrites. */ int edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry) { const char *name = archive_entry_pathname(entry); const char *original_name = name; const char *hardlinkname = archive_entry_hardlink(entry); const char *original_hardlinkname = hardlinkname; #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H) char *subst_name; int r; /* Apply user-specified substitution to pathname. */ r = apply_substitution(bsdtar, name, &subst_name, 0, 0); if (r == -1) { lafe_warnc(0, "Invalid substitution, skipping entry"); return 1; } if (r == 1) { archive_entry_copy_pathname(entry, subst_name); if (*subst_name == '\0') { free(subst_name); return -1; } else free(subst_name); name = archive_entry_pathname(entry); original_name = name; } /* Apply user-specified substitution to hardlink target. */ if (hardlinkname != NULL) { r = apply_substitution(bsdtar, hardlinkname, &subst_name, 0, 1); if (r == -1) { lafe_warnc(0, "Invalid substitution, skipping entry"); return 1; } if (r == 1) { archive_entry_copy_hardlink(entry, subst_name); free(subst_name); } hardlinkname = archive_entry_hardlink(entry); original_hardlinkname = hardlinkname; } /* Apply user-specified substitution to symlink body. */ if (archive_entry_symlink(entry) != NULL) { r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1, 0); if (r == -1) { lafe_warnc(0, "Invalid substitution, skipping entry"); return 1; } if (r == 1) { archive_entry_copy_symlink(entry, subst_name); free(subst_name); } } #endif /* Strip leading dir names as per --strip-components option. */ if (bsdtar->strip_components > 0) { name = strip_components(name, bsdtar->strip_components); if (name == NULL) return (1); if (hardlinkname != NULL) { hardlinkname = strip_components(hardlinkname, bsdtar->strip_components); if (hardlinkname == NULL) return (1); } } if (!bsdtar->option_absolute_paths) { /* By default, don't write or restore absolute pathnames. */ name = strip_absolute_path(bsdtar, name); if (*name == '\0') name = "."; if (hardlinkname != NULL) { hardlinkname = strip_absolute_path(bsdtar, hardlinkname); if (*hardlinkname == '\0') return (1); } } else { /* Strip redundant leading '/' characters. */ while (name[0] == '/' && name[1] == '/') name++; } /* Replace name in archive_entry. */ if (name != original_name) { archive_entry_copy_pathname(entry, name); } if (hardlinkname != original_hardlinkname) { archive_entry_copy_hardlink(entry, hardlinkname); } return (0); } /* * It would be nice to just use printf() for formatting large numbers, * but the compatibility problems are quite a headache. Hence the * following simple utility function. */ const char * tar_i64toa(int64_t n0) { static char buff[24]; uint64_t n = n0 < 0 ? -n0 : n0; char *p = buff + sizeof(buff); *--p = '\0'; do { *--p = '0' + (int)(n % 10); } while (n /= 10); if (n0 < 0) *--p = '-'; return p; } /* * Like strcmp(), but try to be a little more aware of the fact that * we're comparing two paths. Right now, it just handles leading * "./" and trailing '/' specially, so that "a/b/" == "./a/b" * * TODO: Make this better, so that "./a//b/./c/" == "a/b/c" * TODO: After this works, push it down into libarchive. * TODO: Publish the path normalization routines in libarchive so * that bsdtar can normalize paths and use fast strcmp() instead * of this. * * Note: This is currently only used within write.c, so should * not handle \ path separators. */ int pathcmp(const char *a, const char *b) { /* Skip leading './' */ if (a[0] == '.' && a[1] == '/' && a[2] != '\0') a += 2; if (b[0] == '.' && b[1] == '/' && b[2] != '\0') b += 2; /* Find the first difference, or return (0) if none. */ while (*a == *b) { if (*a == '\0') return (0); a++; b++; } /* * If one ends in '/' and the other one doesn't, * they're the same. */ if (a[0] == '/' && a[1] == '\0' && b[0] == '\0') return (0); if (a[0] == '\0' && b[0] == '/' && b[1] == '\0') return (0); /* They're really different, return the correct sign. */ return (*(const unsigned char *)a - *(const unsigned char *)b); } #define PPBUFF_SIZE 1024 const char * passphrase_callback(struct archive *a, void *_client_data) { struct bsdtar *bsdtar = (struct bsdtar *)_client_data; (void)a; /* UNUSED */ if (bsdtar->ppbuff == NULL) { bsdtar->ppbuff = malloc(PPBUFF_SIZE); if (bsdtar->ppbuff == NULL) lafe_errc(1, errno, "Out of memory"); } return lafe_readpassphrase("Enter passphrase:", bsdtar->ppbuff, PPBUFF_SIZE); } void passphrase_free(char *ppbuff) { if (ppbuff != NULL) { memset(ppbuff, 0, PPBUFF_SIZE); free(ppbuff); } } /* * Display information about the current file. * * The format here roughly duplicates the output of 'ls -l'. * This is based on SUSv2, where 'tar tv' is documented as * listing additional information in an "unspecified format," * and 'pax -l' is documented as using the same format as 'ls -l'. */ void list_item_verbose(struct bsdtar *bsdtar, FILE *out, struct archive_entry *entry) { char tmp[100]; size_t w; const char *p; const char *fmt; time_t tim; static time_t now; /* * We avoid collecting the entire list in memory at once by * listing things as we see them. However, that also means we can't * just pre-compute the field widths. Instead, we start with guesses * and just widen them as necessary. These numbers are completely * arbitrary. */ if (!bsdtar->u_width) { bsdtar->u_width = 6; bsdtar->gs_width = 13; } if (!now) time(&now); fprintf(out, "%s %d ", archive_entry_strmode(entry), archive_entry_nlink(entry)); /* Use uname if it's present, else uid. */ p = archive_entry_uname(entry); if ((p == NULL) || (*p == '\0')) { sprintf(tmp, "%lu ", (unsigned long)archive_entry_uid(entry)); p = tmp; } w = strlen(p); if (w > bsdtar->u_width) bsdtar->u_width = w; fprintf(out, "%-*s ", (int)bsdtar->u_width, p); /* Use gname if it's present, else gid. */ p = archive_entry_gname(entry); if (p != NULL && p[0] != '\0') { fprintf(out, "%s", p); w = strlen(p); } else { sprintf(tmp, "%lu", (unsigned long)archive_entry_gid(entry)); w = strlen(tmp); fprintf(out, "%s", tmp); } /* * Print device number or file size, right-aligned so as to make * total width of group and devnum/filesize fields be gs_width. * If gs_width is too small, grow it. */ if (archive_entry_filetype(entry) == AE_IFCHR || archive_entry_filetype(entry) == AE_IFBLK) { sprintf(tmp, "%lu,%lu", (unsigned long)archive_entry_rdevmajor(entry), (unsigned long)archive_entry_rdevminor(entry)); } else { strcpy(tmp, tar_i64toa(archive_entry_size(entry))); } if (w + strlen(tmp) >= bsdtar->gs_width) bsdtar->gs_width = w+strlen(tmp)+1; fprintf(out, "%*s", (int)(bsdtar->gs_width - w), tmp); /* Format the time using 'ls -l' conventions. */ tim = archive_entry_mtime(entry); #define HALF_YEAR (time_t)365 * 86400 / 2 #if defined(_WIN32) && !defined(__CYGWIN__) #define DAY_FMT "%d" /* Windows' strftime function does not support %e format. */ #else #define DAY_FMT "%e" /* Day number without leading zeros */ #endif if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) fmt = bsdtar->day_first ? DAY_FMT " %b %Y" : "%b " DAY_FMT " %Y"; else fmt = bsdtar->day_first ? DAY_FMT " %b %H:%M" : "%b " DAY_FMT " %H:%M"; strftime(tmp, sizeof(tmp), fmt, localtime(&tim)); fprintf(out, " %s ", tmp); safe_fprintf(out, "%s", archive_entry_pathname(entry)); /* Extra information for links. */ if (archive_entry_hardlink(entry)) /* Hard link */ safe_fprintf(out, " link to %s", archive_entry_hardlink(entry)); else if (archive_entry_symlink(entry)) /* Symbolic link */ safe_fprintf(out, " -> %s", archive_entry_symlink(entry)); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5360_0
crossvul-cpp_data_good_2520_0
/* * Copyright (c) Christos Zoulas 2003. * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: readelf.c,v 1.138 2017/08/27 07:55:02 christos Exp $") #endif #ifdef BUILTIN_ELF #include <string.h> #include <ctype.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "readelf.h" #include "magic.h" #ifdef ELFCORE private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int *, uint16_t *); #endif private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int *, uint16_t *); private int doshn(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int, int *, uint16_t *); private size_t donote(struct magic_set *, void *, size_t, size_t, int, int, size_t, int *, uint16_t *, int, off_t, int, off_t); #define ELF_ALIGN(a) ((((a) + align - 1) / align) * align) #define isquote(c) (strchr("'\"`", (c)) != NULL) private uint16_t getu16(int, uint16_t); private uint32_t getu32(int, uint32_t); private uint64_t getu64(int, uint64_t); #define MAX_PHNUM 128 #define MAX_SHNUM 32768 #define SIZE_UNKNOWN ((off_t)-1) private int toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s (%u)", name, num ) == -1) return -1; return 0; } private uint16_t getu16(int swap, uint16_t value) { union { uint16_t ui; char c[2]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[1]; retval.c[1] = tmpval.c[0]; return retval.ui; } else return value; } private uint32_t getu32(int swap, uint32_t value) { union { uint32_t ui; char c[4]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[3]; retval.c[1] = tmpval.c[2]; retval.c[2] = tmpval.c[1]; retval.c[3] = tmpval.c[0]; return retval.ui; } else return value; } private uint64_t getu64(int swap, uint64_t value) { union { uint64_t ui; char c[8]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[7]; retval.c[1] = tmpval.c[6]; retval.c[2] = tmpval.c[5]; retval.c[3] = tmpval.c[4]; retval.c[4] = tmpval.c[3]; retval.c[5] = tmpval.c[2]; retval.c[6] = tmpval.c[1]; retval.c[7] = tmpval.c[0]; return retval.ui; } else return value; } #define elf_getu16(swap, value) getu16(swap, value) #define elf_getu32(swap, value) getu32(swap, value) #define elf_getu64(swap, value) getu64(swap, value) #define xsh_addr (clazz == ELFCLASS32 \ ? (void *)&sh32 \ : (void *)&sh64) #define xsh_sizeof (clazz == ELFCLASS32 \ ? sizeof(sh32) \ : sizeof(sh64)) #define xsh_size (size_t)(clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_size) \ : elf_getu64(swap, sh64.sh_size)) #define xsh_offset (off_t)(clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_offset) \ : elf_getu64(swap, sh64.sh_offset)) #define xsh_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_type) \ : elf_getu32(swap, sh64.sh_type)) #define xsh_name (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_name) \ : elf_getu32(swap, sh64.sh_name)) #define xph_addr (clazz == ELFCLASS32 \ ? (void *) &ph32 \ : (void *) &ph64) #define xph_sizeof (clazz == ELFCLASS32 \ ? sizeof(ph32) \ : sizeof(ph64)) #define xph_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_type) \ : elf_getu32(swap, ph64.p_type)) #define xph_offset (off_t)(clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_offset) \ : elf_getu64(swap, ph64.p_offset)) #define xph_align (size_t)((clazz == ELFCLASS32 \ ? (off_t) (ph32.p_align ? \ elf_getu32(swap, ph32.p_align) : 4) \ : (off_t) (ph64.p_align ? \ elf_getu64(swap, ph64.p_align) : 4))) #define xph_vaddr (size_t)((clazz == ELFCLASS32 \ ? (off_t) (ph32.p_vaddr ? \ elf_getu32(swap, ph32.p_vaddr) : 4) \ : (off_t) (ph64.p_vaddr ? \ elf_getu64(swap, ph64.p_vaddr) : 4))) #define xph_filesz (size_t)((clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_filesz) \ : elf_getu64(swap, ph64.p_filesz))) #define xnh_addr (clazz == ELFCLASS32 \ ? (void *)&nh32 \ : (void *)&nh64) #define xph_memsz (size_t)((clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_memsz) \ : elf_getu64(swap, ph64.p_memsz))) #define xnh_sizeof (clazz == ELFCLASS32 \ ? sizeof(nh32) \ : sizeof(nh64)) #define xnh_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_type) \ : elf_getu32(swap, nh64.n_type)) #define xnh_namesz (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_namesz) \ : elf_getu32(swap, nh64.n_namesz)) #define xnh_descsz (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_descsz) \ : elf_getu32(swap, nh64.n_descsz)) #define prpsoffsets(i) (clazz == ELFCLASS32 \ ? prpsoffsets32[i] \ : prpsoffsets64[i]) #define xcap_addr (clazz == ELFCLASS32 \ ? (void *)&cap32 \ : (void *)&cap64) #define xcap_sizeof (clazz == ELFCLASS32 \ ? sizeof cap32 \ : sizeof cap64) #define xcap_tag (clazz == ELFCLASS32 \ ? elf_getu32(swap, cap32.c_tag) \ : elf_getu64(swap, cap64.c_tag)) #define xcap_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, cap32.c_un.c_val) \ : elf_getu64(swap, cap64.c_un.c_val)) #define xauxv_addr (clazz == ELFCLASS32 \ ? (void *)&auxv32 \ : (void *)&auxv64) #define xauxv_sizeof (clazz == ELFCLASS32 \ ? sizeof(auxv32) \ : sizeof(auxv64)) #define xauxv_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, auxv32.a_type) \ : elf_getu64(swap, auxv64.a_type)) #define xauxv_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, auxv32.a_v) \ : elf_getu64(swap, auxv64.a_v)) #ifdef ELFCORE /* * Try larger offsets first to avoid false matches * from earlier data that happen to look like strings. */ static const size_t prpsoffsets32[] = { #ifdef USE_NT_PSINFO 104, /* SunOS 5.x (command line) */ 88, /* SunOS 5.x (short name) */ #endif /* USE_NT_PSINFO */ 100, /* SunOS 5.x (command line) */ 84, /* SunOS 5.x (short name) */ 44, /* Linux (command line) */ 28, /* Linux 2.0.36 (short name) */ 8, /* FreeBSD */ }; static const size_t prpsoffsets64[] = { #ifdef USE_NT_PSINFO 152, /* SunOS 5.x (command line) */ 136, /* SunOS 5.x (short name) */ #endif /* USE_NT_PSINFO */ 136, /* SunOS 5.x, 64-bit (command line) */ 120, /* SunOS 5.x, 64-bit (short name) */ 56, /* Linux (command line) */ 40, /* Linux (tested on core from 2.4.x, short name) */ 16, /* FreeBSD, 64-bit */ }; #define NOFFSETS32 (sizeof prpsoffsets32 / sizeof prpsoffsets32[0]) #define NOFFSETS64 (sizeof prpsoffsets64 / sizeof prpsoffsets64[0]) #define NOFFSETS (clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64) /* * Look through the program headers of an executable image, searching * for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or * "FreeBSD"; if one is found, try looking in various places in its * contents for a 16-character string containing only printable * characters - if found, that string should be the name of the program * that dropped core. Note: right after that 16-character string is, * at least in SunOS 5.x (and possibly other SVR4-flavored systems) and * Linux, a longer string (80 characters, in 5.x, probably other * SVR4-flavored systems, and Linux) containing the start of the * command line for that program. * * SunOS 5.x core files contain two PT_NOTE sections, with the types * NT_PRPSINFO (old) and NT_PSINFO (new). These structs contain the * same info about the command name and command line, so it probably * isn't worthwhile to look for NT_PSINFO, but the offsets are provided * above (see USE_NT_PSINFO), in case we ever decide to do so. The * NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent; * the SunOS 5.x file command relies on this (and prefers the latter). * * The signal number probably appears in a section of type NT_PRSTATUS, * but that's also rather OS-dependent, in ways that are harder to * dissect with heuristics, so I'm not bothering with the signal number. * (I suppose the signal number could be of interest in situations where * you don't have the binary of the program that dropped core; if you * *do* have that binary, the debugger will probably tell you what * signal it was.) */ #define OS_STYLE_SVR4 0 #define OS_STYLE_FREEBSD 1 #define OS_STYLE_NETBSD 2 private const char os_style_names[][8] = { "SVR4", "FreeBSD", "NetBSD", }; #define FLAGS_CORE_STYLE 0x003 #define FLAGS_DID_CORE 0x004 #define FLAGS_DID_OS_NOTE 0x008 #define FLAGS_DID_BUILD_ID 0x010 #define FLAGS_DID_CORE_STYLE 0x020 #define FLAGS_DID_NETBSD_PAX 0x040 #define FLAGS_DID_NETBSD_MARCH 0x080 #define FLAGS_DID_NETBSD_CMODEL 0x100 #define FLAGS_DID_NETBSD_UNKNOWN 0x200 #define FLAGS_IS_CORE 0x400 #define FLAGS_DID_AUXV 0x800 private int dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; off_t ph_off = off; int ph_num = num; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags, notecount, fd, ph_off, ph_num, fsize); if (offset == 0) break; } } return 0; } #endif static void do_note_netbsd_version(struct magic_set *ms, int swap, void *v) { uint32_t desc; (void)memcpy(&desc, v, sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, ", for NetBSD") == -1) return; /* * The version number used to be stuck as 199905, and was thus * basically content-free. Newer versions of NetBSD have fixed * this and now use the encoding of __NetBSD_Version__: * * MMmmrrpp00 * * M = major version * m = minor version * r = release ["",A-Z,Z[A-Z] but numeric] * p = patchlevel */ if (desc > 100000000U) { uint32_t ver_patch = (desc / 100) % 100; uint32_t ver_rel = (desc / 10000) % 100; uint32_t ver_min = (desc / 1000000) % 100; uint32_t ver_maj = desc / 100000000; if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1) return; if (ver_rel == 0 && ver_patch != 0) { if (file_printf(ms, ".%u", ver_patch) == -1) return; } else if (ver_rel != 0) { while (ver_rel > 26) { if (file_printf(ms, "Z") == -1) return; ver_rel -= 26; } if (file_printf(ms, "%c", 'A' + ver_rel - 1) == -1) return; } } } static void do_note_freebsd_version(struct magic_set *ms, int swap, void *v) { uint32_t desc; (void)memcpy(&desc, v, sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, ", for FreeBSD") == -1) return; /* * Contents is __FreeBSD_version, whose relation to OS * versions is defined by a huge table in the Porter's * Handbook. This is the general scheme: * * Releases: * Mmp000 (before 4.10) * Mmi0p0 (before 5.0) * Mmm0p0 * * Development branches: * Mmpxxx (before 4.6) * Mmp1xx (before 4.10) * Mmi1xx (before 5.0) * M000xx (pre-M.0) * Mmm1xx * * M = major version * m = minor version * i = minor version increment (491000 -> 4.10) * p = patchlevel * x = revision * * The first release of FreeBSD to use ELF by default * was version 3.0. */ if (desc == 460002) { if (file_printf(ms, " 4.6.2") == -1) return; } else if (desc < 460100) { if (file_printf(ms, " %d.%d", desc / 100000, desc / 10000 % 10) == -1) return; if (desc / 1000 % 10 > 0) if (file_printf(ms, ".%d", desc / 1000 % 10) == -1) return; if ((desc % 1000 > 0) || (desc % 100000 == 0)) if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc < 500000) { if (file_printf(ms, " %d.%d", desc / 100000, desc / 10000 % 10 + desc / 1000 % 10) == -1) return; if (desc / 100 % 10 > 0) { if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc / 10 % 10 > 0) { if (file_printf(ms, ".%d", desc / 10 % 10) == -1) return; } } else { if (file_printf(ms, " %d.%d", desc / 100000, desc / 1000 % 100) == -1) return; if ((desc / 100 % 10 > 0) || (desc % 100000 / 100 == 0)) { if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc / 10 % 10 > 0) { if (file_printf(ms, ".%d", desc / 10 % 10) == -1) return; } } } private int /*ARGSUSED*/ do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) { uint8_t desc[20]; const char *btype; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; switch (descsz) { case 8: btype = "xxHash"; break; case 16: btype = "md5/uuid"; break; case 20: btype = "sha1"; break; default: btype = "unknown"; break; } if (file_printf(ms, ", BuildID[%s]=", btype) == -1) return 1; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; } private int do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 && type == NT_GNU_VERSION && descsz == 2) { *flags |= FLAGS_DID_OS_NOTE; file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]); return 1; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_VERSION && descsz == 16) { uint32_t desc[4]; (void)memcpy(desc, &nbuf[doff], sizeof(desc)); *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for GNU/") == -1) return 1; switch (elf_getu32(swap, desc[0])) { case GNU_OS_LINUX: if (file_printf(ms, "Linux") == -1) return 1; break; case GNU_OS_HURD: if (file_printf(ms, "Hurd") == -1) return 1; break; case GNU_OS_SOLARIS: if (file_printf(ms, "Solaris") == -1) return 1; break; case GNU_OS_KFREEBSD: if (file_printf(ms, "kFreeBSD") == -1) return 1; break; case GNU_OS_KNETBSD: if (file_printf(ms, "kNetBSD") == -1) return 1; break; default: if (file_printf(ms, "<unknown>") == -1) return 1; } if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]), elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) return 1; return 1; } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { if (type == NT_NETBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_netbsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) { if (type == NT_FREEBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_freebsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 && type == NT_OPENBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for OpenBSD") == -1) return 1; /* Content of note is always 0 */ return 1; } if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 && type == NT_DRAGONFLY_VERSION && descsz == 4) { uint32_t desc; *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for DragonFly") == -1) return 1; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, " %d.%d.%d", desc / 100000, desc / 10000 % 10, desc % 10000) == -1) return 1; return 1; } return 0; } private int do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 && type == NT_NETBSD_PAX && descsz == 4) { static const char *pax[] = { "+mprotect", "-mprotect", "+segvguard", "-segvguard", "+ASLR", "-ASLR", }; uint32_t desc; size_t i; int did = 0; *flags |= FLAGS_DID_NETBSD_PAX; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (desc && file_printf(ms, ", PaX: ") == -1) return 1; for (i = 0; i < __arraycount(pax); i++) { if (((1 << (int)i) & desc) == 0) continue; if (file_printf(ms, "%s%s", did++ ? "," : "", pax[i]) == -1) return 1; } return 1; } return 0; } private int do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, descsz); if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, " "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)", file_printable(sbuf, sizeof(sbuf), CAST(char *, pi.cpi_name)), elf_getu32(swap, pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; } private off_t get_offset_from_virtaddr(struct magic_set *ms, int swap, int clazz, int fd, off_t off, int num, off_t fsize, uint64_t virtaddr) { Elf32_Phdr ph32; Elf64_Phdr ph64; /* * Loop through all the program headers and find the header with * virtual address in which the "virtaddr" belongs to. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += xph_sizeof; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (virtaddr >= xph_vaddr && virtaddr < xph_vaddr + xph_filesz) return xph_offset + (virtaddr - xph_vaddr); } return 0; } private size_t get_string_on_virtaddr(struct magic_set *ms, int swap, int clazz, int fd, off_t ph_off, int ph_num, off_t fsize, uint64_t virtaddr, char *buf, ssize_t buflen) { char *bptr; off_t offset; if (buflen == 0) return 0; offset = get_offset_from_virtaddr(ms, swap, clazz, fd, ph_off, ph_num, fsize, virtaddr); if ((buflen = pread(fd, buf, CAST(size_t, buflen), offset)) <= 0) { file_badread(ms); return 0; } buf[buflen - 1] = '\0'; /* We expect only printable characters, so return if buffer contains * non-printable character before the '\0' or just '\0'. */ for (bptr = buf; *bptr && isprint((unsigned char)*bptr); bptr++) continue; if (*bptr != '\0') return 0; return bptr - buf; } private int do_auxv_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz __attribute__((__unused__)), uint32_t descsz __attribute__((__unused__)), size_t noff __attribute__((__unused__)), size_t doff, int *flags, size_t size __attribute__((__unused__)), int clazz, int fd, off_t ph_off, int ph_num, off_t fsize) { #ifdef ELFCORE Aux32Info auxv32; Aux64Info auxv64; size_t elsize = xauxv_sizeof; const char *tag; int is_string; size_t nval; if ((*flags & (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) != (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) return 0; switch (*flags & FLAGS_CORE_STYLE) { case OS_STYLE_SVR4: if (type != NT_AUXV) return 0; break; #ifdef notyet case OS_STYLE_NETBSD: if (type != NT_NETBSD_CORE_AUXV) return 0; break; case OS_STYLE_FREEBSD: if (type != NT_FREEBSD_PROCSTAT_AUXV) return 0; break; #endif default: return 0; } *flags |= FLAGS_DID_AUXV; nval = 0; for (size_t off = 0; off + elsize <= descsz; off += elsize) { (void)memcpy(xauxv_addr, &nbuf[doff + off], xauxv_sizeof); /* Limit processing to 50 vector entries to prevent DoS */ if (nval++ >= 50) { file_error(ms, 0, "Too many ELF Auxv elements"); return 1; } switch(xauxv_type) { case AT_LINUX_EXECFN: is_string = 1; tag = "execfn"; break; case AT_LINUX_PLATFORM: is_string = 1; tag = "platform"; break; case AT_LINUX_UID: is_string = 0; tag = "real uid"; break; case AT_LINUX_GID: is_string = 0; tag = "real gid"; break; case AT_LINUX_EUID: is_string = 0; tag = "effective uid"; break; case AT_LINUX_EGID: is_string = 0; tag = "effective gid"; break; default: is_string = 0; tag = NULL; break; } if (tag == NULL) continue; if (is_string) { char buf[256]; ssize_t buflen; buflen = get_string_on_virtaddr(ms, swap, clazz, fd, ph_off, ph_num, fsize, xauxv_val, buf, sizeof(buf)); if (buflen == 0) continue; if (file_printf(ms, ", %s: '%s'", tag, buf) == -1) return 0; } else { if (file_printf(ms, ", %s: %d", tag, (int) xauxv_val) == -1) return 0; } } return 1; #else return 0; #endif } private size_t donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags, uint16_t *notecount, int fd, off_t ph_off, int ph_num, off_t fsize) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); if (*notecount == 0) return 0; --*notecount; if (xnh_sizeof + offset > size) { /* * We're out of note headers. */ return xnh_sizeof + offset; } (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { (void)file_printf(ms, ", bad note name size %#lx", (unsigned long)namesz); return 0; } if (descsz & 0x80000000) { (void)file_printf(ms, ", bad note description size %#lx", (unsigned long)descsz); return 0; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & FLAGS_DID_OS_NOTE) == 0) { if (do_os_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_BUILD_ID) == 0) { if (do_bid_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { if (do_pax_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_CORE) == 0) { if (do_core_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz)) return offset; } if ((*flags & FLAGS_DID_AUXV) == 0) { if (do_auxv_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz, fd, ph_off, ph_num, fsize)) return offset; } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { if (descsz > 100) descsz = 100; switch (xnh_type) { case NT_NETBSD_VERSION: return offset; case NT_NETBSD_MARCH: if (*flags & FLAGS_DID_NETBSD_MARCH) return offset; *flags |= FLAGS_DID_NETBSD_MARCH; if (file_printf(ms, ", compiled for: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return offset; break; case NT_NETBSD_CMODEL: if (*flags & FLAGS_DID_NETBSD_CMODEL) return offset; *flags |= FLAGS_DID_NETBSD_CMODEL; if (file_printf(ms, ", compiler model: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return offset; break; default: if (*flags & FLAGS_DID_NETBSD_UNKNOWN) return offset; *flags |= FLAGS_DID_NETBSD_UNKNOWN; if (file_printf(ms, ", note=%u", xnh_type) == -1) return offset; break; } return offset; } return offset; } /* SunOS 5.x hardware capability descriptions */ typedef struct cap_desc { uint64_t cd_mask; const char *cd_name; } cap_desc_t; static const cap_desc_t cap_desc_sparc[] = { { AV_SPARC_MUL32, "MUL32" }, { AV_SPARC_DIV32, "DIV32" }, { AV_SPARC_FSMULD, "FSMULD" }, { AV_SPARC_V8PLUS, "V8PLUS" }, { AV_SPARC_POPC, "POPC" }, { AV_SPARC_VIS, "VIS" }, { AV_SPARC_VIS2, "VIS2" }, { AV_SPARC_ASI_BLK_INIT, "ASI_BLK_INIT" }, { AV_SPARC_FMAF, "FMAF" }, { AV_SPARC_FJFMAU, "FJFMAU" }, { AV_SPARC_IMA, "IMA" }, { 0, NULL } }; static const cap_desc_t cap_desc_386[] = { { AV_386_FPU, "FPU" }, { AV_386_TSC, "TSC" }, { AV_386_CX8, "CX8" }, { AV_386_SEP, "SEP" }, { AV_386_AMD_SYSC, "AMD_SYSC" }, { AV_386_CMOV, "CMOV" }, { AV_386_MMX, "MMX" }, { AV_386_AMD_MMX, "AMD_MMX" }, { AV_386_AMD_3DNow, "AMD_3DNow" }, { AV_386_AMD_3DNowx, "AMD_3DNowx" }, { AV_386_FXSR, "FXSR" }, { AV_386_SSE, "SSE" }, { AV_386_SSE2, "SSE2" }, { AV_386_PAUSE, "PAUSE" }, { AV_386_SSE3, "SSE3" }, { AV_386_MON, "MON" }, { AV_386_CX16, "CX16" }, { AV_386_AHF, "AHF" }, { AV_386_TSCP, "TSCP" }, { AV_386_AMD_SSE4A, "AMD_SSE4A" }, { AV_386_POPCNT, "POPCNT" }, { AV_386_AMD_LZCNT, "AMD_LZCNT" }, { AV_386_SSSE3, "SSSE3" }, { AV_386_SSE4_1, "SSE4.1" }, { AV_386_SSE4_2, "SSE4.2" }, { 0, NULL } }; private int doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int mach, int strtab, int *flags, uint16_t *notecount) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1, has_debug_info = 0; size_t nbadcap = 0; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */ char name[50]; ssize_t namesize; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) < (ssize_t)xsh_sizeof) { if (file_printf(ms, ", missing section headers") == -1) return -1; return 0; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { file_badread(ms); return -1; } name[namesize] = '\0'; if (strcmp(name, ".debug_info") == 0) { has_debug_info = 1; stripped = 0; } if (pread(fd, xsh_addr, xsh_sizeof, off) < (ssize_t)xsh_sizeof) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((uintmax_t)(xsh_size + xsh_offset) > (uintmax_t)fsize) { if (file_printf(ms, ", note offset/size %#" INTMAX_T_FORMAT "x+%#" INTMAX_T_FORMAT "x exceeds" " file size %#" INTMAX_T_FORMAT "x", (uintmax_t)xsh_offset, (uintmax_t)xsh_size, (uintmax_t)fsize) == -1) return -1; return 0; } if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) < (ssize_t)xsh_size) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags, notecount, fd, 0, 0, 0); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (nbadcap > 5) break; if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } // gnu attributes #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "%#" INT64_T_FORMAT "x = %#" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; if (nbadcap++ > 2) coff = xsh_size; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (has_debug_info) { if (file_printf(ms, ", with debug_info") == -1) return -1; } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability %#" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability %#" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability %#" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; } /* * Look through the program headers of an executable image, searching * for a PT_INTERP section; if one is found, it's dynamically linked, * otherwise it's statically linked. */ private int dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int sh_num, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment %#lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags, notecount, fd, 0, 0, 0); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; } protected int file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum, notecount; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE|MAGIC_EXTENSION)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_2520_0
crossvul-cpp_data_good_4787_14
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD PPPP SSSSS % % D D P P SS % % D D PPPP SSS % % D D P SS % % DDDD P SSSSS % % % % % % Read Postscript Using the Display Postscript System. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/client.h" #include "magick/colormap.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" #include "magick/xwindow-private.h" #if defined(MAGICKCORE_DPS_DELEGATE) #include <DPS/dpsXclient.h> #include <DPS/dpsXpreview.h> #endif #if defined(MAGICKCORE_DPS_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDPSImage() reads a Adobe Postscript image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadDPSImage method is: % % Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *client_name; Display *display; float pixels_per_point; Image *image; int sans, status; Pixmap pixmap; register IndexPacket *indexes; register ssize_t i; register PixelPacket *q; register size_t pixel; Screen *screen; ssize_t x, y; XColor *colors; XImage *dps_image; XRectangle page, bits_per_pixel; XResourceInfo resource_info; XrmDatabase resource_database; XStandardColormap *map_info; XVisualInfo *visual_info; /* Open X server connection. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); display=XOpenDisplay(image_info->server_name); if (display == (Display *) NULL) return((Image *) NULL); /* Set our forgiving exception handler. */ (void) XSetErrorHandler(XError); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Get user defaults from X resource database. */ client_name=GetClientName(); resource_database=XGetResourceDatabase(display,client_name); XGetResourceInfo(image_info,resource_database,client_name,&resource_info); /* Allocate standard colormap. */ map_info=XAllocStandardColormap(); visual_info=(XVisualInfo *) NULL; if (map_info == (XStandardColormap *) NULL) ThrowReaderException(ResourceLimitError,"UnableToCreateStandardColormap") else { /* Initialize visual info. */ (void) CloneString(&resource_info.visual_type,"default"); visual_info=XBestVisualInfo(display,map_info,&resource_info); map_info->colormap=(Colormap) NULL; } if ((map_info == (XStandardColormap *) NULL) || (visual_info == (XVisualInfo *) NULL)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Create a pixmap the appropriate size for the image. */ screen=ScreenOfDisplay(display,visual_info->screen); pixels_per_point=XDPSPixelsPerPoint(screen); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/ DefaultResolution; status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap, &bits_per_pixel,&page); if ((status == dps_status_failure) || (status == dps_status_no_extension)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Rasterize the file into the pixmap. */ status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth, &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue, &sans); if (status != dps_status_success) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Initialize DPS X image. */ dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (dps_image == (XImage *) NULL) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Get the colormap colors. */ colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size, sizeof(*colors)); if (colors == (XColor *) NULL) { image=DestroyImage(image); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor)) for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=(size_t) i; colors[i].pad=0; } else { size_t blue, blue_bit, green, green_bit, red, red_bit; /* DirectColor or TrueColor visual. */ red=0; green=0; blue=0; red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1); green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1); blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1); for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=red | green | blue; colors[i].pad=0; red+=red_bit; if (red > visual_info->red_mask) red=0; green+=green_bit; if (green > visual_info->green_mask) green=0; blue+=blue_bit; if (blue > visual_info->blue_mask) blue=0; } } (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen), colors,visual_info->colormap_size); /* Convert X image to MIFF format. */ if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor)) image->storage_class=PseudoClass; image->columns=(size_t) dps_image->width; image->rows=(size_t) dps_image->height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } switch (image->storage_class) { case DirectClass: default: { register size_t color, index; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=visual_info->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=visual_info->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=visual_info->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((visual_info->colormap_size > 0) && (visual_info->klass == DirectColor)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); index=(pixel >> red_shift) & red_mask; SetPixelRed(q,ScaleShortToQuantum(colors[index].red)); index=(pixel >> green_shift) & green_mask; SetPixelGreen(q,ScaleShortToQuantum(colors[index].green)); index=(pixel >> blue_shift) & blue_mask; SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); color=(pixel >> red_shift) & red_mask; color=(color*65535L)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; color=(color*65535L)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; color=(color*65535L)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } case PseudoClass: { /* Create colormap. */ if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse) { image=DestroyImage(image); colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red); image->colormap[colors[i].pixel].green= ScaleShortToQuantum(colors[i].green); image->colormap[colors[i].pixel].blue= ScaleShortToQuantum(colors[i].blue); } /* Convert X image to PseudoClass packets. */ for (y=0; y < (ssize_t) image->rows; y++) { 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,(unsigned short) XGetPixel(dps_image,x,y)); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } } colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); if (image->storage_class == PseudoClass) (void) SyncImage(image); /* Rasterize matte image. */ status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page); if ((status != dps_status_failure) && (status != dps_status_no_extension)) { status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x, -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans); if (status == dps_status_success) { XImage *matte_image; /* Initialize image matte. */ matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (matte_image != (XImage *) NULL) { image->storage_class=DirectClass; image->matte=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,OpaqueOpacity); if (XGetPixel(matte_image,x,y) == 0) SetPixelOpacity(q,TransparentOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } XDestroyImage(matte_image); } } } /* Relinquish resources. */ XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDPSImage() adds attributes for the Display Postscript image % format to the list of supported formats. The attributes include the image % format tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterDPSImage method is: % % size_t RegisterDPSImage(void) % */ ModuleExport size_t RegisterDPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("DPS"); #if defined(MAGICKCORE_DPS_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadDPSImage; #endif entry->blob_support=MagickFalse; entry->description=ConstantString("Display Postscript Interpreter"); entry->module=ConstantString("DPS"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDPSImage() removes format registrations made by the % DPS module from the list of supported formats. % % The format of the UnregisterDPSImage method is: % % UnregisterDPSImage(void) % */ ModuleExport void UnregisterDPSImage(void) { (void) UnregisterMagickInfo("DPS"); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_14
crossvul-cpp_data_good_1773_0
/* mount.c (22.10.09) exFAT file system implementation library. Free exFAT implementation. Copyright (C) 2010-2015 Andrew Nayenko This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "exfat.h" #include <string.h> #include <stdlib.h> #include <errno.h> #include <inttypes.h> #include <unistd.h> #include <sys/types.h> static uint64_t rootdir_size(const struct exfat* ef) { uint64_t clusters = 0; cluster_t rootdir_cluster = le32_to_cpu(ef->sb->rootdir_cluster); while (!CLUSTER_INVALID(rootdir_cluster)) { clusters++; /* root directory cannot be contiguous because there is no flag to indicate this */ rootdir_cluster = exfat_next_cluster(ef, ef->root, rootdir_cluster); } if (rootdir_cluster != EXFAT_CLUSTER_END) { exfat_error("bad cluster %#x while reading root directory", rootdir_cluster); return 0; } return clusters * CLUSTER_SIZE(*ef->sb); } static const char* get_option(const char* options, const char* option_name) { const char* p; size_t length = strlen(option_name); for (p = strstr(options, option_name); p; p = strstr(p + 1, option_name)) if ((p == options || p[-1] == ',') && p[length] == '=') return p + length + 1; return NULL; } static int get_int_option(const char* options, const char* option_name, int base, int default_value) { const char* p = get_option(options, option_name); if (p == NULL) return default_value; return strtol(p, NULL, base); } static bool match_option(const char* options, const char* option_name) { const char* p; size_t length = strlen(option_name); for (p = strstr(options, option_name); p; p = strstr(p + 1, option_name)) if ((p == options || p[-1] == ',') && (p[length] == ',' || p[length] == '\0')) return true; return false; } static void parse_options(struct exfat* ef, const char* options) { int opt_umask; opt_umask = get_int_option(options, "umask", 8, 0); ef->dmask = get_int_option(options, "dmask", 8, opt_umask); ef->fmask = get_int_option(options, "fmask", 8, opt_umask); ef->uid = get_int_option(options, "uid", 10, geteuid()); ef->gid = get_int_option(options, "gid", 10, getegid()); ef->noatime = match_option(options, "noatime"); } static bool verify_vbr_checksum(struct exfat_dev* dev, void* sector, off_t sector_size) { uint32_t vbr_checksum; int i; if (exfat_pread(dev, sector, sector_size, 0) < 0) { exfat_error("failed to read boot sector"); return false; } vbr_checksum = exfat_vbr_start_checksum(sector, sector_size); for (i = 1; i < 11; i++) { if (exfat_pread(dev, sector, sector_size, i * sector_size) < 0) { exfat_error("failed to read VBR sector"); return false; } vbr_checksum = exfat_vbr_add_checksum(sector, sector_size, vbr_checksum); } if (exfat_pread(dev, sector, sector_size, i * sector_size) < 0) { exfat_error("failed to read VBR checksum sector"); return false; } for (i = 0; i < sector_size / sizeof(vbr_checksum); i++) if (le32_to_cpu(((const le32_t*) sector)[i]) != vbr_checksum) { exfat_error("invalid VBR checksum 0x%x (expected 0x%x)", le32_to_cpu(((const le32_t*) sector)[i]), vbr_checksum); return false; } return true; } static int commit_super_block(const struct exfat* ef) { if (exfat_pwrite(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_error("failed to write super block"); return 1; } return exfat_fsync(ef->dev); } static int prepare_super_block(const struct exfat* ef) { if (le16_to_cpu(ef->sb->volume_state) & EXFAT_STATE_MOUNTED) exfat_warn("volume was not unmounted cleanly"); if (ef->ro) return 0; ef->sb->volume_state = cpu_to_le16( le16_to_cpu(ef->sb->volume_state) | EXFAT_STATE_MOUNTED); return commit_super_block(ef); } int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, "ro")) mode = EXFAT_MODE_RO; else if (match_option(options, "ro_fallback")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error("failed to allocate memory for the super block"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to read boot sector"); return -EIO; } if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("exFAT file system is not found"); return -EIO; } /* sector cannot be smaller than 512 bytes */ if (ef->sb->sector_bits < 9) { exfat_close(ef->dev); exfat_error("too small sector size: 2^%hhd", ef->sb->sector_bits); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { exfat_close(ef->dev); exfat_error("too big cluster size: 2^(%hhd+%hhd)", ef->sb->sector_bits, ef->sb->spc_bits); free(ef->sb); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate zero sector"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported exFAT version: %hhu.%hhu", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn("file system is larger than underlying device: " "%"PRIu64" > %"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate root node"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error("upcase table is not found"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error("clusters bitmap is not found"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } static void finalize_super_block(struct exfat* ef) { if (ef->ro) return; ef->sb->volume_state = cpu_to_le16( le16_to_cpu(ef->sb->volume_state) & ~EXFAT_STATE_MOUNTED); /* Some implementations set the percentage of allocated space to 0xff on FS creation and never update it. In this case leave it as is. */ if (ef->sb->allocated_percent != 0xff) { uint32_t free, total; free = exfat_count_free_clusters(ef); total = le32_to_cpu(ef->sb->cluster_count); ef->sb->allocated_percent = ((total - free) * 100 + total / 2) / total; } commit_super_block(ef); /* ignore return code */ } void exfat_unmount(struct exfat* ef) { exfat_flush(ef); /* ignore return code */ exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); ef->root = NULL; finalize_super_block(ef); exfat_close(ef->dev); /* close descriptor immediately after fsync */ ef->dev = NULL; free(ef->zero_cluster); ef->zero_cluster = NULL; free(ef->cmap.chunk); ef->cmap.chunk = NULL; free(ef->sb); ef->sb = NULL; free(ef->upcase); ef->upcase = NULL; ef->upcase_chars = 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1773_0
crossvul-cpp_data_good_2774_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" #include "opj_common.h" /* ----------------------------------------------------------------------- */ /* TODO MSD: */ #ifdef TODO_MSD void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) { int tileno, compno, resno, bandno, precno;/*, cblkno;*/ fprintf(fd, "image {\n"); fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n", img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0, tcd->image->y1); for (tileno = 0; tileno < img->th * img->tw; tileno++) { opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno]; fprintf(fd, " tile {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n", tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps); for (compno = 0; compno < tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; fprintf(fd, " tilec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n", tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions); for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; fprintf(fd, "\n res {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n", res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands); for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; fprintf(fd, " band {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n", band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps); for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prec = &band->precincts[precno]; fprintf(fd, " prec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n", prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch); /* for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) { opj_tcd_cblk_t *cblk = &prec->cblks[cblkno]; fprintf(fd, " cblk {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d\n", cblk->x0, cblk->y0, cblk->x1, cblk->y1); fprintf(fd, " }\n"); } */ fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, "}\n"); } #endif /** * Initializes tile coding/decoding */ 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_event_mgr_t* manager); /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t * p_code_block); /** * Deallocates the decoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct); /** * Allocates memory for an encoding code block (but not data). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t * p_code_block); /** * Allocates data for an encoding code block */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block); /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct); /** Free the memory allocated for encoding @param tcd TCD handle */ static void opj_tcd_free_tile(opj_tcd_t *tcd); static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info, opj_event_mgr_t *p_manager); /* ----------------------------------------------------------------------- */ /** Create a new TCD handle */ opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder) { opj_tcd_t *l_tcd = 00; /* create the tcd structure */ l_tcd = (opj_tcd_t*) opj_calloc(1, sizeof(opj_tcd_t)); if (!l_tcd) { return 00; } l_tcd->m_is_decoder = p_is_decoder ? 1 : 0; l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1, sizeof(opj_tcd_image_t)); if (!l_tcd->tcd_image) { opj_free(l_tcd); return 00; } return l_tcd; } /* ----------------------------------------------------------------------- */ void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd) { OPJ_UINT32 layno; for (layno = 0; layno < tcd->tcp->numlayers; layno++) { opj_tcd_makelayer_fixed(tcd, layno, 1); } } void opj_tcd_makelayer(opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_FLOAT64 thresh, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_UINT32 passno; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; tcd_tile->distolayer[layno] = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; /* Skip empty bands */ if (opj_tcd_is_band_empty(band)) { continue; } for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) { OPJ_UINT32 dr; OPJ_FLOAT64 dd; opj_tcd_pass_t *pass = &cblk->passes[passno]; if (n == 0) { dr = pass->rate; dd = pass->distortiondec; } else { dr = pass->rate - cblk->passes[n - 1].rate; dd = pass->distortiondec - cblk->passes[n - 1].distortiondec; } if (!dr) { if (dd != 0) { n = passno + 1; } continue; } if (thresh - (dd / dr) < DBL_EPSILON) { /* do not rely on float equality, check with DBL_EPSILON margin */ n = passno + 1; } } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) { layer->disto = 0; continue; } if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; layer->disto = cblk->passes[n - 1].distortiondec; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec; } tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */ if (final) { cblk->numpassesinlayers = n; } } } } } } } void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */ OPJ_INT32 matrice[10][10][3]; OPJ_UINT32 i, j, k; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (i = 0; i < tcd_tcp->numlayers; i++) { for (j = 0; j < tilec->numresolutions; j++) { for (k = 0; k < 3; k++) { matrice[i][j][k] = (OPJ_INT32)((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i * tilec->numresolutions * 3 + j * 3 + k] * (OPJ_FLOAT32)(tcd->image->comps[compno].prec / 16.0)); } } } for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; /* Skip empty bands */ if (opj_tcd_is_band_empty(band)) { continue; } for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec - cblk->numbps); /* number of bit-plan equal to zero */ /* Correction of the matrix of coefficient to include the IMSB information */ if (layno == 0) { value = matrice[layno][resno][bandno]; if (imsb >= value) { value = 0; } else { value -= imsb; } } else { value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno]; if (imsb >= matrice[layno - 1][resno][bandno]) { value -= (imsb - matrice[layno - 1][resno][bandno]); if (value < 0) { value = 0; } } } if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; if (cblk->numpassesinlayers == 0) { if (value != 0) { n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers; } else { n = cblk->numpassesinlayers; } } else { n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) { continue; } if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; } if (final) { cblk->numpassesinlayers = n; } } } } } } } OPJ_BOOL opj_tcd_rateallocate(opj_tcd_t *tcd, OPJ_BYTE *dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 len, opj_codestream_info_t *cstr_info, opj_event_mgr_t *p_manager) { OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno; OPJ_UINT32 passno; OPJ_FLOAT64 min, max; OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */ const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */ OPJ_FLOAT64 maxSE = 0; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; min = DBL_MAX; max = 0; tcd_tile->numpix = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; tilec->numpix = 0; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; /* Skip empty bands */ if (opj_tcd_is_band_empty(band)) { continue; } for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; for (passno = 0; passno < cblk->totalpasses; passno++) { opj_tcd_pass_t *pass = &cblk->passes[passno]; OPJ_INT32 dr; OPJ_FLOAT64 dd, rdslope; if (passno == 0) { dr = (OPJ_INT32)pass->rate; dd = pass->distortiondec; } else { dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate); dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec; } if (dr == 0) { continue; } rdslope = dd / dr; if (rdslope < min) { min = rdslope; } if (rdslope > max) { max = rdslope; } } /* passno */ /* fixed_quality */ tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); } /* cbklno */ } /* precno */ } /* bandno */ } /* resno */ maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0) * ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0)) * ((OPJ_FLOAT64)(tilec->numpix)); } /* compno */ /* index file */ if (cstr_info) { opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno]; tile_info->numpix = tcd_tile->numpix; tile_info->distotile = tcd_tile->distotile; tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof( OPJ_FLOAT64)); if (!tile_info->thresh) { /* FIXME event manager error callback */ return OPJ_FALSE; } } for (layno = 0; layno < tcd_tcp->numlayers; layno++) { OPJ_FLOAT64 lo = min; OPJ_FLOAT64 hi = max; OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min((( OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len; OPJ_FLOAT64 goodthresh = 0; OPJ_FLOAT64 stable_thresh = 0; OPJ_UINT32 i; OPJ_FLOAT64 distotarget; /* fixed_quality */ /* fixed_quality */ distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10, tcd_tcp->distoratio[layno] / 10)); /* Don't try to find an optimal threshold but rather take everything not included yet, if -r xx,yy,zz,0 (disto_alloc == 1 and rates == 0) -q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0) ==> possible to have some lossy layers and the last layer for sure lossless */ if (((cp->m_specific_param.m_enc.m_disto_alloc == 1) && (tcd_tcp->rates[layno] > 0.0f)) || ((cp->m_specific_param.m_enc.m_fixed_quality == 1) && (tcd_tcp->distoratio[layno] > 0.0))) { opj_t2_t*t2 = opj_t2_create(tcd->image, cp); OPJ_FLOAT64 thresh = 0; if (t2 == 00) { return OPJ_FALSE; } for (i = 0; i < 128; ++i) { OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */ thresh = (lo + hi) / 2; opj_tcd_makelayer(tcd, layno, thresh, 0); if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ if (OPJ_IS_CINEMA(cp->rsiz)) { if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino, THRESH_CALC, p_manager)) { lo = thresh; continue; } else { distoachieved = layno == 0 ? tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno]; if (distoachieved < distotarget) { hi = thresh; stable_thresh = thresh; continue; } else { lo = thresh; } } } else { distoachieved = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); if (distoachieved < distotarget) { hi = thresh; stable_thresh = thresh; continue; } lo = thresh; } } else { if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino, THRESH_CALC, p_manager)) { /* TODO: what to do with l ??? seek / tell ??? */ /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */ lo = thresh; continue; } hi = thresh; stable_thresh = thresh; } } goodthresh = stable_thresh == 0 ? thresh : stable_thresh; opj_t2_destroy(t2); } else { goodthresh = min; } if (cstr_info) { /* Threshold for Marcela Index */ cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh; } opj_tcd_makelayer(tcd, layno, goodthresh, 1); /* fixed_quality */ cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_init(opj_tcd_t *p_tcd, opj_image_t * p_image, opj_cp_t * p_cp, opj_thread_pool_t* p_tp) { p_tcd->image = p_image; p_tcd->cp = p_cp; p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1, sizeof(opj_tcd_tile_t)); if (! p_tcd->tcd_image->tiles) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc( p_image->numcomps, sizeof(opj_tcd_tilecomp_t)); if (! p_tcd->tcd_image->tiles->comps) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->numcomps = p_image->numcomps; p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos; p_tcd->thread_pool = p_tp; return OPJ_TRUE; } /** Destroy a previously created TCD handle */ void opj_tcd_destroy(opj_tcd_t *tcd) { if (tcd) { opj_tcd_free_tile(tcd); if (tcd->tcd_image) { opj_free(tcd->tcd_image); tcd->tcd_image = 00; } opj_free(tcd); } } OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec) { if ((l_tilec->data == 00) || ((l_tilec->data_size_needed > l_tilec->data_size) && (l_tilec->ownsData == OPJ_FALSE))) { l_tilec->data = (OPJ_INT32 *) opj_image_data_alloc(l_tilec->data_size_needed); if (! l_tilec->data) { return OPJ_FALSE; } /*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } else if (l_tilec->data_size_needed > l_tilec->data_size) { /* We don't need to keep old data */ opj_image_data_free(l_tilec->data); l_tilec->data = (OPJ_INT32 *) opj_image_data_alloc(l_tilec->data_size_needed); if (! l_tilec->data) { l_tilec->data_size = 0; l_tilec->data_size_needed = 0; l_tilec->ownsData = OPJ_FALSE; return OPJ_FALSE; } /*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ 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_event_mgr_t* manager) { 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; OPJ_UINT32 l_tx0, l_ty0; /* 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_tx0 = l_cp->tx0 + p * l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */ l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0); l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx), l_image->x1); /* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */ if ((l_tile->x0 < 0) || (l_tile->x1 <= l_tile->x0)) { opj_event_msg(manager, EVT_ERROR, "Tile X coordinates are not supported\n"); return OPJ_FALSE; } l_ty0 = l_cp->ty0 + q * l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */ l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0); l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy), l_image->y1); /* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */ if ((l_tile->y0 < 0) || (l_tile->y1 <= l_tile->y0)) { opj_event_msg(manager, EVT_ERROR, "Tile Y coordinates are not supported\n"); return OPJ_FALSE; } /* testcase 1888.pdf.asan.35.988 */ if (l_tccp->numresolutions == 0) { opj_event_msg(manager, EVT_ERROR, "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); /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */ if ((l_data_size > 0U) && ((((OPJ_UINT32) - 1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0))) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); 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) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); 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)) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); 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(manager, EVT_ERROR, "Not enough memory for 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; 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; --l_level_no; /* 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) ? 0U : (OPJ_UINT32)(( l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx); l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (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 );*/ if ((l_res->pw != 0U) && ((((OPJ_UINT32) - 1) / l_res->pw) < l_res->ph)) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } l_nb_precincts = l_res->pw * l_res->ph; if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) < l_nb_precincts) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } 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, ++l_band, ++l_step_size) { 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_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); } if (isEncoder) { /* Skip empty bands */ if (opj_tcd_is_band_empty(l_band)) { /* Do not zero l_band->precints to avoid leaks */ /* but make sure we don't use it later, since */ /* it will point to precincts of previous bands... */ continue; } } /** 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; /* Mb value of Equation E-2 in "E.1 Inverse quantization * procedure" of the standard */ l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; if (!l_band->precincts && (l_nb_precincts > 0U)) { l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */ l_nb_precinct_size); if (! l_band->precincts) { opj_event_msg(manager, EVT_ERROR, "Not enough memory to handle band precints\n"); 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(manager, EVT_ERROR, "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_nb_code_blocks > 0U)) { 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(manager, EVT_ERROR, "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, manager); } else { l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch, manager); } if (! l_current_precinct->imsbtree) { l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager); } else { l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch, manager); } 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 */ } /* bandno */ ++l_res; } /* resno */ ++l_tccp; ++l_tilec; ++l_image_comp; } /* compno */ return OPJ_TRUE; } OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F, sizeof(opj_tcd_cblk_enc_t), p_manager); } OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F, sizeof(opj_tcd_cblk_dec_t), p_manager); } /** * Allocates memory for an encoding code block (but not data memory). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t * p_code_block) { if (! p_code_block->layers) { /* no memset since data */ p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t)); if (! p_code_block->layers) { return OPJ_FALSE; } } if (! p_code_block->passes) { p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t)); if (! p_code_block->passes) { return OPJ_FALSE; } } return OPJ_TRUE; } /** * Allocates data memory for an encoding code block. */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */ /* TODO: is there a theoretical upper-bound for the compressed code */ /* block size ? */ l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } void opj_tcd_reinit_segment(opj_tcd_seg_t* seg) { memset(seg, 0, sizeof(opj_tcd_seg_t)); } /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t * p_code_block) { if (! p_code_block->segs) { p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS, sizeof(opj_tcd_seg_t)); if (! p_code_block->segs) { return OPJ_FALSE; } /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/ p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS; /*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/ } else { /* sanitize */ opj_tcd_seg_t * l_segs = p_code_block->segs; OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs; opj_tcd_seg_data_chunk_t* l_chunks = p_code_block->chunks; OPJ_UINT32 l_numchunksalloc = p_code_block->numchunksalloc; OPJ_UINT32 i; memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t)); p_code_block->segs = l_segs; p_code_block->m_current_max_segs = l_current_max_segs; for (i = 0; i < l_current_max_segs; ++i) { opj_tcd_reinit_segment(&l_segs[i]); } p_code_block->chunks = l_chunks; p_code_block->numchunksalloc = l_numchunksalloc; } return OPJ_TRUE; } OPJ_UINT32 opj_tcd_get_decoded_tile_size(opj_tcd_t *p_tcd) { OPJ_UINT32 i; OPJ_UINT32 l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tcd_resolution_t * l_res = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_temp; l_tile_comp = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i = 0; i < p_tcd->image->numcomps; ++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1; l_temp = (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 - l_res->y0)); /* x1*y1 can't overflow */ if (l_size_comp && UINT_MAX / l_size_comp < l_temp) { return UINT_MAX; } l_temp *= l_size_comp; if (l_temp > UINT_MAX - l_data_size) { return UINT_MAX; } l_data_size += l_temp; ++l_img_comp; ++l_tile_comp; } return l_data_size; } OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BYTE *p_dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_length, opj_codestream_info_t *p_cstr_info, opj_event_mgr_t *p_manager) { if (p_tcd->cur_tp_num == 0) { p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no]; /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */ if (p_cstr_info) { OPJ_UINT32 l_num_packs = 0; OPJ_UINT32 i; opj_tcd_tilecomp_t *l_tilec_idx = &p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */ opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */ for (i = 0; i < l_tilec_idx->numresolutions; i++) { opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i]; p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw; p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph; l_num_packs += l_res_idx->pw * l_res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i]; p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i]; } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc(( size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs, sizeof(opj_packet_info_t)); if (!p_cstr_info->tile[p_tile_no].packet) { /* FIXME event manager error callback */ return OPJ_FALSE; } } /* << INDEX */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ if (! opj_tcd_dc_level_shift_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /* FIXME _ProfStart(PGROUP_RATE); */ if (! opj_tcd_rate_allocate_encode(p_tcd, p_dest, p_max_length, p_cstr_info, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_RATE); */ } /*--------------TIER2------------------*/ /* INDEX */ if (p_cstr_info) { p_cstr_info->index_write = 1; } /* FIXME _ProfStart(PGROUP_T2); */ if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length, p_cstr_info, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*---------------CLEAN-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_decode_tile(opj_tcd_t *p_tcd, OPJ_BYTE *p_src, OPJ_UINT32 p_max_length, OPJ_UINT32 p_tile_no, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager ) { OPJ_UINT32 l_data_read; p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]); #ifdef TODO_MSD /* FIXME */ /* INDEX >> */ if (p_cstr_info) { OPJ_UINT32 resno, compno, numprec = 0; for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) { opj_tcp_t *tcp = &p_tcd->cp->tcps[0]; opj_tccp_t *tccp = &tcp->tccps[compno]; opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno]; for (resno = 0; resno < tilec_idx->numresolutions; resno++) { opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno]; p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw; p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph; numprec += res_idx->pw * res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno]; p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno]; } } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc( p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t)); p_cstr_info->packno = 0; } /* << INDEX */ #endif /*--------------TIER2------------------*/ /* FIXME _ProfStart(PGROUP_T2); */ l_data_read = 0; if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*------------------TIER1-----------------*/ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_decode(p_tcd, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /*----------------DWT---------------------*/ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /*----------------MCT-------------------*/ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_decode(p_tcd, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ if (! opj_tcd_dc_level_shift_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd, OPJ_BYTE * p_dest, OPJ_UINT32 p_dest_length ) { OPJ_UINT32 i, j, k, l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; opj_tcd_resolution_t * l_res; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_stride, l_width, l_height; l_data_size = opj_tcd_get_decoded_tile_size(p_tcd); if (l_data_size == UINT_MAX || l_data_size > p_dest_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i = 0; i < p_tcd->image->numcomps; ++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_res = l_tilec->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width; if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest; const OPJ_INT32 * l_src_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = (OPJ_CHAR)(*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = (OPJ_CHAR)((*(l_src_ptr++)) & 0xff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE *)l_dest_ptr; } break; case 2: { const OPJ_INT32 * l_src_ptr = l_tilec->data; OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest; if (l_img_comp->sgnd) { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { OPJ_INT16 val = (OPJ_INT16)(*(l_src_ptr++)); memcpy(l_dest_ptr, &val, sizeof(val)); l_dest_ptr ++; } l_src_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { OPJ_INT16 val = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff); memcpy(l_dest_ptr, &val, sizeof(val)); l_dest_ptr ++; } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; case 4: { OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest; OPJ_INT32 * l_src_ptr = l_tilec->data; for (j = 0; j < l_height; ++j) { memcpy(l_dest_ptr, l_src_ptr, l_width * sizeof(OPJ_INT32)); l_dest_ptr += l_width; l_src_ptr += l_width + l_stride; } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; } static void opj_tcd_free_tile(opj_tcd_t *p_tcd) { OPJ_UINT32 compno, resno, bandno, precno; opj_tcd_tile_t *l_tile = 00; opj_tcd_tilecomp_t *l_tile_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_tcd_precinct_t *l_precinct = 00; OPJ_UINT32 l_nb_resolutions, l_nb_precincts; void (* l_tcd_code_block_deallocate)(opj_tcd_precinct_t *) = 00; if (! p_tcd) { return; } if (! p_tcd->tcd_image) { return; } if (p_tcd->m_is_decoder) { l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate; } else { l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate; } l_tile = p_tcd->tcd_image->tiles; if (! l_tile) { return; } l_tile_comp = l_tile->comps; for (compno = 0; compno < l_tile->numcomps; ++compno) { l_res = l_tile_comp->resolutions; if (l_res) { l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t); for (resno = 0; resno < l_nb_resolutions; ++resno) { l_band = l_res->bands; for (bandno = 0; bandno < 3; ++bandno) { l_precinct = l_band->precincts; if (l_precinct) { l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t); for (precno = 0; precno < l_nb_precincts; ++precno) { opj_tgt_destroy(l_precinct->incltree); l_precinct->incltree = 00; opj_tgt_destroy(l_precinct->imsbtree); l_precinct->imsbtree = 00; (*l_tcd_code_block_deallocate)(l_precinct); ++l_precinct; } opj_free(l_band->precincts); l_band->precincts = 00; } ++l_band; } /* for (resno */ ++l_res; } opj_free(l_tile_comp->resolutions); l_tile_comp->resolutions = 00; } if (l_tile_comp->ownsData && l_tile_comp->data) { opj_image_data_free(l_tile_comp->data); l_tile_comp->data = 00; l_tile_comp->ownsData = 0; l_tile_comp->data_size = 0; l_tile_comp->data_size_needed = 0; } ++l_tile_comp; } opj_free(l_tile->comps); l_tile->comps = 00; opj_free(p_tcd->tcd_image->tiles); p_tcd->tcd_image->tiles = 00; } static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_decode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_src_data, p_data_read, p_max_src_size, p_cstr_index, p_manager)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager) { OPJ_UINT32 compno; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; volatile OPJ_BOOL ret = OPJ_TRUE; OPJ_BOOL check_pterm = OPJ_FALSE; opj_mutex_t* p_manager_mutex = NULL; p_manager_mutex = opj_mutex_create(); /* Only enable PTERM check if we decode all layers */ if (p_tcd->tcp->num_layers_to_decode == p_tcd->tcp->numlayers && (l_tccp->cblksty & J2K_CCP_CBLKSTY_PTERM) != 0) { check_pterm = OPJ_TRUE; } for (compno = 0; compno < l_tile->numcomps; ++compno) { opj_t1_decode_cblks(p_tcd->thread_pool, &ret, l_tile_comp, l_tccp, p_manager, p_manager_mutex, check_pterm); if (!ret) { break; } ++l_tile_comp; ++l_tccp; } opj_thread_pool_wait_completion(p_tcd->thread_pool, 0); if (p_manager_mutex) { opj_mutex_destroy(p_manager_mutex); } return ret; } static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd) { OPJ_UINT32 compno; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; opj_image_comp_t * l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { /* if (tcd->cp->reduce != 0) { tcd->image->comps[compno].resno_decoded = tile->comps[compno].numresolutions - tcd->cp->reduce - 1; if (tcd->image->comps[compno].resno_decoded < 0) { return false; } } numres2decode = tcd->image->comps[compno].resno_decoded + 1; if(numres2decode > 0){ */ if (l_tccp->qmfbid == 1) { if (! opj_dwt_decode(p_tcd->thread_pool, l_tile_comp, l_img_comp->resno_decoded + 1)) { return OPJ_FALSE; } } else { if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded + 1)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_img_comp; ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcp_t * l_tcp = p_tcd->tcp; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; OPJ_UINT32 l_samples, i; if (! l_tcp->mct) { return OPJ_TRUE; } l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tile->numcomps >= 3) { /* testcase 1336.pdf.asan.47.376 */ if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples || (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples || (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) { opj_event_msg(p_manager, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n"); return OPJ_FALSE; } else if (l_tcp->mct == 2) { OPJ_BYTE ** l_data; if (! l_tcp->m_mct_decoding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i = 0; i < l_tile->numcomps; ++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_decode_custom(/* MCT data */ (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix, /* size of components */ l_samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd)) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else { if (l_tcp->tccps->qmfbid == 1) { opj_mct_decode(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, l_samples); } else { opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data, (OPJ_FLOAT32*)l_tile->comps[1].data, (OPJ_FLOAT32*)l_tile->comps[2].data, l_samples); } } } else { opj_event_msg(p_manager, EVT_ERROR, "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n", l_tile->numcomps); } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_resolution_t* l_res = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_width, l_height, i, j; OPJ_INT32 * l_current_ptr; OPJ_INT32 l_min, l_max; OPJ_UINT32 l_stride; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width; assert(l_height == 0 || l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/ if (l_img_comp->sgnd) { l_min = -(1 << (l_img_comp->prec - 1)); l_max = (1 << (l_img_comp->prec - 1)) - 1; } else { l_min = 0; l_max = (OPJ_INT32)((1U << l_img_comp->prec) - 1); } l_current_ptr = l_tile_comp->data; if (l_tccp->qmfbid == 1) { for (j = 0; j < l_height; ++j) { for (i = 0; i < l_width; ++i) { *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min, l_max); ++l_current_ptr; } l_current_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (i = 0; i < l_width; ++i) { OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr); OPJ_INT32 l_value_int = (OPJ_INT32)opj_lrintf(l_value); if (l_value > INT_MAX || (l_value_int > 0 && l_tccp->m_dc_level_shift > 0 && l_value_int > INT_MAX - l_tccp->m_dc_level_shift)) { *l_current_ptr = l_max; } else { *l_current_ptr = opj_int_clamp( l_value_int + l_tccp->m_dc_level_shift, l_min, l_max); } ++l_current_ptr; } l_current_ptr += l_stride; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno, l_nb_code_blocks; opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec; if (l_code_block) { /*fprintf(stderr,"deallocate codeblock:{\n");*/ /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/ /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ", l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/ l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t); /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/ for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->segs) { opj_free(l_code_block->segs); l_code_block->segs = 00; } if (l_code_block->chunks) { opj_free(l_code_block->chunks); l_code_block->chunks = 00; } ++l_code_block; } opj_free(p_precinct->cblks.dec); p_precinct->cblks.dec = 00; } } /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno, l_nb_code_blocks; opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc; if (l_code_block) { l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t); for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { /* We refer to data - 1 since below we incremented it */ /* in opj_tcd_code_block_enc_allocate_data() */ opj_free(l_code_block->data - 1); l_code_block->data = 00; } if (l_code_block->layers) { opj_free(l_code_block->layers); l_code_block->layers = 00; } if (l_code_block->passes) { opj_free(l_code_block->passes); l_code_block->passes = 00; } ++l_code_block; } opj_free(p_precinct->cblks.enc); p_precinct->cblks.enc = 00; } } OPJ_UINT32 opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd) { OPJ_UINT32 i, l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i = 0; i < p_tcd->image->numcomps; ++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); ++l_img_comp; ++l_tilec; } return l_data_size; } static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_nb_elem, i; OPJ_INT32 * l_current_ptr; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_current_ptr = l_tile_comp->data; l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tccp->qmfbid == 1) { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr -= l_tccp->m_dc_level_shift ; ++l_current_ptr; } } else { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11); ++l_current_ptr; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); OPJ_UINT32 i; OPJ_BYTE ** l_data = 00; opj_tcp_t * l_tcp = p_tcd->tcp; if (!p_tcd->tcp->mct) { return OPJ_TRUE; } if (p_tcd->tcp->mct == 2) { if (! p_tcd->tcp->m_mct_coding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i = 0; i < l_tile->numcomps; ++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_encode_custom(/* MCT data */ (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix, /* size of components */ samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd)) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else if (l_tcp->tccps->qmfbid == 0) { opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } else { opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; OPJ_UINT32 compno; for (compno = 0; compno < l_tile->numcomps; ++compno) { if (l_tccp->qmfbid == 1) { if (! opj_dwt_encode(l_tile_comp)) { return OPJ_FALSE; } } else if (l_tccp->qmfbid == 0) { if (! opj_dwt_encode_real(l_tile_comp)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd) { opj_t1_t * l_t1; const OPJ_FLOAT64 * l_mct_norms; OPJ_UINT32 l_mct_numcomps = 0U; opj_tcp_t * l_tcp = p_tcd->tcp; l_t1 = opj_t1_create(OPJ_TRUE); if (l_t1 == 00) { return OPJ_FALSE; } if (l_tcp->mct == 1) { l_mct_numcomps = 3U; /* irreversible encoding */ if (l_tcp->tccps->qmfbid == 0) { l_mct_norms = opj_mct_get_mct_norms_real(); } else { l_mct_norms = opj_mct_get_mct_norms(); } } else { l_mct_numcomps = p_tcd->image->numcomps; l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms); } if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms, l_mct_numcomps)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } opj_t1_destroy(l_t1); return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info, opj_event_mgr_t *p_manager) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_encode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_tcd->tcp->numlayers, p_dest_data, p_data_written, p_max_dest_size, p_cstr_info, p_tcd->tp_num, p_tcd->tp_pos, p_tcd->cur_pino, FINAL_PASS, p_manager)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info, opj_event_mgr_t *p_manager) { opj_cp_t * l_cp = p_tcd->cp; OPJ_UINT32 l_nb_written = 0; if (p_cstr_info) { p_cstr_info->index_write = 0; } if (l_cp->m_specific_param.m_enc.m_disto_alloc || l_cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ /* Normal Rate/distortion allocation */ if (! opj_tcd_rateallocate(p_tcd, p_dest_data, &l_nb_written, p_max_dest_size, p_cstr_info, p_manager)) { return OPJ_FALSE; } } else { /* Fixed layer allocation */ opj_tcd_rateallocate_fixed(p_tcd); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd, OPJ_BYTE * p_src, OPJ_UINT32 p_src_length) { OPJ_UINT32 i, j, l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_nb_elem; l_data_size = opj_tcd_get_encoded_tile_size(p_tcd); if (l_data_size != p_src_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i = 0; i < p_tcd->image->numcomps; ++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j = 0; j < l_nb_elem; ++j) { *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++)); } } else { for (j = 0; j < l_nb_elem; ++j) { *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 2: { OPJ_INT32 * l_dest_ptr = l_tilec->data; OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src; if (l_img_comp->sgnd) { for (j = 0; j < l_nb_elem; ++j) { *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++)); } } else { for (j = 0; j < l_nb_elem; ++j) { *(l_dest_ptr++) = (*(l_src_ptr++)) & 0xffff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 4: { OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; for (j = 0; j < l_nb_elem; ++j) { *(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++)); } p_src = (OPJ_BYTE*) l_src_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; } OPJ_BOOL opj_tcd_is_band_empty(opj_tcd_band_t* band) { return (band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2774_0
crossvul-cpp_data_good_5475_2
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Scanline-oriented Write Support */ #include "tiffiop.h" #include <stdio.h> #define STRIPINCR 20 /* expansion factor on strip array */ #define WRITECHECKSTRIPS(tif, module) \ (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module)) #define WRITECHECKTILES(tif, module) \ (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module)) #define BUFFERCHECK(tif) \ ((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \ TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1)) static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module); static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc); int TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { static const char module[] = "TIFFWriteScanline"; register TIFFDirectory *td; int status, imagegrew = 0; uint32 strip; if (!WRITECHECKSTRIPS(tif, module)) return (-1); /* * Handle delayed allocation of data buffer. This * permits it to be sized more intelligently (using * directory information). */ if (!BUFFERCHECK(tif)) return (-1); tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/ td = &tif->tif_dir; /* * Extend image length if needed * (but only for PlanarConfig=1). */ if (row >= td->td_imagelength) { /* extend image */ if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not change \"ImageLength\" when using separate planes"); return (-1); } td->td_imagelength = row+1; imagegrew = 1; } /* * Calculate strip and check for crossings. */ if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (-1); } strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; /* * Check strip array to make sure there's space. We don't support * dynamically growing files that have data organized in separate * bitplanes because it's too painful. In that case we require that * the imagelength be set properly before the first write (so that the * strips array will be fully allocated above). */ if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module)) return (-1); if (strip != tif->tif_curstrip) { /* * Changing strips -- flush any data present. */ if (!TIFFFlushData(tif)) return (-1); tif->tif_curstrip = strip; /* * Watch out for a growing image. The value of strips/image * will initially be 1 (since it can't be deduced until the * imagelength is known). */ if (strip >= td->td_stripsperimage && imagegrew) td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip); if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image"); return (-1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return (-1); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; if( td->td_stripbytecount[strip] > 0 ) { /* if we are writing over existing tiles, zero length */ td->td_stripbytecount[strip] = 0; /* this forces TIFFAppendToStrip() to do a seek */ tif->tif_curoff = 0; } if (!(*tif->tif_preencode)(tif, sample)) return (-1); tif->tif_flags |= TIFF_POSTENCODE; } /* * Ensure the write is either sequential or at the * beginning of a strip (or that we can randomly * access the data -- i.e. no encoding). */ if (row != tif->tif_row) { if (row < tif->tif_row) { /* * Moving backwards within the same strip: * backup to the start and then decode * forward (below). */ tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; tif->tif_rawcp = tif->tif_rawdata; } /* * Seek forward to the desired row. */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (-1); tif->tif_row = row; } /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize ); status = (*tif->tif_encoderow)(tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; return (status); } /* * Encode the supplied data and write it to the * specified strip. * * NB: Image length must be setup before writing. */ tmsize_t TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint16 sample; if (!WRITECHECKSTRIPS(tif, module)) return ((tmsize_t) -1); /* * Check strip array to make sure there's space. * We don't support dynamically growing files that * have data organized in separate bitplanes because * it's too painful. In that case we require that * the imagelength be set properly before the first * write (so that the strips array will be fully * allocated above). */ if (strip >= td->td_nstrips) { if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not grow image by strips when using separate planes"); return ((tmsize_t) -1); } if (!TIFFGrowStrips(tif, 1, module)) return ((tmsize_t) -1); td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip); } /* * Handle delayed allocation of data buffer. This * permits it to be sized according to the directory * info. */ if (!BUFFERCHECK(tif)) return ((tmsize_t) -1); tif->tif_flags |= TIFF_BUF4WRITE; tif->tif_curstrip = strip; if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image"); return ((tmsize_t) -1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return ((tmsize_t) -1); tif->tif_flags |= TIFF_CODERSETUP; } if( td->td_stripbytecount[strip] > 0 ) { /* Make sure that at the first attempt of rewriting the tile, we will have */ /* more bytes available in the output buffer than the previous byte count, */ /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */ /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */ if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] ) { if( !(TIFFWriteBufferSetup(tif, NULL, (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) ) return ((tmsize_t)(-1)); } /* Force TIFFAppendToStrip() to consider placing data at end of file. */ tif->tif_curoff = 0; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; tif->tif_flags &= ~TIFF_POSTENCODE; /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE ) { /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*) data, cc); if (cc > 0 && !TIFFAppendToStrip(tif, strip, (uint8*) data, cc)) return ((tmsize_t) -1); return (cc); } sample = (uint16)(strip / td->td_stripsperimage); if (!(*tif->tif_preencode)(tif, sample)) return ((tmsize_t) -1); /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample)) return ((tmsize_t) -1); if (!(*tif->tif_postencode)(tif)) return ((tmsize_t) -1); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc); if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc)) return ((tmsize_t) -1); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (cc); } /* * Write the supplied data to the specified strip. * * NB: Image length must be setup before writing. */ tmsize_t TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteRawStrip"; TIFFDirectory *td = &tif->tif_dir; if (!WRITECHECKSTRIPS(tif, module)) return ((tmsize_t) -1); /* * Check strip array to make sure there's space. * We don't support dynamically growing files that * have data organized in separate bitplanes because * it's too painful. In that case we require that * the imagelength be set properly before the first * write (so that the strips array will be fully * allocated above). */ if (strip >= td->td_nstrips) { if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not grow image by strips when using separate planes"); return ((tmsize_t) -1); } /* * Watch out for a growing image. The value of * strips/image will initially be 1 (since it * can't be deduced until the imagelength is known). */ if (strip >= td->td_stripsperimage) td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip); if (!TIFFGrowStrips(tif, 1, module)) return ((tmsize_t) -1); } tif->tif_curstrip = strip; if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image"); return ((tmsize_t) -1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ? cc : (tmsize_t) -1); } /* * Write and compress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); /* * NB: A tile size of -1 is used instead of tif_tilesize knowing * that TIFFWriteEncodedTile will clamp this to the tile size. * This is done because the tile size may not be defined until * after the output buffer is setup in TIFFWriteBufferSetup. */ return (TIFFWriteEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Encode the supplied data and write it to the * specified tile. There must be space for the * data. The function clamps individual writes * to a tile to the tile size, but does not (and * can not) check that multiple writes to the same * tile do not write more than tile size data. * * NB: Image length must be setup before writing; this * interface does not support automatically growing * the image on each write (as TIFFWriteScanline does). */ tmsize_t TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteEncodedTile"; TIFFDirectory *td; uint16 sample; uint32 howmany32; if (!WRITECHECKTILES(tif, module)) return ((tmsize_t)(-1)); td = &tif->tif_dir; if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } /* * Handle delayed allocation of data buffer. This * permits it to be sized more intelligently (using * directory information). */ if (!BUFFERCHECK(tif)) return ((tmsize_t)(-1)); tif->tif_flags |= TIFF_BUF4WRITE; tif->tif_curtile = tile; if( td->td_stripbytecount[tile] > 0 ) { /* Make sure that at the first attempt of rewriting the tile, we will have */ /* more bytes available in the output buffer than the previous byte count, */ /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */ /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */ if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] ) { if( !(TIFFWriteBufferSetup(tif, NULL, (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) ) return ((tmsize_t)(-1)); } /* Force TIFFAppendToStrip() to consider placing data at end of file. */ tif->tif_curoff = 0; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; /* * Compute tiles per row & per column to compute * current row and column */ howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return ((tmsize_t)(-1)); } tif->tif_row = (tile % howmany32) * td->td_tilelength; howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return ((tmsize_t)(-1)); } tif->tif_col = (tile % howmany32) * td->td_tilewidth; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return ((tmsize_t)(-1)); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_flags &= ~TIFF_POSTENCODE; /* * Clamp write amount to the tile size. This is mostly * done so that callers can pass in some large number * (e.g. -1) and have the tile size used instead. */ if ( cc < 1 || cc > tif->tif_tilesize) cc = tif->tif_tilesize; /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE ) { /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*) data, cc); if (cc > 0 && !TIFFAppendToStrip(tif, tile, (uint8*) data, cc)) return ((tmsize_t) -1); return (cc); } sample = (uint16)(tile/td->td_stripsperimage); if (!(*tif->tif_preencode)(tif, sample)) return ((tmsize_t)(-1)); /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample)) return ((tmsize_t) -1); if (!(*tif->tif_postencode)(tif)) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile, tif->tif_rawdata, tif->tif_rawcc)) return ((tmsize_t)(-1)); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (cc); } /* * Write the supplied data to the specified strip. * There must be space for the data; we don't check * if strips overlap! * * NB: Image length must be setup before writing; this * interface does not support automatically growing * the image on each write (as TIFFWriteScanline does). */ tmsize_t TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteRawTile"; if (!WRITECHECKTILES(tif, module)) return ((tmsize_t)(-1)); if (tile >= tif->tif_dir.td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu", (unsigned long) tile, (unsigned long) tif->tif_dir.td_nstrips); return ((tmsize_t)(-1)); } return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ? cc : (tmsize_t)(-1)); } #define isUnspecified(tif, f) \ (TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0) int TIFFSetupStrips(TIFF* tif) { TIFFDirectory* td = &tif->tif_dir; if (isTiled(tif)) td->td_stripsperimage = isUnspecified(tif, FIELD_TILEDIMENSIONS) ? td->td_samplesperpixel : TIFFNumberOfTiles(tif); else td->td_stripsperimage = isUnspecified(tif, FIELD_ROWSPERSTRIP) ? td->td_samplesperpixel : TIFFNumberOfStrips(tif); td->td_nstrips = td->td_stripsperimage; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; td->td_stripoffset = (uint64 *) _TIFFmalloc(td->td_nstrips * sizeof (uint64)); td->td_stripbytecount = (uint64 *) _TIFFmalloc(td->td_nstrips * sizeof (uint64)); if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL) return (0); /* * Place data at the end-of-file * (by setting offsets to zero). */ _TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64)); _TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64)); TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); return (1); } #undef isUnspecified /* * Verify file is writable and that the directory * information is setup properly. In doing the latter * we also "freeze" the state of the directory so * that important information is not changed. */ int TIFFWriteCheck(TIFF* tif, int tiles, const char* module) { if (tif->tif_mode == O_RDONLY) { TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, module, tiles ? "Can not write tiles to a stripped image" : "Can not write scanlines to a tiled image"); return (0); } _TIFFFillStriles( tif ); /* * On the first write verify all the required information * has been setup and initialize any data structures that * had to wait until directory information was set. * Note that a lot of our work is assumed to remain valid * because we disallow any of the important parameters * from changing after we start writing (i.e. once * TIFF_BEENWRITING is set, TIFFSetField will only allow * the image's length to be changed). */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { TIFFErrorExt(tif->tif_clientdata, module, "Must set \"ImageWidth\" before writing data"); return (0); } if (tif->tif_dir.td_samplesperpixel == 1) { /* * Planarconfiguration is irrelevant in case of single band * images and need not be included. We will set it anyway, * because this field is used in other parts of library even * in the single band case. */ if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG; } else { if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { TIFFErrorExt(tif->tif_clientdata, module, "Must set \"PlanarConfiguration\" before writing data"); return (0); } } if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) { tif->tif_dir.td_nstrips = 0; TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays", isTiled(tif) ? "tile" : "strip"); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (tif->tif_tilesize == 0) return (0); } else tif->tif_tilesize = (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); if (tif->tif_scanlinesize == 0) return (0); tif->tif_flags |= TIFF_BEENWRITING; return (1); } /* * Setup the raw data buffer used for encoding. */ int TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFWriteBufferSetup"; if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) { _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; } tif->tif_rawdata = NULL; } if (size == (tmsize_t)(-1)) { size = (isTiled(tif) ? tif->tif_tilesize : TIFFStripSize(tif)); /* * Make raw data buffer at least 8K */ if (size < 8*1024) size = 8*1024; bp = NULL; /* NB: force malloc */ } if (bp == NULL) { bp = _TIFFmalloc(size); if (bp == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer"); return (0); } tif->tif_flags |= TIFF_MYBUFFER; } else tif->tif_flags &= ~TIFF_MYBUFFER; tif->tif_rawdata = (uint8*) bp; tif->tif_rawdatasize = size; tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; tif->tif_flags |= TIFF_BUFFERSETUP; return (1); } /* * Grow the strip data structures by delta strips. */ static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module) { TIFFDirectory *td = &tif->tif_dir; uint64* new_stripoffset; uint64* new_stripbytecount; assert(td->td_planarconfig == PLANARCONFIG_CONTIG); new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset, (td->td_nstrips + delta) * sizeof (uint64)); new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount, (td->td_nstrips + delta) * sizeof (uint64)); if (new_stripoffset == NULL || new_stripbytecount == NULL) { if (new_stripoffset) _TIFFfree(new_stripoffset); if (new_stripbytecount) _TIFFfree(new_stripbytecount); td->td_nstrips = 0; TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays"); return (0); } td->td_stripoffset = new_stripoffset; td->td_stripbytecount = new_stripbytecount; _TIFFmemset(td->td_stripoffset + td->td_nstrips, 0, delta*sizeof (uint64)); _TIFFmemset(td->td_stripbytecount + td->td_nstrips, 0, delta*sizeof (uint64)); td->td_nstrips += delta; tif->tif_flags |= TIFF_DIRTYDIRECT; return (1); } /* * Append the data to the specified strip. */ static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc) { static const char module[] = "TIFFAppendToStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 m; int64 old_byte_count = -1; if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) { assert(td->td_nstrips > 0); if( td->td_stripbytecount[strip] != 0 && td->td_stripoffset[strip] != 0 && td->td_stripbytecount[strip] >= (uint64) cc ) { /* * There is already tile data on disk, and the new tile * data we have will fit in the same space. The only * aspect of this that is risky is that there could be * more data to append to this strip before we are done * depending on how we are getting called. */ if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu", (unsigned long)tif->tif_row); return (0); } } else { /* * Seek to end of file, and set that as our location to * write this strip. */ td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END); tif->tif_flags |= TIFF_DIRTYSTRIP; } tif->tif_curoff = td->td_stripoffset[strip]; /* * We are starting a fresh strip/tile, so set the size to zero. */ old_byte_count = td->td_stripbytecount[strip]; td->td_stripbytecount[strip] = 0; } m = tif->tif_curoff+cc; if (!(tif->tif_flags&TIFF_BIGTIFF)) m = (uint32)m; if ((m<tif->tif_curoff)||(m<(uint64)cc)) { TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded"); return (0); } if (!WriteOK(tif, data, cc)) { TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu", (unsigned long) tif->tif_row); return (0); } tif->tif_curoff = m; td->td_stripbytecount[strip] += cc; if( (int64) td->td_stripbytecount[strip] != old_byte_count ) tif->tif_flags |= TIFF_DIRTYSTRIP; return (1); } /* * Internal version of TIFFFlushData that can be * called by ``encodestrip routines'' w/o concern * for infinite recursion. */ int TIFFFlushData1(TIFF* tif) { if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) { if (!isFillOrder(tif, tif->tif_dir.td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (!TIFFAppendToStrip(tif, isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, tif->tif_rawdata, tif->tif_rawcc)) { /* We update those variables even in case of error since there's */ /* code that doesn't really check the return code of this */ /* function */ tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (0); } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; } return (1); } /* * Set the current write offset. This should only be * used to set the offset to a known previous location * (very carefully), or to 0 so that the next write gets * appended to the end of the file. */ void TIFFSetWriteOffset(TIFF* tif, toff_t off) { tif->tif_curoff = off; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5475_2
crossvul-cpp_data_bad_634_6
/************************************************** * SQLCreateDataSource * * This is a 100% UI so simply pass it on to odbcinst's UI * shadow share. * ************************************************** * This code was created by Peter Harvey @ CodeByDesign. * Released under LGPL 28.JAN.99 * * Contributions from... * ----------------------------------------------- * Peter Harvey - pharvey@codebydesign.com **************************************************/ #include <config.h> #include <odbcinstext.h> /* * Take a wide string consisting of null terminated sections, and copy to a ASCII version */ char* _multi_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { len ++; } chr = malloc( len + 2 ); len = 0; while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; chr[ len ++ ] = '\0'; return chr; } char* _single_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( len + 1 ); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; return chr; } SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { len ++; } chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 )); len = 0; while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; chr[ len ++ ] = 0; return chr; } SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 )); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; return chr; } void _single_string_copy_to_wide( SQLWCHAR *out, LPCSTR in, int len ) { while ( len > 0 && *in ) { *out = *in; out++; in++; len --; } *out = 0; } void _single_copy_to_wide( SQLWCHAR *out, LPCSTR in, int len ) { while ( len >= 0 ) { *out = *in; out++; in++; len --; } } void _single_copy_from_wide( SQLCHAR *out, LPCWSTR in, int len ) { while ( len >= 0 ) { *out = *in; out++; in++; len --; } } void _multi_string_copy_to_wide( SQLWCHAR *out, LPCSTR in, int len ) { while ( len > 0 && ( in[ 0 ] || in[ 1 ] )) { *out = *in; out++; in++; len --; } *out++ = 0; *out++ = 0; } /*! * \brief Invokes a UI (a wizard) to walk User through creating a DSN. * * \param hWnd Input. Parent window handle. This is HWND as per the ODBC * specification but in unixODBC we use a generic window * handle. Caller must cast a HODBCINSTWND to HWND at call. * \param pszDS Input. Data Source Name. This can be a NULL pointer. * * \return BOOL * * \sa ODBCINSTWND */ BOOL SQLCreateDataSource( HWND hWnd, LPCSTR pszDS ) { HODBCINSTWND hODBCInstWnd = (HODBCINSTWND)hWnd; char szName[FILENAME_MAX]; char szNameAndExtension[FILENAME_MAX]; char szPathAndName[FILENAME_MAX]; void * hDLL; BOOL (*pSQLCreateDataSource)(HWND, LPCSTR); inst_logClear(); /* ODBC specification states that hWnd is mandatory. */ if ( !hWnd ) { inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_HWND, "" ); return FALSE; } /* initialize libtool */ if ( lt_dlinit() ) { inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "lt_dlinit() failed" ); return FALSE; } /* get plugin name */ _appendUIPluginExtension( szNameAndExtension, _getUIPluginName( szName, hODBCInstWnd->szUI ) ); /* lets try loading the plugin using an implicit path */ hDLL = lt_dlopen( szNameAndExtension ); if ( hDLL ) { /* change the name, as it avoids it finding it in the calling lib */ pSQLCreateDataSource = (BOOL (*)(HWND, LPCSTR))lt_dlsym( hDLL, "ODBCCreateDataSource" ); if ( pSQLCreateDataSource ) return pSQLCreateDataSource( ( *(hODBCInstWnd->szUI) ? hODBCInstWnd->hWnd : NULL ), pszDS ); else inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, (char*)lt_dlerror() ); } else { /* try with explicit path */ _prependUIPluginPath( szPathAndName, szNameAndExtension ); hDLL = lt_dlopen( szPathAndName ); if ( hDLL ) { /* change the name, as it avoids linker finding it in the calling lib */ pSQLCreateDataSource = (BOOL (*)(HWND,LPCSTR))lt_dlsym( hDLL, "ODBCCreateDataSource" ); if ( pSQLCreateDataSource ) return pSQLCreateDataSource( ( *(hODBCInstWnd->szUI) ? hODBCInstWnd->hWnd : NULL ), pszDS ); else inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, (char*)lt_dlerror() ); } } /* report failure to caller */ inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_GENERAL_ERR, "" ); return FALSE; } /*! * \brief A wide char version of \sa SQLCreateDataSource. * * \sa SQLCreateDataSource */ BOOL INSTAPI SQLCreateDataSourceW( HWND hwndParent, LPCWSTR lpszDSN ) { BOOL ret; char *ms = _multi_string_alloc_and_copy( lpszDSN ); inst_logClear(); ret = SQLCreateDataSource( hwndParent, ms ); free( ms ); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_634_6
crossvul-cpp_data_bad_3020_2
/* * Copyright (c) 2014-2015 Hisilicon Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/cdev.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <asm/cacheflush.h> #include <linux/platform_device.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include <linux/of_irq.h> #include <linux/spinlock.h> #include "hns_dsaf_main.h" #include "hns_dsaf_ppe.h" #include "hns_dsaf_rcb.h" #define RCB_COMMON_REG_OFFSET 0x80000 #define TX_RING 0 #define RX_RING 1 #define RCB_RESET_WAIT_TIMES 30 #define RCB_RESET_TRY_TIMES 10 /* Because default mtu is 1500, rcb buffer size is set to 2048 enough */ #define RCB_DEFAULT_BUFFER_SIZE 2048 /** *hns_rcb_wait_fbd_clean - clean fbd *@qs: ring struct pointer array *@qnum: num of array *@flag: tx or rx flag */ void hns_rcb_wait_fbd_clean(struct hnae_queue **qs, int q_num, u32 flag) { int i, wait_cnt; u32 fbd_num; for (wait_cnt = i = 0; i < q_num; wait_cnt++) { usleep_range(200, 300); fbd_num = 0; if (flag & RCB_INT_FLAG_TX) fbd_num += dsaf_read_dev(qs[i], RCB_RING_TX_RING_FBDNUM_REG); if (flag & RCB_INT_FLAG_RX) fbd_num += dsaf_read_dev(qs[i], RCB_RING_RX_RING_FBDNUM_REG); if (!fbd_num) i++; if (wait_cnt >= 10000) break; } if (i < q_num) dev_err(qs[i]->handle->owner_dev, "queue(%d) wait fbd(%d) clean fail!!\n", i, fbd_num); } /** *hns_rcb_reset_ring_hw - ring reset *@q: ring struct pointer */ void hns_rcb_reset_ring_hw(struct hnae_queue *q) { u32 wait_cnt; u32 try_cnt = 0; u32 could_ret; u32 tx_fbd_num; while (try_cnt++ < RCB_RESET_TRY_TIMES) { usleep_range(100, 200); tx_fbd_num = dsaf_read_dev(q, RCB_RING_TX_RING_FBDNUM_REG); if (tx_fbd_num) continue; dsaf_write_dev(q, RCB_RING_PREFETCH_EN_REG, 0); dsaf_write_dev(q, RCB_RING_T0_BE_RST, 1); msleep(20); could_ret = dsaf_read_dev(q, RCB_RING_COULD_BE_RST); wait_cnt = 0; while (!could_ret && (wait_cnt < RCB_RESET_WAIT_TIMES)) { dsaf_write_dev(q, RCB_RING_T0_BE_RST, 0); dsaf_write_dev(q, RCB_RING_T0_BE_RST, 1); msleep(20); could_ret = dsaf_read_dev(q, RCB_RING_COULD_BE_RST); wait_cnt++; } dsaf_write_dev(q, RCB_RING_T0_BE_RST, 0); if (could_ret) break; } if (try_cnt >= RCB_RESET_TRY_TIMES) dev_err(q->dev->dev, "port%d reset ring fail\n", hns_ae_get_vf_cb(q->handle)->port_index); } /** *hns_rcb_int_ctrl_hw - rcb irq enable control *@q: hnae queue struct pointer *@flag:ring flag tx or rx *@mask:mask */ void hns_rcb_int_ctrl_hw(struct hnae_queue *q, u32 flag, u32 mask) { u32 int_mask_en = !!mask; if (flag & RCB_INT_FLAG_TX) { dsaf_write_dev(q, RCB_RING_INTMSK_TXWL_REG, int_mask_en); dsaf_write_dev(q, RCB_RING_INTMSK_TX_OVERTIME_REG, int_mask_en); } if (flag & RCB_INT_FLAG_RX) { dsaf_write_dev(q, RCB_RING_INTMSK_RXWL_REG, int_mask_en); dsaf_write_dev(q, RCB_RING_INTMSK_RX_OVERTIME_REG, int_mask_en); } } void hns_rcb_int_clr_hw(struct hnae_queue *q, u32 flag) { if (flag & RCB_INT_FLAG_TX) { dsaf_write_dev(q, RCB_RING_INTSTS_TX_RING_REG, 1); dsaf_write_dev(q, RCB_RING_INTSTS_TX_OVERTIME_REG, 1); } if (flag & RCB_INT_FLAG_RX) { dsaf_write_dev(q, RCB_RING_INTSTS_RX_RING_REG, 1); dsaf_write_dev(q, RCB_RING_INTSTS_RX_OVERTIME_REG, 1); } } void hns_rcbv2_int_ctrl_hw(struct hnae_queue *q, u32 flag, u32 mask) { u32 int_mask_en = !!mask; if (flag & RCB_INT_FLAG_TX) dsaf_write_dev(q, RCB_RING_INTMSK_TXWL_REG, int_mask_en); if (flag & RCB_INT_FLAG_RX) dsaf_write_dev(q, RCB_RING_INTMSK_RXWL_REG, int_mask_en); } void hns_rcbv2_int_clr_hw(struct hnae_queue *q, u32 flag) { if (flag & RCB_INT_FLAG_TX) dsaf_write_dev(q, RCBV2_TX_RING_INT_STS_REG, 1); if (flag & RCB_INT_FLAG_RX) dsaf_write_dev(q, RCBV2_RX_RING_INT_STS_REG, 1); } /** *hns_rcb_ring_enable_hw - enable ring *@ring: rcb ring */ void hns_rcb_ring_enable_hw(struct hnae_queue *q, u32 val) { dsaf_write_dev(q, RCB_RING_PREFETCH_EN_REG, !!val); } void hns_rcb_start(struct hnae_queue *q, u32 val) { hns_rcb_ring_enable_hw(q, val); } /** *hns_rcb_common_init_commit_hw - make rcb common init completed *@rcb_common: rcb common device */ void hns_rcb_common_init_commit_hw(struct rcb_common_cb *rcb_common) { wmb(); /* Sync point before breakpoint */ dsaf_write_dev(rcb_common, RCB_COM_CFG_SYS_FSH_REG, 1); wmb(); /* Sync point after breakpoint */ } /* hns_rcb_set_tx_ring_bs - init rcb ring buf size regester *@q: hnae_queue *@buf_size: buffer size set to hw */ void hns_rcb_set_tx_ring_bs(struct hnae_queue *q, u32 buf_size) { u32 bd_size_type = hns_rcb_buf_size2type(buf_size); dsaf_write_dev(q, RCB_RING_TX_RING_BD_LEN_REG, bd_size_type); } /* hns_rcb_set_rx_ring_bs - init rcb ring buf size regester *@q: hnae_queue *@buf_size: buffer size set to hw */ void hns_rcb_set_rx_ring_bs(struct hnae_queue *q, u32 buf_size) { u32 bd_size_type = hns_rcb_buf_size2type(buf_size); dsaf_write_dev(q, RCB_RING_RX_RING_BD_LEN_REG, bd_size_type); } /** *hns_rcb_ring_init - init rcb ring *@ring_pair: ring pair control block *@ring_type: ring type, RX_RING or TX_RING */ static void hns_rcb_ring_init(struct ring_pair_cb *ring_pair, int ring_type) { struct hnae_queue *q = &ring_pair->q; struct hnae_ring *ring = (ring_type == RX_RING) ? &q->rx_ring : &q->tx_ring; dma_addr_t dma = ring->desc_dma_addr; if (ring_type == RX_RING) { dsaf_write_dev(q, RCB_RING_RX_RING_BASEADDR_L_REG, (u32)dma); dsaf_write_dev(q, RCB_RING_RX_RING_BASEADDR_H_REG, (u32)((dma >> 31) >> 1)); hns_rcb_set_rx_ring_bs(q, ring->buf_size); dsaf_write_dev(q, RCB_RING_RX_RING_BD_NUM_REG, ring_pair->port_id_in_comm); dsaf_write_dev(q, RCB_RING_RX_RING_PKTLINE_REG, ring_pair->port_id_in_comm); } else { dsaf_write_dev(q, RCB_RING_TX_RING_BASEADDR_L_REG, (u32)dma); dsaf_write_dev(q, RCB_RING_TX_RING_BASEADDR_H_REG, (u32)((dma >> 31) >> 1)); hns_rcb_set_tx_ring_bs(q, ring->buf_size); dsaf_write_dev(q, RCB_RING_TX_RING_BD_NUM_REG, ring_pair->port_id_in_comm); dsaf_write_dev(q, RCB_RING_TX_RING_PKTLINE_REG, ring_pair->port_id_in_comm + HNS_RCB_TX_PKTLINE_OFFSET); } } /** *hns_rcb_init_hw - init rcb hardware *@ring: rcb ring */ void hns_rcb_init_hw(struct ring_pair_cb *ring) { hns_rcb_ring_init(ring, RX_RING); hns_rcb_ring_init(ring, TX_RING); } /** *hns_rcb_set_port_desc_cnt - set rcb port description num *@rcb_common: rcb_common device *@port_idx:port index *@desc_cnt:BD num */ static void hns_rcb_set_port_desc_cnt(struct rcb_common_cb *rcb_common, u32 port_idx, u32 desc_cnt) { dsaf_write_dev(rcb_common, RCB_CFG_BD_NUM_REG + port_idx * 4, desc_cnt); } static void hns_rcb_set_port_timeout( struct rcb_common_cb *rcb_common, u32 port_idx, u32 timeout) { if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) { dsaf_write_dev(rcb_common, RCB_CFG_OVERTIME_REG, timeout * HNS_RCB_CLK_FREQ_MHZ); } else if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) { if (timeout > HNS_RCB_DEF_GAP_TIME_USECS) dsaf_write_dev(rcb_common, RCB_PORT_INT_GAPTIME_REG + port_idx * 4, HNS_RCB_DEF_GAP_TIME_USECS); else dsaf_write_dev(rcb_common, RCB_PORT_INT_GAPTIME_REG + port_idx * 4, timeout); dsaf_write_dev(rcb_common, RCB_PORT_CFG_OVERTIME_REG + port_idx * 4, timeout); } else { dsaf_write_dev(rcb_common, RCB_PORT_CFG_OVERTIME_REG + port_idx * 4, timeout); } } static int hns_rcb_common_get_port_num(struct rcb_common_cb *rcb_common) { if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) return HNS_RCB_SERVICE_NW_ENGINE_NUM; else return HNS_RCB_DEBUG_NW_ENGINE_NUM; } /*clr rcb comm exception irq**/ static void hns_rcb_comm_exc_irq_en( struct rcb_common_cb *rcb_common, int en) { u32 clr_vlue = 0xfffffffful; u32 msk_vlue = en ? 0 : 0xfffffffful; /* clr int*/ dsaf_write_dev(rcb_common, RCB_COM_INTSTS_ECC_ERR_REG, clr_vlue); dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_RING_STS, clr_vlue); dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_BD_RINT_STS, clr_vlue); dsaf_write_dev(rcb_common, RCB_COM_RINT_TX_PKT_REG, clr_vlue); dsaf_write_dev(rcb_common, RCB_COM_AXI_ERR_STS, clr_vlue); /*en msk*/ dsaf_write_dev(rcb_common, RCB_COM_INTMASK_ECC_ERR_REG, msk_vlue); dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_INTMASK_RING, msk_vlue); /*for tx bd neednot cacheline, so msk sf_txring_fbd_intmask (bit 1)**/ dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_INTMASK_BD, msk_vlue | 2); dsaf_write_dev(rcb_common, RCB_COM_INTMSK_TX_PKT_REG, msk_vlue); dsaf_write_dev(rcb_common, RCB_COM_AXI_WR_ERR_INTMASK, msk_vlue); } /** *hns_rcb_common_init_hw - init rcb common hardware *@rcb_common: rcb_common device *retuen 0 - success , negative --fail */ int hns_rcb_common_init_hw(struct rcb_common_cb *rcb_common) { u32 reg_val; int i; int port_num = hns_rcb_common_get_port_num(rcb_common); hns_rcb_comm_exc_irq_en(rcb_common, 0); reg_val = dsaf_read_dev(rcb_common, RCB_COM_CFG_INIT_FLAG_REG); if (0x1 != (reg_val & 0x1)) { dev_err(rcb_common->dsaf_dev->dev, "RCB_COM_CFG_INIT_FLAG_REG reg = 0x%x\n", reg_val); return -EBUSY; } for (i = 0; i < port_num; i++) { hns_rcb_set_port_desc_cnt(rcb_common, i, rcb_common->desc_num); hns_rcb_set_rx_coalesced_frames( rcb_common, i, HNS_RCB_DEF_RX_COALESCED_FRAMES); if (!AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver) && !HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) hns_rcb_set_tx_coalesced_frames( rcb_common, i, HNS_RCB_DEF_TX_COALESCED_FRAMES); hns_rcb_set_port_timeout( rcb_common, i, HNS_RCB_DEF_COALESCED_USECS); } dsaf_write_dev(rcb_common, RCB_COM_CFG_ENDIAN_REG, HNS_RCB_COMMON_ENDIAN); if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) { dsaf_write_dev(rcb_common, RCB_COM_CFG_FNA_REG, 0x0); dsaf_write_dev(rcb_common, RCB_COM_CFG_FA_REG, 0x1); } else { dsaf_set_dev_bit(rcb_common, RCBV2_COM_CFG_USER_REG, RCB_COM_CFG_FNA_B, false); dsaf_set_dev_bit(rcb_common, RCBV2_COM_CFG_USER_REG, RCB_COM_CFG_FA_B, true); dsaf_set_dev_bit(rcb_common, RCBV2_COM_CFG_TSO_MODE_REG, RCB_COM_TSO_MODE_B, HNS_TSO_MODE_8BD_32K); } return 0; } int hns_rcb_buf_size2type(u32 buf_size) { int bd_size_type; switch (buf_size) { case 512: bd_size_type = HNS_BD_SIZE_512_TYPE; break; case 1024: bd_size_type = HNS_BD_SIZE_1024_TYPE; break; case 2048: bd_size_type = HNS_BD_SIZE_2048_TYPE; break; case 4096: bd_size_type = HNS_BD_SIZE_4096_TYPE; break; default: bd_size_type = -EINVAL; } return bd_size_type; } static void hns_rcb_ring_get_cfg(struct hnae_queue *q, int ring_type) { struct hnae_ring *ring; struct rcb_common_cb *rcb_common; struct ring_pair_cb *ring_pair_cb; u16 desc_num, mdnum_ppkt; bool irq_idx, is_ver1; ring_pair_cb = container_of(q, struct ring_pair_cb, q); is_ver1 = AE_IS_VER1(ring_pair_cb->rcb_common->dsaf_dev->dsaf_ver); if (ring_type == RX_RING) { ring = &q->rx_ring; ring->io_base = ring_pair_cb->q.io_base; irq_idx = HNS_RCB_IRQ_IDX_RX; mdnum_ppkt = HNS_RCB_RING_MAX_BD_PER_PKT; } else { ring = &q->tx_ring; ring->io_base = (u8 __iomem *)ring_pair_cb->q.io_base + HNS_RCB_TX_REG_OFFSET; irq_idx = HNS_RCB_IRQ_IDX_TX; mdnum_ppkt = is_ver1 ? HNS_RCB_RING_MAX_TXBD_PER_PKT : HNS_RCBV2_RING_MAX_TXBD_PER_PKT; } rcb_common = ring_pair_cb->rcb_common; desc_num = rcb_common->dsaf_dev->desc_num; ring->desc = NULL; ring->desc_cb = NULL; ring->irq = ring_pair_cb->virq[irq_idx]; ring->desc_dma_addr = 0; ring->buf_size = RCB_DEFAULT_BUFFER_SIZE; ring->desc_num = desc_num; ring->max_desc_num_per_pkt = mdnum_ppkt; ring->max_raw_data_sz_per_desc = HNS_RCB_MAX_PKT_SIZE; ring->max_pkt_size = HNS_RCB_MAX_PKT_SIZE; ring->next_to_use = 0; ring->next_to_clean = 0; } static void hns_rcb_ring_pair_get_cfg(struct ring_pair_cb *ring_pair_cb) { ring_pair_cb->q.handle = NULL; hns_rcb_ring_get_cfg(&ring_pair_cb->q, RX_RING); hns_rcb_ring_get_cfg(&ring_pair_cb->q, TX_RING); } static int hns_rcb_get_port_in_comm( struct rcb_common_cb *rcb_common, int ring_idx) { return ring_idx / (rcb_common->max_q_per_vf * rcb_common->max_vfn); } #define SERVICE_RING_IRQ_IDX(v1) \ ((v1) ? HNS_SERVICE_RING_IRQ_IDX : HNSV2_SERVICE_RING_IRQ_IDX) static int hns_rcb_get_base_irq_idx(struct rcb_common_cb *rcb_common) { bool is_ver1 = AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver); if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) return SERVICE_RING_IRQ_IDX(is_ver1); else return HNS_DEBUG_RING_IRQ_IDX; } #define RCB_COMM_BASE_TO_RING_BASE(base, ringid)\ ((base) + 0x10000 + HNS_RCB_REG_OFFSET * (ringid)) /** *hns_rcb_get_cfg - get rcb config *@rcb_common: rcb common device */ int hns_rcb_get_cfg(struct rcb_common_cb *rcb_common) { struct ring_pair_cb *ring_pair_cb; u32 i; u32 ring_num = rcb_common->ring_num; int base_irq_idx = hns_rcb_get_base_irq_idx(rcb_common); struct platform_device *pdev = to_platform_device(rcb_common->dsaf_dev->dev); bool is_ver1 = AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver); for (i = 0; i < ring_num; i++) { ring_pair_cb = &rcb_common->ring_pair_cb[i]; ring_pair_cb->rcb_common = rcb_common; ring_pair_cb->dev = rcb_common->dsaf_dev->dev; ring_pair_cb->index = i; ring_pair_cb->q.io_base = RCB_COMM_BASE_TO_RING_BASE(rcb_common->io_base, i); ring_pair_cb->port_id_in_comm = hns_rcb_get_port_in_comm(rcb_common, i); ring_pair_cb->virq[HNS_RCB_IRQ_IDX_TX] = is_ver1 ? platform_get_irq(pdev, base_irq_idx + i * 2) : platform_get_irq(pdev, base_irq_idx + i * 3 + 1); ring_pair_cb->virq[HNS_RCB_IRQ_IDX_RX] = is_ver1 ? platform_get_irq(pdev, base_irq_idx + i * 2 + 1) : platform_get_irq(pdev, base_irq_idx + i * 3); if ((ring_pair_cb->virq[HNS_RCB_IRQ_IDX_TX] == -EPROBE_DEFER) || (ring_pair_cb->virq[HNS_RCB_IRQ_IDX_RX] == -EPROBE_DEFER)) return -EPROBE_DEFER; ring_pair_cb->q.phy_base = RCB_COMM_BASE_TO_RING_BASE(rcb_common->phy_base, i); hns_rcb_ring_pair_get_cfg(ring_pair_cb); } return 0; } /** *hns_rcb_get_rx_coalesced_frames - get rcb port rx coalesced frames *@rcb_common: rcb_common device *@port_idx:port id in comm * *Returns: coalesced_frames */ u32 hns_rcb_get_rx_coalesced_frames( struct rcb_common_cb *rcb_common, u32 port_idx) { return dsaf_read_dev(rcb_common, RCB_CFG_PKTLINE_REG + port_idx * 4); } /** *hns_rcb_get_tx_coalesced_frames - get rcb port tx coalesced frames *@rcb_common: rcb_common device *@port_idx:port id in comm * *Returns: coalesced_frames */ u32 hns_rcb_get_tx_coalesced_frames( struct rcb_common_cb *rcb_common, u32 port_idx) { u64 reg; reg = RCB_CFG_PKTLINE_REG + (port_idx + HNS_RCB_TX_PKTLINE_OFFSET) * 4; return dsaf_read_dev(rcb_common, reg); } /** *hns_rcb_get_coalesce_usecs - get rcb port coalesced time_out *@rcb_common: rcb_common device *@port_idx:port id in comm * *Returns: time_out */ u32 hns_rcb_get_coalesce_usecs( struct rcb_common_cb *rcb_common, u32 port_idx) { if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) return dsaf_read_dev(rcb_common, RCB_CFG_OVERTIME_REG) / HNS_RCB_CLK_FREQ_MHZ; else return dsaf_read_dev(rcb_common, RCB_PORT_CFG_OVERTIME_REG + port_idx * 4); } /** *hns_rcb_set_coalesce_usecs - set rcb port coalesced time_out *@rcb_common: rcb_common device *@port_idx:port id in comm *@timeout:tx/rx time for coalesced time_out * * Returns: * Zero for success, or an error code in case of failure */ int hns_rcb_set_coalesce_usecs( struct rcb_common_cb *rcb_common, u32 port_idx, u32 timeout) { u32 old_timeout = hns_rcb_get_coalesce_usecs(rcb_common, port_idx); if (timeout == old_timeout) return 0; if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) { if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) { dev_err(rcb_common->dsaf_dev->dev, "error: not support coalesce_usecs setting!\n"); return -EINVAL; } } if (timeout > HNS_RCB_MAX_COALESCED_USECS || timeout == 0) { dev_err(rcb_common->dsaf_dev->dev, "error: coalesce_usecs setting supports 1~1023us\n"); return -EINVAL; } hns_rcb_set_port_timeout(rcb_common, port_idx, timeout); return 0; } /** *hns_rcb_set_tx_coalesced_frames - set rcb coalesced frames *@rcb_common: rcb_common device *@port_idx:port id in comm *@coalesced_frames:tx/rx BD num for coalesced frames * * Returns: * Zero for success, or an error code in case of failure */ int hns_rcb_set_tx_coalesced_frames( struct rcb_common_cb *rcb_common, u32 port_idx, u32 coalesced_frames) { u32 old_waterline = hns_rcb_get_tx_coalesced_frames(rcb_common, port_idx); u64 reg; if (coalesced_frames == old_waterline) return 0; if (coalesced_frames != 1) { dev_err(rcb_common->dsaf_dev->dev, "error: not support tx coalesce_frames setting!\n"); return -EINVAL; } reg = RCB_CFG_PKTLINE_REG + (port_idx + HNS_RCB_TX_PKTLINE_OFFSET) * 4; dsaf_write_dev(rcb_common, reg, coalesced_frames); return 0; } /** *hns_rcb_set_rx_coalesced_frames - set rcb rx coalesced frames *@rcb_common: rcb_common device *@port_idx:port id in comm *@coalesced_frames:tx/rx BD num for coalesced frames * * Returns: * Zero for success, or an error code in case of failure */ int hns_rcb_set_rx_coalesced_frames( struct rcb_common_cb *rcb_common, u32 port_idx, u32 coalesced_frames) { u32 old_waterline = hns_rcb_get_rx_coalesced_frames(rcb_common, port_idx); if (coalesced_frames == old_waterline) return 0; if (coalesced_frames >= rcb_common->desc_num || coalesced_frames > HNS_RCB_MAX_COALESCED_FRAMES || coalesced_frames < HNS_RCB_MIN_COALESCED_FRAMES) { dev_err(rcb_common->dsaf_dev->dev, "error: not support coalesce_frames setting!\n"); return -EINVAL; } dsaf_write_dev(rcb_common, RCB_CFG_PKTLINE_REG + port_idx * 4, coalesced_frames); return 0; } /** *hns_rcb_get_queue_mode - get max VM number and max ring number per VM * accordding to dsaf mode *@dsaf_mode: dsaf mode *@max_vfn : max vfn number *@max_q_per_vf:max ring number per vm */ void hns_rcb_get_queue_mode(enum dsaf_mode dsaf_mode, u16 *max_vfn, u16 *max_q_per_vf) { switch (dsaf_mode) { case DSAF_MODE_DISABLE_6PORT_0VM: *max_vfn = 1; *max_q_per_vf = 16; break; case DSAF_MODE_DISABLE_FIX: case DSAF_MODE_DISABLE_SP: *max_vfn = 1; *max_q_per_vf = 1; break; case DSAF_MODE_DISABLE_2PORT_64VM: *max_vfn = 64; *max_q_per_vf = 1; break; case DSAF_MODE_DISABLE_6PORT_16VM: *max_vfn = 16; *max_q_per_vf = 1; break; default: *max_vfn = 1; *max_q_per_vf = 16; break; } } int hns_rcb_get_ring_num(struct dsaf_device *dsaf_dev) { switch (dsaf_dev->dsaf_mode) { case DSAF_MODE_ENABLE_FIX: case DSAF_MODE_DISABLE_SP: return 1; case DSAF_MODE_DISABLE_FIX: return 6; case DSAF_MODE_ENABLE_0VM: return 32; case DSAF_MODE_DISABLE_6PORT_0VM: case DSAF_MODE_ENABLE_16VM: case DSAF_MODE_DISABLE_6PORT_2VM: case DSAF_MODE_DISABLE_6PORT_16VM: case DSAF_MODE_DISABLE_6PORT_4VM: case DSAF_MODE_ENABLE_8VM: return 96; case DSAF_MODE_DISABLE_2PORT_16VM: case DSAF_MODE_DISABLE_2PORT_8VM: case DSAF_MODE_ENABLE_32VM: case DSAF_MODE_DISABLE_2PORT_64VM: case DSAF_MODE_ENABLE_128VM: return 128; default: dev_warn(dsaf_dev->dev, "get ring num fail,use default!dsaf_mode=%d\n", dsaf_dev->dsaf_mode); return 128; } } void __iomem *hns_rcb_common_get_vaddr(struct rcb_common_cb *rcb_common) { struct dsaf_device *dsaf_dev = rcb_common->dsaf_dev; return dsaf_dev->ppe_base + RCB_COMMON_REG_OFFSET; } static phys_addr_t hns_rcb_common_get_paddr(struct rcb_common_cb *rcb_common) { struct dsaf_device *dsaf_dev = rcb_common->dsaf_dev; return dsaf_dev->ppe_paddr + RCB_COMMON_REG_OFFSET; } int hns_rcb_common_get_cfg(struct dsaf_device *dsaf_dev, int comm_index) { struct rcb_common_cb *rcb_common; enum dsaf_mode dsaf_mode = dsaf_dev->dsaf_mode; u16 max_vfn; u16 max_q_per_vf; int ring_num = hns_rcb_get_ring_num(dsaf_dev); rcb_common = devm_kzalloc(dsaf_dev->dev, sizeof(*rcb_common) + ring_num * sizeof(struct ring_pair_cb), GFP_KERNEL); if (!rcb_common) { dev_err(dsaf_dev->dev, "rcb common devm_kzalloc fail!\n"); return -ENOMEM; } rcb_common->comm_index = comm_index; rcb_common->ring_num = ring_num; rcb_common->dsaf_dev = dsaf_dev; rcb_common->desc_num = dsaf_dev->desc_num; hns_rcb_get_queue_mode(dsaf_mode, &max_vfn, &max_q_per_vf); rcb_common->max_vfn = max_vfn; rcb_common->max_q_per_vf = max_q_per_vf; rcb_common->io_base = hns_rcb_common_get_vaddr(rcb_common); rcb_common->phy_base = hns_rcb_common_get_paddr(rcb_common); dsaf_dev->rcb_common[comm_index] = rcb_common; return 0; } void hns_rcb_common_free_cfg(struct dsaf_device *dsaf_dev, u32 comm_index) { dsaf_dev->rcb_common[comm_index] = NULL; } void hns_rcb_update_stats(struct hnae_queue *queue) { struct ring_pair_cb *ring = container_of(queue, struct ring_pair_cb, q); struct dsaf_device *dsaf_dev = ring->rcb_common->dsaf_dev; struct ppe_common_cb *ppe_common = dsaf_dev->ppe_common[ring->rcb_common->comm_index]; struct hns_ring_hw_stats *hw_stats = &ring->hw_stats; hw_stats->rx_pkts += dsaf_read_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG); dsaf_write_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG, 0x1); hw_stats->ppe_rx_ok_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_RX_PKT_QID_OK_CNT_REG + 4 * ring->index); hw_stats->ppe_rx_drop_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_RX_PKT_QID_DROP_CNT_REG + 4 * ring->index); hw_stats->tx_pkts += dsaf_read_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG); dsaf_write_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG, 0x1); hw_stats->ppe_tx_ok_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_TX_PKT_QID_OK_CNT_REG + 4 * ring->index); hw_stats->ppe_tx_drop_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_TX_PKT_QID_ERR_CNT_REG + 4 * ring->index); } /** *hns_rcb_get_stats - get rcb statistic *@ring: rcb ring *@data:statistic value */ void hns_rcb_get_stats(struct hnae_queue *queue, u64 *data) { u64 *regs_buff = data; struct ring_pair_cb *ring = container_of(queue, struct ring_pair_cb, q); struct hns_ring_hw_stats *hw_stats = &ring->hw_stats; regs_buff[0] = hw_stats->tx_pkts; regs_buff[1] = hw_stats->ppe_tx_ok_pkts; regs_buff[2] = hw_stats->ppe_tx_drop_pkts; regs_buff[3] = dsaf_read_dev(queue, RCB_RING_TX_RING_FBDNUM_REG); regs_buff[4] = queue->tx_ring.stats.tx_pkts; regs_buff[5] = queue->tx_ring.stats.tx_bytes; regs_buff[6] = queue->tx_ring.stats.tx_err_cnt; regs_buff[7] = queue->tx_ring.stats.io_err_cnt; regs_buff[8] = queue->tx_ring.stats.sw_err_cnt; regs_buff[9] = queue->tx_ring.stats.seg_pkt_cnt; regs_buff[10] = queue->tx_ring.stats.restart_queue; regs_buff[11] = queue->tx_ring.stats.tx_busy; regs_buff[12] = hw_stats->rx_pkts; regs_buff[13] = hw_stats->ppe_rx_ok_pkts; regs_buff[14] = hw_stats->ppe_rx_drop_pkts; regs_buff[15] = dsaf_read_dev(queue, RCB_RING_RX_RING_FBDNUM_REG); regs_buff[16] = queue->rx_ring.stats.rx_pkts; regs_buff[17] = queue->rx_ring.stats.rx_bytes; regs_buff[18] = queue->rx_ring.stats.rx_err_cnt; regs_buff[19] = queue->rx_ring.stats.io_err_cnt; regs_buff[20] = queue->rx_ring.stats.sw_err_cnt; regs_buff[21] = queue->rx_ring.stats.seg_pkt_cnt; regs_buff[22] = queue->rx_ring.stats.reuse_pg_cnt; regs_buff[23] = queue->rx_ring.stats.err_pkt_len; regs_buff[24] = queue->rx_ring.stats.non_vld_descs; regs_buff[25] = queue->rx_ring.stats.err_bd_num; regs_buff[26] = queue->rx_ring.stats.l2_err; regs_buff[27] = queue->rx_ring.stats.l3l4_csum_err; } /** *hns_rcb_get_ring_sset_count - rcb string set count *@stringset:ethtool cmd *return rcb ring string set count */ int hns_rcb_get_ring_sset_count(int stringset) { if (stringset == ETH_SS_STATS) return HNS_RING_STATIC_REG_NUM; return 0; } /** *hns_rcb_get_common_regs_count - rcb common regs count *return regs count */ int hns_rcb_get_common_regs_count(void) { return HNS_RCB_COMMON_DUMP_REG_NUM; } /** *rcb_get_sset_count - rcb ring regs count *return regs count */ int hns_rcb_get_ring_regs_count(void) { return HNS_RCB_RING_DUMP_REG_NUM; } /** *hns_rcb_get_strings - get rcb string set *@stringset:string set index *@data:strings name value *@index:queue index */ void hns_rcb_get_strings(int stringset, u8 *data, int index) { char *buff = (char *)data; if (stringset != ETH_SS_STATS) return; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_rcb_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_ppe_tx_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_ppe_drop_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_fbd_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_bytes", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_err_cnt", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_io_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_sw_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_seg_pkt", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_restart_queue", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_tx_busy", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_rcb_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_ppe_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_ppe_drop_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_fbd_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_pkt_num", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_bytes", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_err_cnt", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_io_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_sw_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_seg_pkt", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_reuse_pg", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_len_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_non_vld_desc_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_bd_num_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_l2_err", index); buff = buff + ETH_GSTRING_LEN; snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_l3l4csum_err", index); } void hns_rcb_get_common_regs(struct rcb_common_cb *rcb_com, void *data) { u32 *regs = data; bool is_ver1 = AE_IS_VER1(rcb_com->dsaf_dev->dsaf_ver); bool is_dbg = HNS_DSAF_IS_DEBUG(rcb_com->dsaf_dev); u32 reg_tmp; u32 reg_num_tmp; u32 i = 0; /*rcb common registers */ regs[0] = dsaf_read_dev(rcb_com, RCB_COM_CFG_ENDIAN_REG); regs[1] = dsaf_read_dev(rcb_com, RCB_COM_CFG_SYS_FSH_REG); regs[2] = dsaf_read_dev(rcb_com, RCB_COM_CFG_INIT_FLAG_REG); regs[3] = dsaf_read_dev(rcb_com, RCB_COM_CFG_PKT_REG); regs[4] = dsaf_read_dev(rcb_com, RCB_COM_CFG_RINVLD_REG); regs[5] = dsaf_read_dev(rcb_com, RCB_COM_CFG_FNA_REG); regs[6] = dsaf_read_dev(rcb_com, RCB_COM_CFG_FA_REG); regs[7] = dsaf_read_dev(rcb_com, RCB_COM_CFG_PKT_TC_BP_REG); regs[8] = dsaf_read_dev(rcb_com, RCB_COM_CFG_PPE_TNL_CLKEN_REG); regs[9] = dsaf_read_dev(rcb_com, RCB_COM_INTMSK_TX_PKT_REG); regs[10] = dsaf_read_dev(rcb_com, RCB_COM_RINT_TX_PKT_REG); regs[11] = dsaf_read_dev(rcb_com, RCB_COM_INTMASK_ECC_ERR_REG); regs[12] = dsaf_read_dev(rcb_com, RCB_COM_INTSTS_ECC_ERR_REG); regs[13] = dsaf_read_dev(rcb_com, RCB_COM_EBD_SRAM_ERR_REG); regs[14] = dsaf_read_dev(rcb_com, RCB_COM_RXRING_ERR_REG); regs[15] = dsaf_read_dev(rcb_com, RCB_COM_TXRING_ERR_REG); regs[16] = dsaf_read_dev(rcb_com, RCB_COM_TX_FBD_ERR_REG); regs[17] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK_EN_REG); regs[18] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK0_REG); regs[19] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK1_REG); regs[20] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK2_REG); regs[21] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK3_REG); regs[22] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK4_REG); regs[23] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK5_REG); regs[24] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR0_REG); regs[25] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR3_REG); regs[26] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR4_REG); regs[27] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR5_REG); regs[28] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_INTMASK_RING); regs[29] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_RING_STS); regs[30] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_RING); regs[31] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_INTMASK_BD); regs[32] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_BD_RINT_STS); regs[33] = dsaf_read_dev(rcb_com, RCB_COM_RCB_RD_BD_BUSY); regs[34] = dsaf_read_dev(rcb_com, RCB_COM_RCB_FBD_CRT_EN); regs[35] = dsaf_read_dev(rcb_com, RCB_COM_AXI_WR_ERR_INTMASK); regs[36] = dsaf_read_dev(rcb_com, RCB_COM_AXI_ERR_STS); regs[37] = dsaf_read_dev(rcb_com, RCB_COM_CHK_TX_FBD_NUM_REG); /* rcb common entry registers */ for (i = 0; i < 16; i++) { /* total 16 model registers */ regs[38 + i] = dsaf_read_dev(rcb_com, RCB_CFG_BD_NUM_REG + 4 * i); regs[54 + i] = dsaf_read_dev(rcb_com, RCB_CFG_PKTLINE_REG + 4 * i); } reg_tmp = is_ver1 ? RCB_CFG_OVERTIME_REG : RCB_PORT_CFG_OVERTIME_REG; reg_num_tmp = (is_ver1 || is_dbg) ? 1 : 6; for (i = 0; i < reg_num_tmp; i++) regs[70 + i] = dsaf_read_dev(rcb_com, reg_tmp); regs[76] = dsaf_read_dev(rcb_com, RCB_CFG_PKTLINE_INT_NUM_REG); regs[77] = dsaf_read_dev(rcb_com, RCB_CFG_OVERTIME_INT_NUM_REG); /* mark end of rcb common regs */ for (i = 78; i < 80; i++) regs[i] = 0xcccccccc; } void hns_rcb_get_ring_regs(struct hnae_queue *queue, void *data) { u32 *regs = data; struct ring_pair_cb *ring_pair = container_of(queue, struct ring_pair_cb, q); u32 i = 0; /*rcb ring registers */ regs[0] = dsaf_read_dev(queue, RCB_RING_RX_RING_BASEADDR_L_REG); regs[1] = dsaf_read_dev(queue, RCB_RING_RX_RING_BASEADDR_H_REG); regs[2] = dsaf_read_dev(queue, RCB_RING_RX_RING_BD_NUM_REG); regs[3] = dsaf_read_dev(queue, RCB_RING_RX_RING_BD_LEN_REG); regs[4] = dsaf_read_dev(queue, RCB_RING_RX_RING_PKTLINE_REG); regs[5] = dsaf_read_dev(queue, RCB_RING_RX_RING_TAIL_REG); regs[6] = dsaf_read_dev(queue, RCB_RING_RX_RING_HEAD_REG); regs[7] = dsaf_read_dev(queue, RCB_RING_RX_RING_FBDNUM_REG); regs[8] = dsaf_read_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG); regs[9] = dsaf_read_dev(queue, RCB_RING_TX_RING_BASEADDR_L_REG); regs[10] = dsaf_read_dev(queue, RCB_RING_TX_RING_BASEADDR_H_REG); regs[11] = dsaf_read_dev(queue, RCB_RING_TX_RING_BD_NUM_REG); regs[12] = dsaf_read_dev(queue, RCB_RING_TX_RING_BD_LEN_REG); regs[13] = dsaf_read_dev(queue, RCB_RING_TX_RING_PKTLINE_REG); regs[15] = dsaf_read_dev(queue, RCB_RING_TX_RING_TAIL_REG); regs[16] = dsaf_read_dev(queue, RCB_RING_TX_RING_HEAD_REG); regs[17] = dsaf_read_dev(queue, RCB_RING_TX_RING_FBDNUM_REG); regs[18] = dsaf_read_dev(queue, RCB_RING_TX_RING_OFFSET_REG); regs[19] = dsaf_read_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG); regs[20] = dsaf_read_dev(queue, RCB_RING_PREFETCH_EN_REG); regs[21] = dsaf_read_dev(queue, RCB_RING_CFG_VF_NUM_REG); regs[22] = dsaf_read_dev(queue, RCB_RING_ASID_REG); regs[23] = dsaf_read_dev(queue, RCB_RING_RX_VM_REG); regs[24] = dsaf_read_dev(queue, RCB_RING_T0_BE_RST); regs[25] = dsaf_read_dev(queue, RCB_RING_COULD_BE_RST); regs[26] = dsaf_read_dev(queue, RCB_RING_WRR_WEIGHT_REG); regs[27] = dsaf_read_dev(queue, RCB_RING_INTMSK_RXWL_REG); regs[28] = dsaf_read_dev(queue, RCB_RING_INTSTS_RX_RING_REG); regs[29] = dsaf_read_dev(queue, RCB_RING_INTMSK_TXWL_REG); regs[30] = dsaf_read_dev(queue, RCB_RING_INTSTS_TX_RING_REG); regs[31] = dsaf_read_dev(queue, RCB_RING_INTMSK_RX_OVERTIME_REG); regs[32] = dsaf_read_dev(queue, RCB_RING_INTSTS_RX_OVERTIME_REG); regs[33] = dsaf_read_dev(queue, RCB_RING_INTMSK_TX_OVERTIME_REG); regs[34] = dsaf_read_dev(queue, RCB_RING_INTSTS_TX_OVERTIME_REG); /* mark end of ring regs */ for (i = 35; i < 40; i++) regs[i] = 0xcccccc00 + ring_pair->index; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3020_2
crossvul-cpp_data_bad_1615_0
/* ----------------------------------------------------------------------------- * Copyright (c) 2011 Ozmo Inc * Released under the GNU General Public License Version 2 (GPLv2). * * This file implements the protocol specific parts of the USB service for a PD. * ----------------------------------------------------------------------------- */ #include <linux/module.h> #include <linux/timer.h> #include <linux/sched.h> #include <linux/netdevice.h> #include <linux/errno.h> #include <linux/input.h> #include <asm/unaligned.h> #include "ozdbg.h" #include "ozprotocol.h" #include "ozeltbuf.h" #include "ozpd.h" #include "ozproto.h" #include "ozusbif.h" #include "ozhcd.h" #include "ozusbsvc.h" #define MAX_ISOC_FIXED_DATA (253-sizeof(struct oz_isoc_fixed)) /* * Context: softirq */ static int oz_usb_submit_elt(struct oz_elt_buf *eb, struct oz_elt_info *ei, struct oz_usb_ctx *usb_ctx, u8 strid, u8 isoc) { int ret; struct oz_elt *elt = (struct oz_elt *)ei->data; struct oz_app_hdr *app_hdr = (struct oz_app_hdr *)(elt+1); elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_USB; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_USB; spin_lock_bh(&eb->lock); if (isoc == 0) { app_hdr->elt_seq_num = usb_ctx->tx_seq_num++; if (usb_ctx->tx_seq_num == 0) usb_ctx->tx_seq_num = 1; } ret = oz_queue_elt_info(eb, isoc, strid, ei); if (ret) oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); return ret; } /* * Context: softirq */ int oz_usb_get_desc_req(void *hpd, u8 req_id, u8 req_type, u8 desc_type, u8 index, __le16 windex, int offset, int len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_get_desc_req *body; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); oz_dbg(ON, " req_type = 0x%x\n", req_type); oz_dbg(ON, " desc_type = 0x%x\n", desc_type); oz_dbg(ON, " index = 0x%x\n", index); oz_dbg(ON, " windex = 0x%x\n", windex); oz_dbg(ON, " offset = 0x%x\n", offset); oz_dbg(ON, " len = 0x%x\n", len); if (len > 200) len = 200; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_get_desc_req); body = (struct oz_get_desc_req *)(elt+1); body->type = OZ_GET_DESC_REQ; body->req_id = req_id; put_unaligned(cpu_to_le16(offset), &body->offset); put_unaligned(cpu_to_le16(len), &body->size); body->req_type = req_type; body->desc_type = desc_type; body->w_index = windex; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_config_req(void *hpd, u8 req_id, u8 index) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_config_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_config_req); body = (struct oz_set_config_req *)(elt+1); body->type = OZ_SET_CONFIG_REQ; body->req_id = req_id; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_interface_req(void *hpd, u8 req_id, u8 index, u8 alt) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_interface_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_interface_req); body = (struct oz_set_interface_req *)(elt+1); body->type = OZ_SET_INTERFACE_REQ; body->req_id = req_id; body->index = index; body->alternative = alt; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_clear_feature_req(void *hpd, u8 req_id, u8 type, u8 recipient, u8 index, __le16 feature) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_feature_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_feature_req); body = (struct oz_feature_req *)(elt+1); body->type = type; body->req_id = req_id; body->recipient = recipient; body->index = index; put_unaligned(feature, &body->feature); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_vendor_class_req(void *hpd, u8 req_id, u8 req_type, u8 request, __le16 value, __le16 index, const u8 *data, int data_len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_vendor_class_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_vendor_class_req) - 1 + data_len; body = (struct oz_vendor_class_req *)(elt+1); body->type = OZ_VENDOR_CLASS_REQ; body->req_id = req_id; body->req_type = req_type; body->request = request; put_unaligned(value, &body->value); put_unaligned(index, &body->index); if (data_len) memcpy(body->data, data, data_len); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ int oz_usb_control_req(void *hpd, u8 req_id, struct usb_ctrlrequest *setup, const u8 *data, int data_len) { unsigned wvalue = le16_to_cpu(setup->wValue); unsigned windex = le16_to_cpu(setup->wIndex); unsigned wlength = le16_to_cpu(setup->wLength); int rc = 0; if ((setup->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) { switch (setup->bRequest) { case USB_REQ_GET_DESCRIPTOR: rc = oz_usb_get_desc_req(hpd, req_id, setup->bRequestType, (u8)(wvalue>>8), (u8)wvalue, setup->wIndex, 0, wlength); break; case USB_REQ_SET_CONFIGURATION: rc = oz_usb_set_config_req(hpd, req_id, (u8)wvalue); break; case USB_REQ_SET_INTERFACE: { u8 if_num = (u8)windex; u8 alt = (u8)wvalue; rc = oz_usb_set_interface_req(hpd, req_id, if_num, alt); } break; case USB_REQ_SET_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_SET_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; case USB_REQ_CLEAR_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_CLEAR_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; } } else { rc = oz_usb_vendor_class_req(hpd, req_id, setup->bRequestType, setup->bRequest, setup->wValue, setup->wIndex, data, data_len); } return rc; } /* * Context: softirq */ int oz_usb_send_isoc(void *hpd, u8 ep_num, struct urb *urb) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt_buf *eb; int i; int hdr_size; u8 *data; struct usb_iso_packet_descriptor *desc; if (pd->mode & OZ_F_ISOC_NO_ELTS) { for (i = 0; i < urb->number_of_packets; i++) { u8 *data; desc = &urb->iso_frame_desc[i]; data = ((u8 *)urb->transfer_buffer)+desc->offset; oz_send_isoc_unit(pd, ep_num, data, desc->length); } return 0; } hdr_size = sizeof(struct oz_isoc_fixed) - 1; eb = &pd->elt_buff; i = 0; while (i < urb->number_of_packets) { struct oz_elt_info *ei = oz_elt_info_alloc(eb); struct oz_elt *elt; struct oz_isoc_fixed *body; int unit_count; int unit_size; int rem; if (ei == NULL) return -1; rem = MAX_ISOC_FIXED_DATA; elt = (struct oz_elt *)ei->data; body = (struct oz_isoc_fixed *)(elt + 1); body->type = OZ_USB_ENDPOINT_DATA; body->endpoint = ep_num; body->format = OZ_DATA_F_ISOC_FIXED; unit_size = urb->iso_frame_desc[i].length; body->unit_size = (u8)unit_size; data = ((u8 *)(elt+1)) + hdr_size; unit_count = 0; while (i < urb->number_of_packets) { desc = &urb->iso_frame_desc[i]; if ((unit_size == desc->length) && (desc->length <= rem)) { memcpy(data, ((u8 *)urb->transfer_buffer) + desc->offset, unit_size); data += unit_size; rem -= unit_size; unit_count++; desc->status = 0; desc->actual_length = desc->length; i++; } else { break; } } elt->length = hdr_size + MAX_ISOC_FIXED_DATA - rem; /* Store the number of units in body->frame_number for the * moment. This field will be correctly determined before * the element is sent. */ body->frame_number = (u8)unit_count; oz_usb_submit_elt(eb, ei, usb_ctx, ep_num, pd->mode & OZ_F_ISOC_ANYTIME); } return 0; } /* * Context: softirq-serialized */ static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; int n = (len - sizeof(struct oz_multiple_fixed)+1) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } } /* * This is called when the PD has received a USB element. The type of element * is determined and is then passed to an appropriate handler function. * Context: softirq-serialized */ void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; int data_len = elt->length - sizeof(struct oz_get_desc_rsp) + 1; u16 offs = le16_to_cpu(get_unaligned(&body->offset)); u16 total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } /* * Context: softirq, process */ void oz_usb_farewell(struct oz_pd *pd, u8 ep_num, u8 *data, u8 len) { struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (!usb_ctx->stopped) { oz_dbg(ON, "Farewell indicated ep = 0x%x\n", ep_num); oz_hcd_data_ind(usb_ctx->hport, ep_num, data, len); } oz_usb_put(usb_ctx); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1615_0
crossvul-cpp_data_good_4787_17
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE X X RRRR % % E X X R R % % EEE X RRRR % % E X X R R % % EEEEE X X R R % % % % % % Read/Write High Dynamic-Range (HDR) Image File Format % % % % Software Design % % Cristy % % April 2007 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/resource_.h" #include "magick/utility.h" #if defined(MAGICKCORE_OPENEXR_DELEGATE) #include <ImfCRgbaFile.h> /* Forward declarations. */ static MagickBooleanType WriteEXRImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s E X R % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsEXR() returns MagickTrue if the image format type, identified by the % magick string, is EXR. % % The format of the IsEXR method is: % % MagickBooleanType IsEXR(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsEXR(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\166\057\061\001",4) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_OPENEXR_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d E X R I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadEXRImage reads an image in the high dynamic-range (HDR) file format % developed by Industrial Light & Magic. It allocates the memory necessary % for the new Image structure and returns a pointer to the new image. % % The format of the ReadEXRImage method is: % % Image *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception) { const ImfHeader *hdr_info; Image *image; ImageInfo *read_info; ImfInputFile *file; ImfRgba *scanline; int max_x, max_y, min_x, min_y; MagickBooleanType status; register ssize_t x; register PixelPacket *q; ssize_t y; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } read_info=CloneImageInfo(image_info); if (IsPathAccessible(read_info->filename) == MagickFalse) { (void) AcquireUniqueFilename(read_info->filename); (void) ImageToFile(image,read_info->filename,exception); } file=ImfOpenInputFile(read_info->filename); if (file == (ImfInputFile *) NULL) { ThrowFileException(exception,BlobError,"UnableToOpenBlob", ImfErrorMessage()); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } hdr_info=ImfInputHeader(file); ImfHeaderDisplayWindow(hdr_info,&min_x,&min_y,&max_x,&max_y); image->columns=max_x-min_x+1UL; image->rows=max_y-min_y+1UL; image->matte=MagickTrue; SetImageColorspace(image,RGBColorspace); if (image_info->ping != MagickFalse) { (void) ImfCloseInputFile(file); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline)); if (scanline == (ImfRgba *) NULL) { (void) ImfCloseInputFile(file); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline)); ImfInputSetFrameBuffer(file,scanline-min_x-image->columns*(min_y+y),1, image->columns); ImfInputReadPixels(file,min_y+y,min_y+y); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].r))); SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].g))); SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].b))); SetPixelAlpha(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].a))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } scanline=(ImfRgba *) RelinquishMagickMemory(scanline); (void) ImfCloseInputFile(file); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r E X R I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterEXRImage() adds properties for the EXR image format % to the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterEXRImage method is: % % size_t RegisterEXRImage(void) % */ ModuleExport size_t RegisterEXRImage(void) { MagickInfo *entry; entry=SetMagickInfo("EXR"); #if defined(MAGICKCORE_OPENEXR_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadEXRImage; entry->encoder=(EncodeImageHandler *) WriteEXRImage; #endif entry->magick=(IsImageFormatHandler *) IsEXR; entry->adjoin=MagickFalse; entry->description=ConstantString("High Dynamic-range (HDR)"); entry->blob_support=MagickFalse; entry->module=ConstantString("EXR"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r E X R I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterEXRImage() removes format registrations made by the % EXR module from the list of supported formats. % % The format of the UnregisterEXRImage method is: % % UnregisterEXRImage(void) % */ ModuleExport void UnregisterEXRImage(void) { (void) UnregisterMagickInfo("EXR"); } #if defined(MAGICKCORE_OPENEXR_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e E X R I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteEXRImage() writes an image to a file the in the high dynamic-range % (HDR) file format developed by Industrial Light & Magic. % % The format of the WriteEXRImage method is: % % MagickBooleanType WriteEXRImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteEXRImage(const ImageInfo *image_info,Image *image) { ImageInfo *write_info; ImfHalf half_quantum; ImfHeader *hdr_info; ImfOutputFile *file; ImfRgba *scanline; int compression; MagickBooleanType status; register const PixelPacket *p; register ssize_t x; ssize_t y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) SetImageColorspace(image,RGBColorspace); write_info=CloneImageInfo(image_info); (void) AcquireUniqueFilename(write_info->filename); hdr_info=ImfNewHeader(); ImfHeaderSetDataWindow(hdr_info,0,0,(int) image->columns-1,(int) image->rows-1); ImfHeaderSetDisplayWindow(hdr_info,0,0,(int) image->columns-1,(int) image->rows-1); compression=IMF_NO_COMPRESSION; if (write_info->compression == ZipSCompression) compression=IMF_ZIPS_COMPRESSION; if (write_info->compression == ZipCompression) compression=IMF_ZIP_COMPRESSION; if (write_info->compression == PizCompression) compression=IMF_PIZ_COMPRESSION; if (write_info->compression == Pxr24Compression) compression=IMF_PXR24_COMPRESSION; #if defined(B44Compression) if (write_info->compression == B44Compression) compression=IMF_B44_COMPRESSION; #endif #if defined(B44ACompression) if (write_info->compression == B44ACompression) compression=IMF_B44A_COMPRESSION; #endif ImfHeaderSetCompression(hdr_info,compression); ImfHeaderSetLineOrder(hdr_info,IMF_INCREASING_Y); file=ImfOpenOutputFile(write_info->filename,hdr_info,IMF_WRITE_RGBA); ImfDeleteHeader(hdr_info); if (file == (ImfOutputFile *) NULL) { (void) RelinquishUniqueFileResource(write_info->filename); write_info=DestroyImageInfo(write_info); ThrowFileException(&image->exception,BlobError,"UnableToOpenBlob", ImfErrorMessage()); return(MagickFalse); } scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline)); if (scanline == (ImfRgba *) NULL) { (void) ImfCloseOutputFile(file); (void) RelinquishUniqueFileResource(write_info->filename); write_info=DestroyImageInfo(write_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline)); for (y=0; y < (ssize_t) image->rows; y++) { 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++) { ImfFloatToHalf(QuantumScale*GetPixelRed(p),&half_quantum); scanline[x].r=half_quantum; ImfFloatToHalf(QuantumScale*GetPixelGreen(p),&half_quantum); scanline[x].g=half_quantum; ImfFloatToHalf(QuantumScale*GetPixelBlue(p),&half_quantum); scanline[x].b=half_quantum; if (image->matte == MagickFalse) ImfFloatToHalf(1.0,&half_quantum); else ImfFloatToHalf(1.0-QuantumScale*GetPixelOpacity(p), &half_quantum); scanline[x].a=half_quantum; p++; } ImfOutputSetFrameBuffer(file,scanline-(y*image->columns),1,image->columns); ImfOutputWritePixels(file,1); } (void) ImfCloseOutputFile(file); scanline=(ImfRgba *) RelinquishMagickMemory(scanline); (void) FileToImage(image,write_info->filename); (void) RelinquishUniqueFileResource(write_info->filename); write_info=DestroyImageInfo(write_info); (void) CloseBlob(image); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_17
crossvul-cpp_data_bad_3420_0
/* * ScreenPressor decoder * * Copyright (c) 2017 Paul B Mahol * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "avcodec.h" #include "bytestream.h" #include "internal.h" #define TOP 0x01000000 #define BOT 0x010000 typedef struct RangeCoder { unsigned code; unsigned range; unsigned code1; } RangeCoder; typedef struct PixelModel { unsigned freq[256]; unsigned lookup[16]; unsigned total_freq; } PixelModel; typedef struct SCPRContext { AVFrame *last_frame; AVFrame *current_frame; GetByteContext gb; RangeCoder rc; PixelModel pixel_model[3][4096]; unsigned op_model[6][7]; unsigned run_model[6][257]; unsigned range_model[257]; unsigned count_model[257]; unsigned fill_model[6]; unsigned sxy_model[4][17]; unsigned mv_model[2][513]; unsigned nbx, nby; unsigned nbcount; unsigned *blocks; unsigned cbits; int cxshift; int (*get_freq)(RangeCoder *rc, unsigned total_freq, unsigned *freq); int (*decode)(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq); } SCPRContext; static void init_rangecoder(RangeCoder *rc, GetByteContext *gb) { rc->code1 = 0; rc->range = 0xFFFFFFFFU; rc->code = bytestream2_get_be32(gb); } static void reinit_tables(SCPRContext *s) { int comp, i, j; for (comp = 0; comp < 3; comp++) { for (j = 0; j < 4096; j++) { if (s->pixel_model[comp][j].total_freq != 256) { for (i = 0; i < 256; i++) s->pixel_model[comp][j].freq[i] = 1; for (i = 0; i < 16; i++) s->pixel_model[comp][j].lookup[i] = 16; s->pixel_model[comp][j].total_freq = 256; } } } for (j = 0; j < 6; j++) { unsigned *p = s->run_model[j]; for (i = 0; i < 256; i++) p[i] = 1; p[256] = 256; } for (j = 0; j < 6; j++) { unsigned *op = s->op_model[j]; for (i = 0; i < 6; i++) op[i] = 1; op[6] = 6; } for (i = 0; i < 256; i++) { s->range_model[i] = 1; s->count_model[i] = 1; } s->range_model[256] = 256; s->count_model[256] = 256; for (i = 0; i < 5; i++) { s->fill_model[i] = 1; } s->fill_model[5] = 5; for (j = 0; j < 4; j++) { for (i = 0; i < 16; i++) { s->sxy_model[j][i] = 1; } s->sxy_model[j][16] = 16; } for (i = 0; i < 512; i++) { s->mv_model[0][i] = 1; s->mv_model[1][i] = 1; } s->mv_model[0][512] = 512; s->mv_model[1][512] = 512; } static int decode(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq) { rc->code -= cumFreq * rc->range; rc->range *= freq; while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) { unsigned byte = bytestream2_get_byte(gb); rc->code = (rc->code << 8) | byte; rc->range <<= 8; } return 0; } static int get_freq(RangeCoder *rc, unsigned total_freq, unsigned *freq) { if (total_freq == 0) return AVERROR_INVALIDDATA; rc->range = rc->range / total_freq; if (rc->range == 0) return AVERROR_INVALIDDATA; *freq = rc->code / rc->range; return 0; } static int decode0(GetByteContext *gb, RangeCoder *rc, unsigned cumFreq, unsigned freq, unsigned total_freq) { unsigned t; if (total_freq == 0) return AVERROR_INVALIDDATA; t = rc->range * (uint64_t)cumFreq / total_freq; rc->code1 += t + 1; rc->range = rc->range * (uint64_t)(freq + cumFreq) / total_freq - (t + 1); while (rc->range < TOP && bytestream2_get_bytes_left(gb) > 0) { unsigned byte = bytestream2_get_byte(gb); rc->code = (rc->code << 8) | byte; rc->code1 <<= 8; rc->range <<= 8; } return 0; } static int get_freq0(RangeCoder *rc, unsigned total_freq, unsigned *freq) { if (rc->range == 0) return AVERROR_INVALIDDATA; *freq = total_freq * (uint64_t)(rc->code - rc->code1) / rc->range; return 0; } static int decode_value(SCPRContext *s, unsigned *cnt, unsigned maxc, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = cnt[maxc]; unsigned value; unsigned c = 0, cumfr = 0, cnt_c = 0; int i, ret; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (c < maxc) { cnt_c = cnt[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0) return ret; cnt[c] = cnt_c + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < maxc; i++) { unsigned nc = (cnt[i] >> 1) + 1; cnt[i] = nc; totfr += nc; } } cnt[maxc] = totfr; *rval = c; return 0; } static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = pixel->total_freq; unsigned value, x = 0, cumfr = 0, cnt_x = 0; int i, j, ret, c, cnt_c; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (x < 16) { cnt_x = pixel->lookup[x]; if (value >= cumfr + cnt_x) cumfr += cnt_x; else break; x++; } c = x * 16; cnt_c = 0; while (c < 256) { cnt_c = pixel->freq[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0) return ret; pixel->freq[c] = cnt_c + step; pixel->lookup[x] = cnt_x + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < 256; i++) { unsigned nc = (pixel->freq[i] >> 1) + 1; pixel->freq[i] = nc; totfr += nc; } for (i = 0; i < 16; i++) { unsigned sum = 0; unsigned i16_17 = i << 4; for (j = 0; j < 16; j++) sum += pixel->freq[i16_17 + j]; pixel->lookup[i] = sum; } } pixel->total_freq = totfr; *rval = c & s->cbits; return 0; } static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int cx = 0, cx1 = 0, k = 0, clr = 0; int run, r, g, b, off, y = 0, x = 0, z, ret; unsigned backstep = linesize - avctx->width; const int cxshift = s->cxshift; unsigned lx, ly, ptype; reinit_tables(s); bytestream2_skip(gb, 2); init_rangecoder(&s->rc, gb); while (k < avctx->width + 1) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = b >> cxshift; ret = decode_value(s, s->run_model[0], 256, 400, &run); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; k += run; while (run-- > 0) { dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } } off = -linesize - 1; ptype = 0; while (x < avctx->width && y < avctx->height) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ret < 0) return ret; if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 1: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = dst[ly * linesize + lx]; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } clr = dst[ly * linesize + lx]; break; case 2: while (run-- > 0) { if (y < 1 || y >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[y * linesize + x + off + 1]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } r = odst[(ly * linesize + lx) * 4] + odst[((y * linesize + x) + off - z) * 4 + 4] - odst[((y * linesize + x) + off - z) * 4]; g = odst[(ly * linesize + lx) * 4 + 1] + odst[((y * linesize + x) + off - z) * 4 + 5] - odst[((y * linesize + x) + off - z) * 4 + 1]; b = odst[(ly * linesize + lx) * 4 + 2] + odst[((y * linesize + x) + off - z) * 4 + 6] - odst[((y * linesize + x) + off - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 5: while (run-- > 0) { if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } clr = dst[y * linesize + x + off - z]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } return 0; } static int decompress_p(AVCodecContext *avctx, uint32_t *dst, int linesize, uint32_t *prev, int plinesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int ret, temp, min, max, x, y, cx = 0, cx1 = 0; int backstep = linesize - avctx->width; const int cxshift = s->cxshift; if (bytestream2_get_byte(gb) == 0) return 0; bytestream2_skip(gb, 1); init_rangecoder(&s->rc, gb); ret = decode_value(s, s->range_model, 256, 1, &min); ret |= decode_value(s, s->range_model, 256, 1, &temp); min += temp << 8; ret |= decode_value(s, s->range_model, 256, 1, &max); ret |= decode_value(s, s->range_model, 256, 1, &temp); if (ret < 0) return ret; max += temp << 8; memset(s->blocks, 0, sizeof(*s->blocks) * s->nbcount); while (min <= max) { int fill, count; ret = decode_value(s, s->fill_model, 5, 10, &fill); ret |= decode_value(s, s->count_model, 256, 20, &count); if (ret < 0) return ret; while (min < s->nbcount && count-- > 0) { s->blocks[min++] = fill; } } for (y = 0; y < s->nby; y++) { for (x = 0; x < s->nbx; x++) { int sy1 = 0, sy2 = 16, sx1 = 0, sx2 = 16; if (s->blocks[y * s->nbx + x] == 0) continue; if (((s->blocks[y * s->nbx + x] - 1) & 1) > 0) { ret = decode_value(s, s->sxy_model[0], 16, 100, &sx1); ret |= decode_value(s, s->sxy_model[1], 16, 100, &sy1); ret |= decode_value(s, s->sxy_model[2], 16, 100, &sx2); ret |= decode_value(s, s->sxy_model[3], 16, 100, &sy2); if (ret < 0) return ret; sx2++; sy2++; } if (((s->blocks[y * s->nbx + x] - 1) & 2) > 0) { int i, j, by = y * 16, bx = x * 16; int mvx, mvy; ret = decode_value(s, s->mv_model[0], 512, 100, &mvx); ret |= decode_value(s, s->mv_model[1], 512, 100, &mvy); if (ret < 0) return ret; mvx -= 256; mvy -= 256; if (by + mvy + sy1 < 0 || bx + mvx + sx1 < 0 || by + mvy + sy1 >= avctx->height || bx + mvx + sx1 >= avctx->width) return AVERROR_INVALIDDATA; for (i = 0; i < sy2 - sy1 && (by + sy1 + i) < avctx->height && (by + mvy + sy1 + i) < avctx->height; i++) { for (j = 0; j < sx2 - sx1 && (bx + sx1 + j) < avctx->width && (bx + mvx + sx1 + j) < avctx->width; j++) { dst[(by + i + sy1) * linesize + bx + sx1 + j] = prev[(by + mvy + sy1 + i) * plinesize + bx + sx1 + mvx + j]; } } } else { int run, r, g, b, z, bx = x * 16 + sx1, by = y * 16 + sy1; unsigned clr, ptype = 0; for (; by < y * 16 + sy2 && by < avctx->height;) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (by >= avctx->height) return AVERROR_INVALIDDATA; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 1: while (run-- > 0) { if (bx == 0) { if (by < 1) return AVERROR_INVALIDDATA; z = backstep; } else { z = 0; } if (by >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[by * linesize + bx - 1 - z]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 2: while (run-- > 0) { if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[(by - 1) * linesize + bx]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 3: while (run-- > 0) { if (by >= avctx->height) return AVERROR_INVALIDDATA; clr = prev[by * plinesize + bx]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; if (bx == 0) { z = backstep; } else { z = 0; } r = odst[((by - 1) * linesize + bx) * 4] + odst[(by * linesize + bx - 1 - z) * 4] - odst[((by - 1) * linesize + bx - 1 - z) * 4]; g = odst[((by - 1) * linesize + bx) * 4 + 1] + odst[(by * linesize + bx - 1 - z) * 4 + 1] - odst[((by - 1) * linesize + bx - 1 - z) * 4 + 1]; b = odst[((by - 1) * linesize + bx) * 4 + 2] + odst[(by * linesize + bx - 1 - z) * 4 + 2] - odst[((by - 1) * linesize + bx - 1 - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 5: while (run-- > 0) { if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; if (bx == 0) { z = backstep; } else { z = 0; } clr = dst[(by - 1) * linesize + bx - 1 - z]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } } } } return 0; } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; AVFrame *frame = data; int ret, type; if (avctx->bits_per_coded_sample == 16) { if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; } if ((ret = ff_reget_buffer(avctx, s->current_frame)) < 0) return ret; bytestream2_init(gb, avpkt->data, avpkt->size); type = bytestream2_peek_byte(gb); if (type == 2) { s->get_freq = get_freq0; s->decode = decode0; frame->key_frame = 1; ret = decompress_i(avctx, (uint32_t *)s->current_frame->data[0], s->current_frame->linesize[0] / 4); } else if (type == 18) { s->get_freq = get_freq; s->decode = decode; frame->key_frame = 1; ret = decompress_i(avctx, (uint32_t *)s->current_frame->data[0], s->current_frame->linesize[0] / 4); } else if (type == 17) { uint32_t clr, *dst = (uint32_t *)s->current_frame->data[0]; int x, y; frame->key_frame = 1; bytestream2_skip(gb, 1); if (avctx->bits_per_coded_sample == 16) { uint16_t value = bytestream2_get_le16(gb); int r, g, b; r = (value ) & 31; g = (value >> 5) & 31; b = (value >> 10) & 31; clr = (r << 16) + (g << 8) + b; } else { clr = bytestream2_get_le24(gb); } for (y = 0; y < avctx->height; y++) { for (x = 0; x < avctx->width; x++) { dst[x] = clr; } dst += s->current_frame->linesize[0] / 4; } } else if (type == 0 || type == 1) { frame->key_frame = 0; ret = av_frame_copy(s->current_frame, s->last_frame); if (ret < 0) return ret; ret = decompress_p(avctx, (uint32_t *)s->current_frame->data[0], s->current_frame->linesize[0] / 4, (uint32_t *)s->last_frame->data[0], s->last_frame->linesize[0] / 4); } else { return AVERROR_PATCHWELCOME; } if (ret < 0) return ret; if (avctx->bits_per_coded_sample != 16) { ret = av_frame_ref(data, s->current_frame); if (ret < 0) return ret; } else { uint8_t *dst = frame->data[0]; int x, y; ret = av_frame_copy(frame, s->current_frame); if (ret < 0) return ret; for (y = 0; y < avctx->height; y++) { for (x = 0; x < avctx->width * 4; x++) { dst[x] = dst[x] << 3; } dst += frame->linesize[0]; } } frame->pict_type = frame->key_frame ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; FFSWAP(AVFrame *, s->current_frame, s->last_frame); frame->data[0] += frame->linesize[0] * (avctx->height - 1); frame->linesize[0] *= -1; *got_frame = 1; return avpkt->size; } static av_cold int decode_init(AVCodecContext *avctx) { SCPRContext *s = avctx->priv_data; switch (avctx->bits_per_coded_sample) { case 16: avctx->pix_fmt = AV_PIX_FMT_RGB0; break; case 24: case 32: avctx->pix_fmt = AV_PIX_FMT_BGR0; break; default: av_log(avctx, AV_LOG_ERROR, "Unsupported bitdepth %i\n", avctx->bits_per_coded_sample); return AVERROR_INVALIDDATA; } s->get_freq = get_freq0; s->decode = decode0; s->cxshift = avctx->bits_per_coded_sample == 16 ? 0 : 2; s->cbits = avctx->bits_per_coded_sample == 16 ? 0x1F : 0xFF; s->nbx = (avctx->width + 15) / 16; s->nby = (avctx->height + 15) / 16; s->nbcount = s->nbx * s->nby; s->blocks = av_malloc_array(s->nbcount, sizeof(*s->blocks)); if (!s->blocks) return AVERROR(ENOMEM); s->last_frame = av_frame_alloc(); s->current_frame = av_frame_alloc(); if (!s->last_frame || !s->current_frame) return AVERROR(ENOMEM); return 0; } static av_cold int decode_close(AVCodecContext *avctx) { SCPRContext *s = avctx->priv_data; av_freep(&s->blocks); av_frame_free(&s->last_frame); av_frame_free(&s->current_frame); return 0; } AVCodec ff_scpr_decoder = { .name = "scpr", .long_name = NULL_IF_CONFIG_SMALL("ScreenPressor"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_SCPR, .priv_data_size = sizeof(SCPRContext), .init = decode_init, .close = decode_close, .decode = decode_frame, .capabilities = AV_CODEC_CAP_DR1, .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3420_0
crossvul-cpp_data_bad_2045_0
/* * OpenPBS (Portable Batch System) v2.3 Software License * * Copyright (c) 1999-2000 Veridian Information Solutions, Inc. * All rights reserved. * * --------------------------------------------------------------------------- * For a license to use or redistribute the OpenPBS software under conditions * other than those described below, or to purchase support for this software, * please contact Veridian Systems, PBS Products Department ("Licensor") at: * * www.OpenPBS.org +1 650 967-4675 sales@OpenPBS.org * 877 902-4PBS (US toll-free) * --------------------------------------------------------------------------- * * This license covers use of the OpenPBS v2.3 software (the "Software") at * your site or location, and, for certain users, redistribution of the * Software to other sites and locations. Use and redistribution of * OpenPBS v2.3 in source and binary forms, with or without modification, * are permitted provided that all of the following conditions are met. * After December 31, 2001, only conditions 3-6 must be met: * * 1. Commercial and/or non-commercial use of the Software is permitted * provided a current software registration is on file at www.OpenPBS.org. * If use of this software contributes to a publication, product, or * service, proper attribution must be given; see www.OpenPBS.org/credit.html * * 2. Redistribution in any form is only permitted for non-commercial, * non-profit purposes. There can be no charge for the Software or any * software incorporating the Software. Further, there can be no * expectation of revenue generated as a consequence of redistributing * the Software. * * 3. Any Redistribution of source code must retain the above copyright notice * and the acknowledgment contained in paragraph 6, this list of conditions * and the disclaimer contained in paragraph 7. * * 4. Any Redistribution in binary form must reproduce the above copyright * notice and the acknowledgment contained in paragraph 6, this list of * conditions and the disclaimer contained in paragraph 7 in the * documentation and/or other materials provided with the distribution. * * 5. Redistributions in any form must be accompanied by information on how to * obtain complete source code for the OpenPBS software and any * modifications and/or additions to the OpenPBS software. The source code * must either be included in the distribution or be available for no more * than the cost of distribution plus a nominal fee, and all modifications * and additions to the Software must be freely redistributable by any party * (including Licensor) without restriction. * * 6. All advertising materials mentioning features or use of the Software must * display the following acknowledgment: * * "This product includes software developed by NASA Ames Research Center, * Lawrence Livermore National Laboratory, and Veridian Information * Solutions, Inc. * Visit www.OpenPBS.org for OpenPBS software support, * products, and information." * * 7. DISCLAIMER OF WARRANTY * * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT * ARE EXPRESSLY DISCLAIMED. * * IN NO EVENT SHALL VERIDIAN CORPORATION, ITS AFFILIATED COMPANIES, OR THE * U.S. GOVERNMENT OR ANY OF ITS AGENCIES BE LIABLE FOR ANY DIRECT OR INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This license will be governed by the laws of the Commonwealth of Virginia, * without reference to its choice of law rules. */ #include <pbs_config.h> /* the master config generated by configure */ #include <assert.h> #include <stddef.h> #include "dis.h" #include "dis_.h" int disrsi_( int stream, int *negate, unsigned *value, unsigned count) { int c; unsigned locval; unsigned ndigs; char *cp; char scratch[DIS_BUFSIZ+1]; assert(negate != NULL); assert(value != NULL); assert(count); assert(stream >= 0); assert(dis_getc != NULL); assert(dis_gets != NULL); memset(scratch, 0, DIS_BUFSIZ+1); if (dis_umaxd == 0) disiui_(); switch (c = (*dis_getc)(stream)) { case '-': case '+': *negate = c == '-'; if ((*dis_gets)(stream, scratch, count) != (int)count) { return(DIS_EOD); } if (count >= dis_umaxd) { if (count > dis_umaxd) goto overflow; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) goto overflow; } cp = scratch; locval = 0; do { if (((c = *cp++) < '0') || (c > '9')) { return(DIS_NONDIGIT); } locval = 10 * locval + c - '0'; } while (--count); *value = locval; return (DIS_SUCCESS); break; case '0': return (DIS_LEADZRO); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigs = c - '0'; if (count > 1) { if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) { return(DIS_EOD); } cp = scratch; if (count >= dis_umaxd) { if (count > dis_umaxd) break; *cp = c; if (memcmp(scratch, dis_umax, dis_umaxd) > 0) break; } while (--count) { if (((c = *++cp) < '0') || (c > '9')) { return(DIS_NONDIGIT); } ndigs = 10 * ndigs + c - '0'; } } /* END if (count > 1) */ return(disrsi_(stream, negate, value, ndigs)); /*NOTREACHED*/ break; case - 1: return(DIS_EOD); /*NOTREACHED*/ break; case -2: return(DIS_EOF); /*NOTREACHED*/ break; default: return(DIS_NONDIGIT); /*NOTREACHED*/ break; } *negate = FALSE; overflow: *value = UINT_MAX; return(DIS_OVERFLOW); } /* END disrsi_() */
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2045_0
crossvul-cpp_data_bad_4837_0
/* * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * multiple format streaming server based on the FFmpeg libraries */ #include "config.h" #if !HAVE_CLOSESOCKET #define closesocket close #endif #include <string.h> #include <stdlib.h> #include <stdio.h> #include "libavformat/avformat.h" /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */ #include "libavformat/rtpproto.h" #include "libavformat/rtsp.h" #include "libavformat/avio_internal.h" #include "libavformat/internal.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/lfg.h" #include "libavutil/dict.h" #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "libavutil/random_seed.h" #include "libavutil/rational.h" #include "libavutil/parseutils.h" #include "libavutil/opt.h" #include "libavutil/time.h" #include <stdarg.h> #if HAVE_UNISTD_H #include <unistd.h> #endif #include <fcntl.h> #include <sys/ioctl.h> #if HAVE_POLL_H #include <poll.h> #endif #include <errno.h> #include <time.h> #include <sys/wait.h> #include <signal.h> #include "cmdutils.h" #include "ffserver_config.h" #define PATH_LENGTH 1024 const char program_name[] = "ffserver"; const int program_birth_year = 2000; static const OptionDef options[]; enum HTTPState { HTTPSTATE_WAIT_REQUEST, HTTPSTATE_SEND_HEADER, HTTPSTATE_SEND_DATA_HEADER, HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */ HTTPSTATE_SEND_DATA_TRAILER, HTTPSTATE_RECEIVE_DATA, HTTPSTATE_WAIT_FEED, /* wait for data from the feed */ HTTPSTATE_READY, RTSPSTATE_WAIT_REQUEST, RTSPSTATE_SEND_REPLY, RTSPSTATE_SEND_PACKET, }; static const char * const http_state[] = { "HTTP_WAIT_REQUEST", "HTTP_SEND_HEADER", "SEND_DATA_HEADER", "SEND_DATA", "SEND_DATA_TRAILER", "RECEIVE_DATA", "WAIT_FEED", "READY", "RTSP_WAIT_REQUEST", "RTSP_SEND_REPLY", "RTSP_SEND_PACKET", }; #define IOBUFFER_INIT_SIZE 8192 /* timeouts are in ms */ #define HTTP_REQUEST_TIMEOUT (15 * 1000) #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000) #define SYNC_TIMEOUT (10 * 1000) typedef struct RTSPActionServerSetup { uint32_t ipaddr; char transport_option[512]; } RTSPActionServerSetup; typedef struct { int64_t count1, count2; int64_t time1, time2; } DataRateData; /* context associated with one connection */ typedef struct HTTPContext { enum HTTPState state; int fd; /* socket file descriptor */ struct sockaddr_in from_addr; /* origin */ struct pollfd *poll_entry; /* used when polling */ int64_t timeout; uint8_t *buffer_ptr, *buffer_end; int http_error; int post; int chunked_encoding; int chunk_size; /* 0 if it needs to be read */ struct HTTPContext *next; int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */ int64_t data_count; /* feed input */ int feed_fd; /* input format handling */ AVFormatContext *fmt_in; int64_t start_time; /* In milliseconds - this wraps fairly often */ int64_t first_pts; /* initial pts value */ int64_t cur_pts; /* current pts value from the stream in us */ int64_t cur_frame_duration; /* duration of the current frame in us */ int cur_frame_bytes; /* output frame size, needed to compute the time at which we send each packet */ int pts_stream_index; /* stream we choose as clock reference */ int64_t cur_clock; /* current clock reference value in us */ /* output format handling */ struct FFServerStream *stream; /* -1 is invalid stream */ int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */ int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */ int switch_pending; AVFormatContext *pfmt_ctx; /* instance of FFServerStream for one user */ int last_packet_sent; /* true if last data packet was sent */ int suppress_log; DataRateData datarate; int wmp_client_id; char protocol[16]; char method[16]; char url[128]; char clean_url[128*7]; int buffer_size; uint8_t *buffer; int is_packetized; /* if true, the stream is packetized */ int packet_stream_index; /* current stream for output in state machine */ /* RTSP state specific */ uint8_t *pb_buffer; /* XXX: use that in all the code */ AVIOContext *pb; int seq; /* RTSP sequence number */ /* RTP state specific */ enum RTSPLowerTransport rtp_protocol; char session_id[32]; /* session id */ AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS]; /* RTP/UDP specific */ URLContext *rtp_handles[FFSERVER_MAX_STREAMS]; /* RTP/TCP specific */ struct HTTPContext *rtsp_c; uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end; } HTTPContext; static HTTPContext *first_http_ctx; static FFServerConfig config = { .nb_max_http_connections = 2000, .nb_max_connections = 5, .max_bandwidth = 1000, .use_defaults = 1, }; static void new_connection(int server_fd, int is_rtsp); static void close_connection(HTTPContext *c); /* HTTP handling */ static int handle_connection(HTTPContext *c); static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream); static void compute_status(HTTPContext *c); static int open_input_stream(HTTPContext *c, const char *info); static int http_parse_request(HTTPContext *c); static int http_send_data(HTTPContext *c); static int http_start_receive_data(HTTPContext *c); static int http_receive_data(HTTPContext *c); /* RTSP handling */ static int rtsp_parse_request(HTTPContext *c); static void rtsp_cmd_describe(HTTPContext *c, const char *url); static void rtsp_cmd_options(HTTPContext *c, const char *url); static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPMessageHeader *h); static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h); static void rtsp_cmd_interrupt(HTTPContext *c, const char *url, RTSPMessageHeader *h, int pause_only); /* SDP handling */ static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer, struct in_addr my_ip); /* RTP handling */ static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr, FFServerStream *stream, const char *session_id, enum RTSPLowerTransport rtp_protocol); static int rtp_new_av_stream(HTTPContext *c, int stream_index, struct sockaddr_in *dest_addr, HTTPContext *rtsp_c); /* utils */ static size_t htmlencode (const char *src, char **dest); static inline void cp_html_entity (char *buffer, const char *entity); static inline int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream); static const char *my_program_name; static int no_launch; static int need_to_start_children; /* maximum number of simultaneous HTTP connections */ static unsigned int nb_connections; static uint64_t current_bandwidth; /* Making this global saves on passing it around everywhere */ static int64_t cur_time; static AVLFG random_state; static FILE *logfile = NULL; static void unlayer_stream(AVStream *st, LayeredAVStream *lst) { avcodec_free_context(&st->codec); avcodec_parameters_free(&st->codecpar); #define COPY(a) st->a = lst->a; COPY(index) COPY(id) COPY(codec) COPY(codecpar) COPY(time_base) COPY(pts_wrap_bits) COPY(sample_aspect_ratio) COPY(recommended_encoder_configuration) } static inline void cp_html_entity (char *buffer, const char *entity) { if (!buffer || !entity) return; while (*entity) *buffer++ = *entity++; } /** * Substitutes known conflicting chars on a text string with * their corresponding HTML entities. * * Returns the number of bytes in the 'encoded' representation * not including the terminating NUL. */ static size_t htmlencode (const char *src, char **dest) { const char *amp = "&amp;"; const char *lt = "&lt;"; const char *gt = "&gt;"; const char *start; char *tmp; size_t final_size = 0; if (!src) return 0; start = src; /* Compute needed dest size */ while (*src != '\0') { switch(*src) { case 38: /* & */ final_size += 5; break; case 60: /* < */ case 62: /* > */ final_size += 4; break; default: final_size++; } src++; } src = start; *dest = av_mallocz(final_size + 1); if (!*dest) return 0; /* Build dest */ tmp = *dest; while (*src != '\0') { switch(*src) { case 38: /* & */ cp_html_entity (tmp, amp); tmp += 5; break; case 60: /* < */ cp_html_entity (tmp, lt); tmp += 4; break; case 62: /* > */ cp_html_entity (tmp, gt); tmp += 4; break; default: *tmp = *src; tmp += 1; } src++; } *tmp = '\0'; return final_size; } static int64_t ffm_read_write_index(int fd) { uint8_t buf[8]; if (lseek(fd, 8, SEEK_SET) < 0) return AVERROR(EIO); if (read(fd, buf, 8) != 8) return AVERROR(EIO); return AV_RB64(buf); } static int ffm_write_write_index(int fd, int64_t pos) { uint8_t buf[8]; int i; for(i=0;i<8;i++) buf[i] = (pos >> (56 - i * 8)) & 0xff; if (lseek(fd, 8, SEEK_SET) < 0) goto bail_eio; if (write(fd, buf, 8) != 8) goto bail_eio; return 8; bail_eio: return AVERROR(EIO); } static void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size) { av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN); } static char *ctime1(char *buf2, size_t buf_size) { time_t ti; char *p; ti = time(NULL); p = ctime(&ti); if (!p || !*p) { *buf2 = '\0'; return buf2; } av_strlcpy(buf2, p, buf_size); p = buf2 + strlen(buf2) - 1; if (*p == '\n') *p = '\0'; return buf2; } static void http_vlog(const char *fmt, va_list vargs) { static int print_prefix = 1; char buf[32]; if (!logfile) return; if (print_prefix) { ctime1(buf, sizeof(buf)); fprintf(logfile, "%s ", buf); } print_prefix = strstr(fmt, "\n") != NULL; vfprintf(logfile, fmt, vargs); fflush(logfile); } #ifdef __GNUC__ __attribute__ ((format (printf, 1, 2))) #endif static void http_log(const char *fmt, ...) { va_list vargs; va_start(vargs, fmt); http_vlog(fmt, vargs); va_end(vargs); } static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs) { static int print_prefix = 1; AVClass *avc = ptr ? *(AVClass**)ptr : NULL; if (level > av_log_get_level()) return; if (print_prefix && avc) http_log("[%s @ %p]", avc->item_name(ptr), ptr); print_prefix = strstr(fmt, "\n") != NULL; http_vlog(fmt, vargs); } static void log_connection(HTTPContext *c) { if (c->suppress_log) return; http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n", inet_ntoa(c->from_addr.sin_addr), c->method, c->url, c->protocol, (c->http_error ? c->http_error : 200), c->data_count); } static void update_datarate(DataRateData *drd, int64_t count) { if (!drd->time1 && !drd->count1) { drd->time1 = drd->time2 = cur_time; drd->count1 = drd->count2 = count; } else if (cur_time - drd->time2 > 5000) { drd->time1 = drd->time2; drd->count1 = drd->count2; drd->time2 = cur_time; drd->count2 = count; } } /* In bytes per second */ static int compute_datarate(DataRateData *drd, int64_t count) { if (cur_time == drd->time1) return 0; return ((count - drd->count1) * 1000) / (cur_time - drd->time1); } static void start_children(FFServerStream *feed) { char *pathname; char *slash; int i; size_t cmd_length; if (no_launch) return; cmd_length = strlen(my_program_name); /** * FIXME: WIP Safeguard. Remove after clearing all harcoded * '1024' path lengths */ if (cmd_length > PATH_LENGTH - 1) { http_log("Could not start children. Command line: '%s' exceeds " "path length limit (%d)\n", my_program_name, PATH_LENGTH); return; } pathname = av_strdup (my_program_name); if (!pathname) { http_log("Could not allocate memory for children cmd line\n"); return; } /* replace "ffserver" with "ffmpeg" in the path of current * program. Ignore user provided path */ slash = strrchr(pathname, '/'); if (!slash) slash = pathname; else slash++; strcpy(slash, "ffmpeg"); for (; feed; feed = feed->next) { if (!feed->child_argv || feed->pid) continue; feed->pid_start = time(0); feed->pid = fork(); if (feed->pid < 0) { http_log("Unable to create children: %s\n", strerror(errno)); av_free (pathname); exit(EXIT_FAILURE); } if (feed->pid) continue; /* In child */ http_log("Launch command line: "); http_log("%s ", pathname); for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++) http_log("%s ", feed->child_argv[i]); http_log("\n"); for (i = 3; i < 256; i++) close(i); if (!config.debug) { if (!freopen("/dev/null", "r", stdin)) http_log("failed to redirect STDIN to /dev/null\n;"); if (!freopen("/dev/null", "w", stdout)) http_log("failed to redirect STDOUT to /dev/null\n;"); if (!freopen("/dev/null", "w", stderr)) http_log("failed to redirect STDERR to /dev/null\n;"); } signal(SIGPIPE, SIG_DFL); execvp(pathname, feed->child_argv); av_free (pathname); _exit(1); } av_free (pathname); } /* open a listening socket */ static int socket_open_listen(struct sockaddr_in *my_addr) { int server_fd, tmp; server_fd = socket(AF_INET,SOCK_STREAM,0); if (server_fd < 0) { perror ("socket"); return -1; } tmp = 1; if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp))) av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n"); my_addr->sin_family = AF_INET; if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) { char bindmsg[32]; snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port)); perror (bindmsg); goto fail; } if (listen (server_fd, 5) < 0) { perror ("listen"); goto fail; } if (ff_socket_nonblock(server_fd, 1) < 0) av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n"); return server_fd; fail: closesocket(server_fd); return -1; } /* start all multicast streams */ static void start_multicast(void) { FFServerStream *stream; char session_id[32]; HTTPContext *rtp_c; struct sockaddr_in dest_addr = {0}; int default_port, stream_index; unsigned int random0, random1; default_port = 6000; for(stream = config.first_stream; stream; stream = stream->next) { if (!stream->is_multicast) continue; random0 = av_lfg_get(&random_state); random1 = av_lfg_get(&random_state); /* open the RTP connection */ snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1); /* choose a port if none given */ if (stream->multicast_port == 0) { stream->multicast_port = default_port; default_port += 100; } dest_addr.sin_family = AF_INET; dest_addr.sin_addr = stream->multicast_ip; dest_addr.sin_port = htons(stream->multicast_port); rtp_c = rtp_new_connection(&dest_addr, stream, session_id, RTSP_LOWER_TRANSPORT_UDP_MULTICAST); if (!rtp_c) continue; if (open_input_stream(rtp_c, "") < 0) { http_log("Could not open input stream for stream '%s'\n", stream->filename); continue; } /* open each RTP stream */ for(stream_index = 0; stream_index < stream->nb_streams; stream_index++) { dest_addr.sin_port = htons(stream->multicast_port + 2 * stream_index); if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0) continue; http_log("Could not open output stream '%s/streamid=%d'\n", stream->filename, stream_index); exit(1); } rtp_c->state = HTTPSTATE_SEND_DATA; } } /* main loop of the HTTP server */ static int http_server(void) { int server_fd = 0, rtsp_server_fd = 0; int ret, delay; struct pollfd *poll_table, *poll_entry; HTTPContext *c, *c_next; poll_table = av_mallocz_array(config.nb_max_http_connections + 2, sizeof(*poll_table)); if(!poll_table) { http_log("Impossible to allocate a poll table handling %d " "connections.\n", config.nb_max_http_connections); return -1; } if (config.http_addr.sin_port) { server_fd = socket_open_listen(&config.http_addr); if (server_fd < 0) goto quit; } if (config.rtsp_addr.sin_port) { rtsp_server_fd = socket_open_listen(&config.rtsp_addr); if (rtsp_server_fd < 0) { closesocket(server_fd); goto quit; } } if (!rtsp_server_fd && !server_fd) { http_log("HTTP and RTSP disabled.\n"); goto quit; } http_log("FFserver started.\n"); start_children(config.first_feed); start_multicast(); for(;;) { poll_entry = poll_table; if (server_fd) { poll_entry->fd = server_fd; poll_entry->events = POLLIN; poll_entry++; } if (rtsp_server_fd) { poll_entry->fd = rtsp_server_fd; poll_entry->events = POLLIN; poll_entry++; } /* wait for events on each HTTP handle */ c = first_http_ctx; delay = 1000; while (c) { int fd; fd = c->fd; switch(c->state) { case HTTPSTATE_SEND_HEADER: case RTSPSTATE_SEND_REPLY: case RTSPSTATE_SEND_PACKET: c->poll_entry = poll_entry; poll_entry->fd = fd; poll_entry->events = POLLOUT; poll_entry++; break; case HTTPSTATE_SEND_DATA_HEADER: case HTTPSTATE_SEND_DATA: case HTTPSTATE_SEND_DATA_TRAILER: if (!c->is_packetized) { /* for TCP, we output as much as we can * (may need to put a limit) */ c->poll_entry = poll_entry; poll_entry->fd = fd; poll_entry->events = POLLOUT; poll_entry++; } else { /* when ffserver is doing the timing, we work by * looking at which packet needs to be sent every * 10 ms (one tick wait XXX: 10 ms assumed) */ if (delay > 10) delay = 10; } break; case HTTPSTATE_WAIT_REQUEST: case HTTPSTATE_RECEIVE_DATA: case HTTPSTATE_WAIT_FEED: case RTSPSTATE_WAIT_REQUEST: /* need to catch errors */ c->poll_entry = poll_entry; poll_entry->fd = fd; poll_entry->events = POLLIN;/* Maybe this will work */ poll_entry++; break; default: c->poll_entry = NULL; break; } c = c->next; } /* wait for an event on one connection. We poll at least every * second to handle timeouts */ do { ret = poll(poll_table, poll_entry - poll_table, delay); if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) { goto quit; } } while (ret < 0); cur_time = av_gettime() / 1000; if (need_to_start_children) { need_to_start_children = 0; start_children(config.first_feed); } /* now handle the events */ for(c = first_http_ctx; c; c = c_next) { c_next = c->next; if (handle_connection(c) < 0) { log_connection(c); /* close and free the connection */ close_connection(c); } } poll_entry = poll_table; if (server_fd) { /* new HTTP connection request ? */ if (poll_entry->revents & POLLIN) new_connection(server_fd, 0); poll_entry++; } if (rtsp_server_fd) { /* new RTSP connection request ? */ if (poll_entry->revents & POLLIN) new_connection(rtsp_server_fd, 1); } } quit: av_free(poll_table); return -1; } /* start waiting for a new HTTP/RTSP request */ static void start_wait_request(HTTPContext *c, int is_rtsp) { c->buffer_ptr = c->buffer; c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */ c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST; c->timeout = cur_time + (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT); } static void http_send_too_busy_reply(int fd) { char buffer[400]; int len = snprintf(buffer, sizeof(buffer), "HTTP/1.0 503 Server too busy\r\n" "Content-type: text/html\r\n" "\r\n" "<!DOCTYPE html>\n" "<html><head><title>Too busy</title></head><body>\r\n" "<p>The server is too busy to serve your request at " "this time.</p>\r\n" "<p>The number of current connections is %u, and this " "exceeds the limit of %u.</p>\r\n" "</body></html>\r\n", nb_connections, config.nb_max_connections); av_assert0(len < sizeof(buffer)); if (send(fd, buffer, len, 0) < len) av_log(NULL, AV_LOG_WARNING, "Could not send too-busy reply, send() failed\n"); } static void new_connection(int server_fd, int is_rtsp) { struct sockaddr_in from_addr; socklen_t len; int fd; HTTPContext *c = NULL; len = sizeof(from_addr); fd = accept(server_fd, (struct sockaddr *)&from_addr, &len); if (fd < 0) { http_log("error during accept %s\n", strerror(errno)); return; } if (ff_socket_nonblock(fd, 1) < 0) av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n"); if (nb_connections >= config.nb_max_connections) { http_send_too_busy_reply(fd); goto fail; } /* add a new connection */ c = av_mallocz(sizeof(HTTPContext)); if (!c) goto fail; c->fd = fd; c->poll_entry = NULL; c->from_addr = from_addr; c->buffer_size = IOBUFFER_INIT_SIZE; c->buffer = av_malloc(c->buffer_size); if (!c->buffer) goto fail; c->next = first_http_ctx; first_http_ctx = c; nb_connections++; start_wait_request(c, is_rtsp); return; fail: if (c) { av_freep(&c->buffer); av_free(c); } closesocket(fd); } static void close_connection(HTTPContext *c) { HTTPContext **cp, *c1; int i, nb_streams; AVFormatContext *ctx; AVStream *st; /* remove connection from list */ cp = &first_http_ctx; while (*cp) { c1 = *cp; if (c1 == c) *cp = c->next; else cp = &c1->next; } /* remove references, if any (XXX: do it faster) */ for(c1 = first_http_ctx; c1; c1 = c1->next) { if (c1->rtsp_c == c) c1->rtsp_c = NULL; } /* remove connection associated resources */ if (c->fd >= 0) closesocket(c->fd); if (c->fmt_in) { /* close each frame parser */ for(i=0;i<c->fmt_in->nb_streams;i++) { st = c->fmt_in->streams[i]; if (st->codec->codec) avcodec_close(st->codec); } avformat_close_input(&c->fmt_in); } /* free RTP output streams if any */ nb_streams = 0; if (c->stream) nb_streams = c->stream->nb_streams; for(i=0;i<nb_streams;i++) { ctx = c->rtp_ctx[i]; if (ctx) { av_write_trailer(ctx); av_dict_free(&ctx->metadata); av_freep(&ctx->streams[0]); av_freep(&ctx); } ffurl_close(c->rtp_handles[i]); } ctx = c->pfmt_ctx; if (ctx) { if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) { /* prepare header */ if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) { av_write_trailer(ctx); av_freep(&c->pb_buffer); avio_close_dyn_buf(ctx->pb, &c->pb_buffer); } } for(i=0; i<ctx->nb_streams; i++) av_freep(&ctx->streams[i]); av_freep(&ctx->streams); av_freep(&ctx->priv_data); } if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE) current_bandwidth -= c->stream->bandwidth; /* signal that there is no feed if we are the feeder socket */ if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) { c->stream->feed_opened = 0; close(c->feed_fd); } av_freep(&c->pb_buffer); av_freep(&c->packet_buffer); av_freep(&c->buffer); av_free(c); nb_connections--; } static int handle_connection(HTTPContext *c) { int len, ret; uint8_t *ptr; switch(c->state) { case HTTPSTATE_WAIT_REQUEST: case RTSPSTATE_WAIT_REQUEST: /* timeout ? */ if ((c->timeout - cur_time) < 0) return -1; if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; /* no need to read if no events */ if (!(c->poll_entry->revents & POLLIN)) return 0; /* read the data */ read_loop: if (!(len = recv(c->fd, c->buffer_ptr, 1, 0))) return -1; if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) return -1; break; } /* search for end of request. */ c->buffer_ptr += len; ptr = c->buffer_ptr; if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) || (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) { /* request found : parse it and reply */ if (c->state == HTTPSTATE_WAIT_REQUEST) ret = http_parse_request(c); else ret = rtsp_parse_request(c); if (ret < 0) return -1; } else if (ptr >= c->buffer_end) { /* request too long: cannot do anything */ return -1; } else goto read_loop; break; case HTTPSTATE_SEND_HEADER: if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; /* no need to write if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) { goto close_connection; } break; } c->buffer_ptr += len; if (c->stream) c->stream->bytes_served += len; c->data_count += len; if (c->buffer_ptr >= c->buffer_end) { av_freep(&c->pb_buffer); /* if error, exit */ if (c->http_error) return -1; /* all the buffer was sent : synchronize to the incoming * stream */ c->state = HTTPSTATE_SEND_DATA_HEADER; c->buffer_ptr = c->buffer_end = c->buffer; } break; case HTTPSTATE_SEND_DATA: case HTTPSTATE_SEND_DATA_HEADER: case HTTPSTATE_SEND_DATA_TRAILER: /* for packetized output, we consider we can always write (the * input streams set the speed). It may be better to verify * that we do not rely too much on the kernel queues */ if (!c->is_packetized) { if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; /* no need to read if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; } if (http_send_data(c) < 0) return -1; /* close connection if trailer sent */ if (c->state == HTTPSTATE_SEND_DATA_TRAILER) return -1; /* Check if it is a single jpeg frame 123 */ if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) { close_connection(c); } break; case HTTPSTATE_RECEIVE_DATA: /* no need to read if no events */ if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; if (!(c->poll_entry->revents & POLLIN)) return 0; if (http_receive_data(c) < 0) return -1; break; case HTTPSTATE_WAIT_FEED: /* no need to read if no events */ if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP)) return -1; /* nothing to do, we'll be waken up by incoming feed packets */ break; case RTSPSTATE_SEND_REPLY: if (c->poll_entry->revents & (POLLERR | POLLHUP)) goto close_connection; /* no need to write if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) { goto close_connection; } break; } c->buffer_ptr += len; c->data_count += len; if (c->buffer_ptr >= c->buffer_end) { /* all the buffer was sent : wait for a new request */ av_freep(&c->pb_buffer); start_wait_request(c, 1); } break; case RTSPSTATE_SEND_PACKET: if (c->poll_entry->revents & (POLLERR | POLLHUP)) { av_freep(&c->packet_buffer); return -1; } /* no need to write if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; len = send(c->fd, c->packet_buffer_ptr, c->packet_buffer_end - c->packet_buffer_ptr, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) { /* error : close connection */ av_freep(&c->packet_buffer); return -1; } break; } c->packet_buffer_ptr += len; if (c->packet_buffer_ptr >= c->packet_buffer_end) { /* all the buffer was sent : wait for a new request */ av_freep(&c->packet_buffer); c->state = RTSPSTATE_WAIT_REQUEST; } break; case HTTPSTATE_READY: /* nothing to do */ break; default: return -1; } return 0; close_connection: av_freep(&c->pb_buffer); return -1; } static int extract_rates(char *rates, int ratelen, const char *request) { const char *p; for (p = request; *p && *p != '\r' && *p != '\n'; ) { if (av_strncasecmp(p, "Pragma:", 7) == 0) { const char *q = p + 7; while (*q && *q != '\n' && av_isspace(*q)) q++; if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) { int stream_no; int rate_no; q += 20; memset(rates, 0xff, ratelen); while (1) { while (*q && *q != '\n' && *q != ':') q++; if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2) break; stream_no--; if (stream_no < ratelen && stream_no >= 0) rates[stream_no] = rate_no; while (*q && *q != '\n' && !av_isspace(*q)) q++; } return 1; } } p = strchr(p, '\n'); if (!p) break; p++; } return 0; } static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec, int bit_rate) { int i; int best_bitrate = 100000000; int best = -1; for (i = 0; i < feed->nb_streams; i++) { AVCodecParameters *feed_codec = feed->streams[i]->codecpar; if (feed_codec->codec_id != codec->codec_id || feed_codec->sample_rate != codec->sample_rate || feed_codec->width != codec->width || feed_codec->height != codec->height) continue; /* Potential stream */ /* We want the fastest stream less than bit_rate, or the slowest * faster than bit_rate */ if (feed_codec->bit_rate <= bit_rate) { if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) { best_bitrate = feed_codec->bit_rate; best = i; } continue; } if (feed_codec->bit_rate < best_bitrate) { best_bitrate = feed_codec->bit_rate; best = i; } } return best; } static int modify_current_stream(HTTPContext *c, char *rates) { int i; FFServerStream *req = c->stream; int action_required = 0; /* Not much we can do for a feed */ if (!req->feed) return 0; for (i = 0; i < req->nb_streams; i++) { AVCodecParameters *codec = req->streams[i]->codecpar; switch(rates[i]) { case 0: c->switch_feed_streams[i] = req->feed_streams[i]; break; case 1: c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2); break; case 2: /* Wants off or slow */ c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4); #ifdef WANTS_OFF /* This doesn't work well when it turns off the only stream! */ c->switch_feed_streams[i] = -2; c->feed_streams[i] = -2; #endif break; } if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i]) { action_required = 1; } } return action_required; } static void get_word(char *buf, int buf_size, const char **pp) { const char *p; char *q; #define SPACE_CHARS " \t\r\n" p = *pp; p += strspn(p, SPACE_CHARS); q = buf; while (!av_isspace(*p) && *p != '\0') { if ((q - buf) < buf_size - 1) *q++ = *p; p++; } if (buf_size > 0) *q = '\0'; *pp = p; } static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream, HTTPContext *c) { FILE* f; char line[1024]; char cmd[1024]; FFServerIPAddressACL *acl = NULL; int line_num = 0; const char *p; f = fopen(stream->dynamic_acl, "r"); if (!f) { perror(stream->dynamic_acl); return NULL; } acl = av_mallocz(sizeof(FFServerIPAddressACL)); if (!acl) { fclose(f); return NULL; } /* Build ACL */ while (fgets(line, sizeof(line), f)) { line_num++; p = line; while (av_isspace(*p)) p++; if (*p == '\0' || *p == '#') continue; ffserver_get_arg(cmd, sizeof(cmd), &p); if (!av_strcasecmp(cmd, "ACL")) ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl, line_num); } fclose(f); return acl; } static void free_acl_list(FFServerIPAddressACL *in_acl) { FFServerIPAddressACL *pacl, *pacl2; pacl = in_acl; while(pacl) { pacl2 = pacl; pacl = pacl->next; av_freep(pacl2); } } static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c) { enum FFServerIPAddressAction last_action = IP_DENY; FFServerIPAddressACL *acl; struct in_addr *src = &c->from_addr.sin_addr; unsigned long src_addr = src->s_addr; for (acl = in_acl; acl; acl = acl->next) { if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr) return (acl->action == IP_ALLOW) ? 1 : 0; last_action = acl->action; } /* Nothing matched, so return not the last action */ return (last_action == IP_DENY) ? 1 : 0; } static int validate_acl(FFServerStream *stream, HTTPContext *c) { int ret = 0; FFServerIPAddressACL *acl; /* if stream->acl is null validate_acl_list will return 1 */ ret = validate_acl_list(stream->acl, c); if (stream->dynamic_acl[0]) { acl = parse_dynamic_acl(stream, c); ret = validate_acl_list(acl, c); free_acl_list(acl); } return ret; } /** * compute the real filename of a file by matching it without its * extensions to all the stream's filenames */ static void compute_real_filename(char *filename, int max_size) { char file1[1024]; char file2[1024]; char *p; FFServerStream *stream; av_strlcpy(file1, filename, sizeof(file1)); p = strrchr(file1, '.'); if (p) *p = '\0'; for(stream = config.first_stream; stream; stream = stream->next) { av_strlcpy(file2, stream->filename, sizeof(file2)); p = strrchr(file2, '.'); if (p) *p = '\0'; if (!strcmp(file1, file2)) { av_strlcpy(filename, stream->filename, max_size); break; } } } enum RedirType { REDIR_NONE, REDIR_ASX, REDIR_RAM, REDIR_ASF, REDIR_RTSP, REDIR_SDP, }; /* parse HTTP request and prepare header */ static int http_parse_request(HTTPContext *c) { const char *p; char *p1; enum RedirType redir_type; char cmd[32]; char info[1024], filename[1024]; char url[1024], *q; char protocol[32]; char msg[1024]; char *encoded_msg = NULL; const char *mime_type; FFServerStream *stream; int i; char ratebuf[32]; const char *useragent = 0; p = c->buffer; get_word(cmd, sizeof(cmd), &p); av_strlcpy(c->method, cmd, sizeof(c->method)); if (!strcmp(cmd, "GET")) c->post = 0; else if (!strcmp(cmd, "POST")) c->post = 1; else return -1; get_word(url, sizeof(url), &p); av_strlcpy(c->url, url, sizeof(c->url)); get_word(protocol, sizeof(protocol), (const char **)&p); if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1")) return -1; av_strlcpy(c->protocol, protocol, sizeof(c->protocol)); if (config.debug) http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url); /* find the filename and the optional info string in the request */ p1 = strchr(url, '?'); if (p1) { av_strlcpy(info, p1, sizeof(info)); *p1 = '\0'; } else info[0] = '\0'; av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1); for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) { if (av_strncasecmp(p, "User-Agent:", 11) == 0) { useragent = p + 11; if (*useragent && *useragent != '\n' && av_isspace(*useragent)) useragent++; break; } p = strchr(p, '\n'); if (!p) break; p++; } redir_type = REDIR_NONE; if (av_match_ext(filename, "asx")) { redir_type = REDIR_ASX; filename[strlen(filename)-1] = 'f'; } else if (av_match_ext(filename, "asf") && (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) { /* if this isn't WMP or lookalike, return the redirector file */ redir_type = REDIR_ASF; } else if (av_match_ext(filename, "rpm,ram")) { redir_type = REDIR_RAM; strcpy(filename + strlen(filename)-2, "m"); } else if (av_match_ext(filename, "rtsp")) { redir_type = REDIR_RTSP; compute_real_filename(filename, sizeof(filename) - 1); } else if (av_match_ext(filename, "sdp")) { redir_type = REDIR_SDP; compute_real_filename(filename, sizeof(filename) - 1); } /* "redirect" request to index.html */ if (!strlen(filename)) av_strlcpy(filename, "index.html", sizeof(filename) - 1); stream = config.first_stream; while (stream) { if (!strcmp(stream->filename, filename) && validate_acl(stream, c)) break; stream = stream->next; } if (!stream) { snprintf(msg, sizeof(msg), "File '%s' not found", url); http_log("File '%s' not found\n", url); goto send_error; } c->stream = stream; memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams)); memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams)); if (stream->stream_type == STREAM_TYPE_REDIRECT) { c->http_error = 301; q = c->buffer; snprintf(q, c->buffer_size, "HTTP/1.0 301 Moved\r\n" "Location: %s\r\n" "Content-type: text/html\r\n" "\r\n" "<!DOCTYPE html>\n" "<html><head><title>Moved</title></head><body>\r\n" "You should be <a href=\"%s\">redirected</a>.\r\n" "</body></html>\r\n", stream->feed_filename, stream->feed_filename); q += strlen(q); /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; } /* If this is WMP, get the rate information */ if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) { if (modify_current_stream(c, ratebuf)) { for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) { if (c->switch_feed_streams[i] >= 0) c->switch_feed_streams[i] = -1; } } } if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE) current_bandwidth += stream->bandwidth; /* If already streaming this feed, do not let another feeder start */ if (stream->feed_opened) { snprintf(msg, sizeof(msg), "This feed is already being received."); http_log("Feed '%s' already being received\n", stream->feed_filename); goto send_error; } if (c->post == 0 && config.max_bandwidth < current_bandwidth) { c->http_error = 503; q = c->buffer; snprintf(q, c->buffer_size, "HTTP/1.0 503 Server too busy\r\n" "Content-type: text/html\r\n" "\r\n" "<!DOCTYPE html>\n" "<html><head><title>Too busy</title></head><body>\r\n" "<p>The server is too busy to serve your request at " "this time.</p>\r\n" "<p>The bandwidth being served (including your stream) " "is %"PRIu64"kbit/s, and this exceeds the limit of " "%"PRIu64"kbit/s.</p>\r\n" "</body></html>\r\n", current_bandwidth, config.max_bandwidth); q += strlen(q); /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; } if (redir_type != REDIR_NONE) { const char *hostinfo = 0; for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) { if (av_strncasecmp(p, "Host:", 5) == 0) { hostinfo = p + 5; break; } p = strchr(p, '\n'); if (!p) break; p++; } if (hostinfo) { char *eoh; char hostbuf[260]; while (av_isspace(*hostinfo)) hostinfo++; eoh = strchr(hostinfo, '\n'); if (eoh) { if (eoh[-1] == '\r') eoh--; if (eoh - hostinfo < sizeof(hostbuf) - 1) { memcpy(hostbuf, hostinfo, eoh - hostinfo); hostbuf[eoh - hostinfo] = 0; c->http_error = 200; q = c->buffer; switch(redir_type) { case REDIR_ASX: snprintf(q, c->buffer_size, "HTTP/1.0 200 ASX Follows\r\n" "Content-type: video/x-ms-asf\r\n" "\r\n" "<ASX Version=\"3\">\r\n" //"<!-- Autogenerated by ffserver -->\r\n" "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n" "</ASX>\r\n", hostbuf, filename, info); q += strlen(q); break; case REDIR_RAM: snprintf(q, c->buffer_size, "HTTP/1.0 200 RAM Follows\r\n" "Content-type: audio/x-pn-realaudio\r\n" "\r\n" "# Autogenerated by ffserver\r\n" "http://%s/%s%s\r\n", hostbuf, filename, info); q += strlen(q); break; case REDIR_ASF: snprintf(q, c->buffer_size, "HTTP/1.0 200 ASF Redirect follows\r\n" "Content-type: video/x-ms-asf\r\n" "\r\n" "[Reference]\r\n" "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info); q += strlen(q); break; case REDIR_RTSP: { char hostname[256], *p; /* extract only hostname */ av_strlcpy(hostname, hostbuf, sizeof(hostname)); p = strrchr(hostname, ':'); if (p) *p = '\0'; snprintf(q, c->buffer_size, "HTTP/1.0 200 RTSP Redirect follows\r\n" /* XXX: incorrect MIME type ? */ "Content-type: application/x-rtsp\r\n" "\r\n" "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename); q += strlen(q); } break; case REDIR_SDP: { uint8_t *sdp_data; int sdp_data_size; socklen_t len; struct sockaddr_in my_addr; snprintf(q, c->buffer_size, "HTTP/1.0 200 OK\r\n" "Content-type: application/sdp\r\n" "\r\n"); q += strlen(q); len = sizeof(my_addr); /* XXX: Should probably fail? */ if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len)) http_log("getsockname() failed\n"); /* XXX: should use a dynamic buffer */ sdp_data_size = prepare_sdp_description(stream, &sdp_data, my_addr.sin_addr); if (sdp_data_size > 0) { memcpy(q, sdp_data, sdp_data_size); q += sdp_data_size; *q = '\0'; av_freep(&sdp_data); } } break; default: abort(); break; } /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; } } } snprintf(msg, sizeof(msg), "ASX/RAM file not handled"); goto send_error; } stream->conns_served++; /* XXX: add there authenticate and IP match */ if (c->post) { /* if post, it means a feed is being sent */ if (!stream->is_feed) { /* However it might be a status report from WMP! Let us log the * data as it might come handy one day. */ const char *logline = 0; int client_id = 0; for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) { if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) { logline = p; break; } if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0) client_id = strtol(p + 18, 0, 10); p = strchr(p, '\n'); if (!p) break; p++; } if (logline) { char *eol = strchr(logline, '\n'); logline += 17; if (eol) { if (eol[-1] == '\r') eol--; http_log("%.*s\n", (int) (eol - logline), logline); c->suppress_log = 1; } } #ifdef DEBUG http_log("\nGot request:\n%s\n", c->buffer); #endif if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) { HTTPContext *wmpc; /* Now we have to find the client_id */ for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) { if (wmpc->wmp_client_id == client_id) break; } if (wmpc && modify_current_stream(wmpc, ratebuf)) wmpc->switch_pending = 1; } snprintf(msg, sizeof(msg), "POST command not handled"); c->stream = 0; goto send_error; } if (http_start_receive_data(c) < 0) { snprintf(msg, sizeof(msg), "could not open feed"); goto send_error; } c->http_error = 0; c->state = HTTPSTATE_RECEIVE_DATA; return 0; } #ifdef DEBUG if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0) http_log("\nGot request:\n%s\n", c->buffer); #endif if (c->stream->stream_type == STREAM_TYPE_STATUS) goto send_status; /* open input stream */ if (open_input_stream(c, info) < 0) { snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url); goto send_error; } /* prepare HTTP header */ c->buffer[0] = 0; av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n"); mime_type = c->stream->fmt->mime_type; if (!mime_type) mime_type = "application/x-octet-stream"; av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n"); /* for asf, we need extra headers */ if (!strcmp(c->stream->fmt->name,"asf_stream")) { /* Need to allocate a client id */ c->wmp_client_id = av_lfg_get(&random_state); av_strlcatf(c->buffer, c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id); } av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type); av_strlcatf(c->buffer, c->buffer_size, "\r\n"); q = c->buffer + strlen(c->buffer); /* prepare output buffer */ c->http_error = 0; c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; send_error: c->http_error = 404; q = c->buffer; if (!htmlencode(msg, &encoded_msg)) { http_log("Could not encode filename '%s' as HTML\n", msg); } snprintf(q, c->buffer_size, "HTTP/1.0 404 Not Found\r\n" "Content-type: text/html\r\n" "\r\n" "<!DOCTYPE html>\n" "<html>\n" "<head>\n" "<meta charset=\"UTF-8\">\n" "<title>404 Not Found</title>\n" "</head>\n" "<body>%s</body>\n" "</html>\n", encoded_msg? encoded_msg : "File not found"); q += strlen(q); /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; av_freep(&encoded_msg); return 0; send_status: compute_status(c); /* horrible: we use this value to avoid * going to the send data state */ c->http_error = 200; c->state = HTTPSTATE_SEND_HEADER; return 0; } static void fmt_bytecount(AVIOContext *pb, int64_t count) { static const char suffix[] = " kMGTP"; const char *s; for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++); avio_printf(pb, "%"PRId64"%c", count, *s); } static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream) { int i, stream_no; const char *type = "unknown"; char parameters[64]; LayeredAVStream *st; AVCodec *codec; stream_no = stream->nb_streams; avio_printf(pb, "<table><tr><th>Stream<th>" "type<th>kbit/s<th>codec<th>" "Parameters\n"); for (i = 0; i < stream_no; i++) { st = stream->streams[i]; codec = avcodec_find_encoder(st->codecpar->codec_id); parameters[0] = 0; switch(st->codecpar->codec_type) { case AVMEDIA_TYPE_AUDIO: type = "audio"; snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codecpar->channels, st->codecpar->sample_rate); break; case AVMEDIA_TYPE_VIDEO: type = "video"; snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codecpar->width, st->codecpar->height, st->codec->qmin, st->codec->qmax, st->time_base.den / st->time_base.num); break; default: abort(); } avio_printf(pb, "<tr><td>%d<td>%s<td>%"PRId64 "<td>%s<td>%s\n", i, type, (int64_t)st->codecpar->bit_rate/1000, codec ? codec->name : "", parameters); } avio_printf(pb, "</table>\n"); } static void clean_html(char *clean, int clean_len, char *dirty) { int i, o; for (o = i = 0; o+10 < clean_len && dirty[i];) { int len = strspn(dirty+i, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*(),?/ :;%"); if (len) { if (o + len >= clean_len) break; memcpy(clean + o, dirty + i, len); i += len; o += len; } else { int c = dirty[i++]; switch (c) { case '&': av_strlcat(clean+o, "&amp;" , clean_len - o); break; case '<': av_strlcat(clean+o, "&lt;" , clean_len - o); break; case '>': av_strlcat(clean+o, "&gt;" , clean_len - o); break; case '\'': av_strlcat(clean+o, "&apos;" , clean_len - o); break; case '\"': av_strlcat(clean+o, "&quot;" , clean_len - o); break; default: av_strlcat(clean+o, "&#9785;", clean_len - o); break; } o += strlen(clean+o); } } clean[o] = 0; } static void compute_status(HTTPContext *c) { HTTPContext *c1; FFServerStream *stream; char *p; time_t ti; int i, len; AVIOContext *pb; if (avio_open_dyn_buf(&pb) < 0) { /* XXX: return an error ? */ c->buffer_ptr = c->buffer; c->buffer_end = c->buffer; return; } avio_printf(pb, "HTTP/1.0 200 OK\r\n"); avio_printf(pb, "Content-type: text/html\r\n"); avio_printf(pb, "Pragma: no-cache\r\n"); avio_printf(pb, "\r\n"); avio_printf(pb, "<!DOCTYPE html>\n"); avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name); if (c->stream->feed_filename[0]) avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename); avio_printf(pb, "</head>\n<body>"); avio_printf(pb, "<h1>%s Status</h1>\n", program_name); /* format status */ avio_printf(pb, "<h2>Available Streams</h2>\n"); avio_printf(pb, "<table>\n"); avio_printf(pb, "<tr><th>Path<th>Served<br>Conns<th><br>bytes<th>Format<th>Bit rate<br>kbit/s<th>Video<br>kbit/s<th><br>Codec<th>Audio<br>kbit/s<th><br>Codec<th>Feed\n"); stream = config.first_stream; while (stream) { char sfilename[1024]; char *eosf; if (stream->feed == stream) { stream = stream->next; continue; } av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10); eosf = sfilename + strlen(sfilename); if (eosf - sfilename >= 4) { if (strcmp(eosf - 4, ".asf") == 0) strcpy(eosf - 4, ".asx"); else if (strcmp(eosf - 3, ".rm") == 0) strcpy(eosf - 3, ".ram"); else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) { /* generate a sample RTSP director if * unicast. Generate an SDP redirector if * multicast */ eosf = strrchr(sfilename, '.'); if (!eosf) eosf = sfilename + strlen(sfilename); if (stream->is_multicast) strcpy(eosf, ".sdp"); else strcpy(eosf, ".rtsp"); } } avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ", sfilename, stream->filename); avio_printf(pb, "<td> %d <td> ", stream->conns_served); // TODO: Investigate if we can make http bitexact so it always produces the same count of bytes if (!config.bitexact) fmt_bytecount(pb, stream->bytes_served); switch(stream->stream_type) { case STREAM_TYPE_LIVE: { int audio_bit_rate = 0; int video_bit_rate = 0; const char *audio_codec_name = ""; const char *video_codec_name = ""; const char *audio_codec_name_extra = ""; const char *video_codec_name_extra = ""; for(i=0;i<stream->nb_streams;i++) { LayeredAVStream *st = stream->streams[i]; AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id); switch(st->codecpar->codec_type) { case AVMEDIA_TYPE_AUDIO: audio_bit_rate += st->codecpar->bit_rate; if (codec) { if (*audio_codec_name) audio_codec_name_extra = "..."; audio_codec_name = codec->name; } break; case AVMEDIA_TYPE_VIDEO: video_bit_rate += st->codecpar->bit_rate; if (codec) { if (*video_codec_name) video_codec_name_extra = "..."; video_codec_name = codec->name; } break; case AVMEDIA_TYPE_DATA: video_bit_rate += st->codecpar->bit_rate; break; default: abort(); } } avio_printf(pb, "<td> %s <td> %d <td> %d <td> %s %s <td> " "%d <td> %s %s", stream->fmt->name, stream->bandwidth, video_bit_rate / 1000, video_codec_name, video_codec_name_extra, audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra); if (stream->feed) avio_printf(pb, "<td>%s", stream->feed->filename); else avio_printf(pb, "<td>%s", stream->feed_filename); avio_printf(pb, "\n"); } break; default: avio_printf(pb, "<td> - <td> - " "<td> - <td><td> - <td>\n"); break; } stream = stream->next; } avio_printf(pb, "</table>\n"); stream = config.first_stream; while (stream) { if (stream->feed != stream) { stream = stream->next; continue; } avio_printf(pb, "<h2>Feed %s</h2>", stream->filename); if (stream->pid) { avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid); #if defined(linux) { FILE *pid_stat; char ps_cmd[64]; /* This is somewhat linux specific I guess */ snprintf(ps_cmd, sizeof(ps_cmd), "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"", (int64_t) stream->pid); pid_stat = popen(ps_cmd, "r"); if (pid_stat) { char cpuperc[10]; char cpuused[64]; if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) { avio_printf(pb, "Currently using %s%% of the cpu. " "Total time used %s.\n", cpuperc, cpuused); } fclose(pid_stat); } } #endif avio_printf(pb, "<p>"); } print_stream_params(pb, stream); stream = stream->next; } /* connection status */ avio_printf(pb, "<h2>Connection Status</h2>\n"); avio_printf(pb, "Number of connections: %d / %d<br>\n", nb_connections, config.nb_max_connections); avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n", current_bandwidth, config.max_bandwidth); avio_printf(pb, "<table>\n"); avio_printf(pb, "<tr><th>#<th>File<th>IP<th>URL<th>Proto<th>State<th>Target " "bit/s<th>Actual bit/s<th>Bytes transferred\n"); c1 = first_http_ctx; i = 0; while (c1) { int bitrate; int j; bitrate = 0; if (c1->stream) { for (j = 0; j < c1->stream->nb_streams; j++) { if (!c1->stream->feed) bitrate += c1->stream->streams[j]->codecpar->bit_rate; else if (c1->feed_streams[j] >= 0) bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate; } } i++; p = inet_ntoa(c1->from_addr.sin_addr); clean_html(c1->clean_url, sizeof(c1->clean_url), c1->url); avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td>%s" "<td>", i, c1->stream ? c1->stream->filename : "", c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p, c1->clean_url, c1->protocol, http_state[c1->state]); fmt_bytecount(pb, bitrate); avio_printf(pb, "<td>"); fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8); avio_printf(pb, "<td>"); fmt_bytecount(pb, c1->data_count); avio_printf(pb, "\n"); c1 = c1->next; } avio_printf(pb, "</table>\n"); if (!config.bitexact) { /* date */ ti = time(NULL); p = ctime(&ti); avio_printf(pb, "<hr>Generated at %s", p); } avio_printf(pb, "</body>\n</html>\n"); len = avio_close_dyn_buf(pb, &c->pb_buffer); c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; } static int open_input_stream(HTTPContext *c, const char *info) { char buf[128]; char input_filename[1024]; AVFormatContext *s = NULL; int buf_size, i, ret; int64_t stream_pos; /* find file name */ if (c->stream->feed) { strcpy(input_filename, c->stream->feed->feed_filename); buf_size = FFM_PACKET_SIZE; /* compute position (absolute time) */ if (av_find_info_tag(buf, sizeof(buf), "date", info)) { if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) { http_log("Invalid date specification '%s' for stream\n", buf); return ret; } } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) { int prebuffer = strtol(buf, 0, 10); stream_pos = av_gettime() - prebuffer * (int64_t)1000000; } else stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000; } else { strcpy(input_filename, c->stream->feed_filename); buf_size = 0; /* compute position (relative time) */ if (av_find_info_tag(buf, sizeof(buf), "date", info)) { if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) { http_log("Invalid date specification '%s' for stream\n", buf); return ret; } } else stream_pos = 0; } if (!input_filename[0]) { http_log("No filename was specified for stream\n"); return AVERROR(EINVAL); } /* open stream */ ret = avformat_open_input(&s, input_filename, c->stream->ifmt, &c->stream->in_opts); if (ret < 0) { http_log("Could not open input '%s': %s\n", input_filename, av_err2str(ret)); return ret; } /* set buffer size */ if (buf_size > 0) { ret = ffio_set_buf_size(s->pb, buf_size); if (ret < 0) { http_log("Failed to set buffer size\n"); return ret; } } s->flags |= AVFMT_FLAG_GENPTS; c->fmt_in = s; if (strcmp(s->iformat->name, "ffm") && (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) { http_log("Could not find stream info for input '%s'\n", input_filename); avformat_close_input(&s); return ret; } /* choose stream as clock source (we favor the video stream if * present) for packet sending */ c->pts_stream_index = 0; for(i=0;i<c->stream->nb_streams;i++) { if (c->pts_stream_index == 0 && c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { c->pts_stream_index = i; } } if (c->fmt_in->iformat->read_seek) av_seek_frame(c->fmt_in, -1, stream_pos, 0); /* set the start time (needed for maxtime and RTP packet timing) */ c->start_time = cur_time; c->first_pts = AV_NOPTS_VALUE; return 0; } /* return the server clock (in us) */ static int64_t get_server_clock(HTTPContext *c) { /* compute current pts value from system time */ return (cur_time - c->start_time) * 1000; } /* return the estimated time (in us) at which the current packet must be sent */ static int64_t get_packet_send_clock(HTTPContext *c) { int bytes_left, bytes_sent, frame_bytes; frame_bytes = c->cur_frame_bytes; if (frame_bytes <= 0) return c->cur_pts; bytes_left = c->buffer_end - c->buffer_ptr; bytes_sent = frame_bytes - bytes_left; return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes; } static int http_prepare_data(HTTPContext *c) { int i, len, ret; AVFormatContext *ctx; av_freep(&c->pb_buffer); switch(c->state) { case HTTPSTATE_SEND_DATA_HEADER: ctx = avformat_alloc_context(); if (!ctx) return AVERROR(ENOMEM); c->pfmt_ctx = ctx; av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0); for(i=0;i<c->stream->nb_streams;i++) { LayeredAVStream *src; AVStream *st = avformat_new_stream(c->pfmt_ctx, NULL); if (!st) return AVERROR(ENOMEM); /* if file or feed, then just take streams from FFServerStream * struct */ if (!c->stream->feed || c->stream->feed == c->stream) src = c->stream->streams[i]; else src = c->stream->feed->streams[c->stream->feed_streams[i]]; unlayer_stream(c->pfmt_ctx->streams[i], src); //TODO we no longer copy st->internal, does this matter? av_assert0(!c->pfmt_ctx->streams[i]->priv_data); if (src->codec->flags & AV_CODEC_FLAG_BITEXACT) c->pfmt_ctx->flags |= AVFMT_FLAG_BITEXACT; } /* set output format parameters */ c->pfmt_ctx->oformat = c->stream->fmt; av_assert0(c->pfmt_ctx->nb_streams == c->stream->nb_streams); c->got_key_frame = 0; /* prepare header and save header data in a stream */ if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) { /* XXX: potential leak */ return -1; } c->pfmt_ctx->pb->seekable = 0; /* * HACK to avoid MPEG-PS muxer to spit many underflow errors * Default value from FFmpeg * Try to set it using configuration option */ c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE); if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) { http_log("Error writing output header for stream '%s': %s\n", c->stream->filename, av_err2str(ret)); return ret; } av_dict_free(&c->pfmt_ctx->metadata); len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer); c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; c->state = HTTPSTATE_SEND_DATA; c->last_packet_sent = 0; break; case HTTPSTATE_SEND_DATA: /* find a new packet */ /* read a packet from the input stream */ if (c->stream->feed) ffm_set_write_index(c->fmt_in, c->stream->feed->feed_write_index, c->stream->feed->feed_size); if (c->stream->max_time && c->stream->max_time + c->start_time - cur_time < 0) /* We have timed out */ c->state = HTTPSTATE_SEND_DATA_TRAILER; else { AVPacket pkt; redo: ret = av_read_frame(c->fmt_in, &pkt); if (ret < 0) { if (c->stream->feed) { /* if coming from feed, it means we reached the end of the * ffm file, so must wait for more data */ c->state = HTTPSTATE_WAIT_FEED; return 1; /* state changed */ } if (ret == AVERROR(EAGAIN)) { /* input not ready, come back later */ return 0; } if (c->stream->loop) { avformat_close_input(&c->fmt_in); if (open_input_stream(c, "") < 0) goto no_loop; goto redo; } else { no_loop: /* must send trailer now because EOF or error */ c->state = HTTPSTATE_SEND_DATA_TRAILER; } } else { int source_index = pkt.stream_index; /* update first pts if needed */ if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) { c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q); c->start_time = cur_time; } /* send it to the appropriate stream */ if (c->stream->feed) { /* if coming from a feed, select the right stream */ if (c->switch_pending) { c->switch_pending = 0; for(i=0;i<c->stream->nb_streams;i++) { if (c->switch_feed_streams[i] == pkt.stream_index) if (pkt.flags & AV_PKT_FLAG_KEY) c->switch_feed_streams[i] = -1; if (c->switch_feed_streams[i] >= 0) c->switch_pending = 1; } } for(i=0;i<c->stream->nb_streams;i++) { if (c->stream->feed_streams[i] == pkt.stream_index) { AVStream *st = c->fmt_in->streams[source_index]; pkt.stream_index = i; if (pkt.flags & AV_PKT_FLAG_KEY && (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || c->stream->nb_streams == 1)) c->got_key_frame = 1; if (!c->stream->send_on_key || c->got_key_frame) goto send_it; } } } else { AVStream *ist, *ost; send_it: ist = c->fmt_in->streams[source_index]; /* specific handling for RTP: we use several * output streams (one for each RTP connection). * XXX: need more abstract handling */ if (c->is_packetized) { /* compute send time and duration */ if (pkt.dts != AV_NOPTS_VALUE) { c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q); c->cur_pts -= c->first_pts; } c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q); /* find RTP context */ c->packet_stream_index = pkt.stream_index; ctx = c->rtp_ctx[c->packet_stream_index]; if(!ctx) { av_packet_unref(&pkt); break; } /* only one stream per RTP connection */ pkt.stream_index = 0; } else { ctx = c->pfmt_ctx; /* Fudge here */ } if (c->is_packetized) { int max_packet_size; if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) max_packet_size = RTSP_TCP_MAX_PACKET_SIZE; else max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size; ret = ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size); } else ret = avio_open_dyn_buf(&ctx->pb); if (ret < 0) { /* XXX: potential leak */ return -1; } ost = ctx->streams[pkt.stream_index]; ctx->pb->seekable = 0; if (pkt.dts != AV_NOPTS_VALUE) pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base); if (pkt.pts != AV_NOPTS_VALUE) pkt.pts = av_rescale_q(pkt.pts, ist->time_base, ost->time_base); pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base); if ((ret = av_write_frame(ctx, &pkt)) < 0) { http_log("Error writing frame to output for stream '%s': %s\n", c->stream->filename, av_err2str(ret)); c->state = HTTPSTATE_SEND_DATA_TRAILER; } av_freep(&c->pb_buffer); len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer); ctx->pb = NULL; c->cur_frame_bytes = len; c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; if (len == 0) { av_packet_unref(&pkt); goto redo; } } av_packet_unref(&pkt); } } break; default: case HTTPSTATE_SEND_DATA_TRAILER: /* last packet test ? */ if (c->last_packet_sent || c->is_packetized) return -1; ctx = c->pfmt_ctx; /* prepare header */ if (avio_open_dyn_buf(&ctx->pb) < 0) { /* XXX: potential leak */ return -1; } c->pfmt_ctx->pb->seekable = 0; av_write_trailer(ctx); len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer); c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; c->last_packet_sent = 1; break; } return 0; } /* should convert the format at the same time */ /* send data starting at c->buffer_ptr to the output connection * (either UDP or TCP) */ static int http_send_data(HTTPContext *c) { int len, ret; for(;;) { if (c->buffer_ptr >= c->buffer_end) { ret = http_prepare_data(c); if (ret < 0) return -1; else if (ret) /* state change requested */ break; } else { if (c->is_packetized) { /* RTP data output */ len = c->buffer_end - c->buffer_ptr; if (len < 4) { /* fail safe - should never happen */ fail1: c->buffer_ptr = c->buffer_end; return 0; } len = (c->buffer_ptr[0] << 24) | (c->buffer_ptr[1] << 16) | (c->buffer_ptr[2] << 8) | (c->buffer_ptr[3]); if (len > (c->buffer_end - c->buffer_ptr)) goto fail1; if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) { /* nothing to send yet: we can wait */ return 0; } c->data_count += len; update_datarate(&c->datarate, c->data_count); if (c->stream) c->stream->bytes_served += len; if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) { /* RTP packets are sent inside the RTSP TCP connection */ AVIOContext *pb; int interleaved_index, size; uint8_t header[4]; HTTPContext *rtsp_c; rtsp_c = c->rtsp_c; /* if no RTSP connection left, error */ if (!rtsp_c) return -1; /* if already sending something, then wait. */ if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST) break; if (avio_open_dyn_buf(&pb) < 0) goto fail1; interleaved_index = c->packet_stream_index * 2; /* RTCP packets are sent at odd indexes */ if (c->buffer_ptr[1] == 200) interleaved_index++; /* write RTSP TCP header */ header[0] = '$'; header[1] = interleaved_index; header[2] = len >> 8; header[3] = len; avio_write(pb, header, 4); /* write RTP packet data */ c->buffer_ptr += 4; avio_write(pb, c->buffer_ptr, len); size = avio_close_dyn_buf(pb, &c->packet_buffer); /* prepare asynchronous TCP sending */ rtsp_c->packet_buffer_ptr = c->packet_buffer; rtsp_c->packet_buffer_end = c->packet_buffer + size; c->buffer_ptr += len; /* send everything we can NOW */ len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr, rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0); if (len > 0) rtsp_c->packet_buffer_ptr += len; if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) { /* if we could not send all the data, we will * send it later, so a new state is needed to * "lock" the RTSP TCP connection */ rtsp_c->state = RTSPSTATE_SEND_PACKET; break; } else /* all data has been sent */ av_freep(&c->packet_buffer); } else { /* send RTP packet directly in UDP */ c->buffer_ptr += 4; ffurl_write(c->rtp_handles[c->packet_stream_index], c->buffer_ptr, len); c->buffer_ptr += len; /* here we continue as we can send several packets * per 10 ms slot */ } } else { /* TCP data output */ len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) /* error : close connection */ return -1; else return 0; } c->buffer_ptr += len; c->data_count += len; update_datarate(&c->datarate, c->data_count); if (c->stream) c->stream->bytes_served += len; break; } } } /* for(;;) */ return 0; } static int http_start_receive_data(HTTPContext *c) { int fd; int ret; int64_t ret64; if (c->stream->feed_opened) { http_log("Stream feed '%s' was not opened\n", c->stream->feed_filename); return AVERROR(EINVAL); } /* Don't permit writing to this one */ if (c->stream->readonly) { http_log("Cannot write to read-only file '%s'\n", c->stream->feed_filename); return AVERROR(EINVAL); } /* open feed */ fd = open(c->stream->feed_filename, O_RDWR); if (fd < 0) { ret = AVERROR(errno); http_log("Could not open feed file '%s': %s\n", c->stream->feed_filename, strerror(errno)); return ret; } c->feed_fd = fd; if (c->stream->truncate) { /* truncate feed file */ ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE); http_log("Truncating feed file '%s'\n", c->stream->feed_filename); if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) { ret = AVERROR(errno); http_log("Error truncating feed file '%s': %s\n", c->stream->feed_filename, strerror(errno)); return ret; } } else { ret64 = ffm_read_write_index(fd); if (ret64 < 0) { http_log("Error reading write index from feed file '%s': %s\n", c->stream->feed_filename, strerror(errno)); return ret64; } c->stream->feed_write_index = ret64; } c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE); c->stream->feed_size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); /* init buffer input */ c->buffer_ptr = c->buffer; c->buffer_end = c->buffer + FFM_PACKET_SIZE; c->stream->feed_opened = 1; c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked"); return 0; } static int http_receive_data(HTTPContext *c) { HTTPContext *c1; int len, loop_run = 0; while (c->chunked_encoding && !c->chunk_size && c->buffer_end > c->buffer_ptr) { /* read chunk header, if present */ len = recv(c->fd, c->buffer_ptr, 1, 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) /* error : close connection */ goto fail; return 0; } else if (len == 0) { /* end of connection : close it */ goto fail; } else if (c->buffer_ptr - c->buffer >= 2 && !memcmp(c->buffer_ptr - 1, "\r\n", 2)) { c->chunk_size = strtol(c->buffer, 0, 16); if (c->chunk_size == 0) // end of stream goto fail; c->buffer_ptr = c->buffer; break; } else if (++loop_run > 10) /* no chunk header, abort */ goto fail; else c->buffer_ptr++; } if (c->buffer_end > c->buffer_ptr) { len = recv(c->fd, c->buffer_ptr, FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0); if (len < 0) { if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) /* error : close connection */ goto fail; } else if (len == 0) /* end of connection : close it */ goto fail; else { c->chunk_size -= len; c->buffer_ptr += len; c->data_count += len; update_datarate(&c->datarate, c->data_count); } } if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) { if (c->buffer[0] != 'f' || c->buffer[1] != 'm') { http_log("Feed stream has become desynchronized -- disconnecting\n"); goto fail; } } if (c->buffer_ptr >= c->buffer_end) { FFServerStream *feed = c->stream; /* a packet has been received : write it in the store, except * if header */ if (c->data_count > FFM_PACKET_SIZE) { /* XXX: use llseek or url_seek * XXX: Should probably fail? */ if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1) http_log("Seek to %"PRId64" failed\n", feed->feed_write_index); if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) { http_log("Error writing to feed file: %s\n", strerror(errno)); goto fail; } feed->feed_write_index += FFM_PACKET_SIZE; /* update file size */ if (feed->feed_write_index > c->stream->feed_size) feed->feed_size = feed->feed_write_index; /* handle wrap around if max file size reached */ if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size) feed->feed_write_index = FFM_PACKET_SIZE; /* write index */ if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) { http_log("Error writing index to feed file: %s\n", strerror(errno)); goto fail; } /* wake up any waiting connections */ for(c1 = first_http_ctx; c1; c1 = c1->next) { if (c1->state == HTTPSTATE_WAIT_FEED && c1->stream->feed == c->stream->feed) c1->state = HTTPSTATE_SEND_DATA; } } else { /* We have a header in our hands that contains useful data */ AVFormatContext *s = avformat_alloc_context(); AVIOContext *pb; AVInputFormat *fmt_in; int i; if (!s) goto fail; /* use feed output format name to find corresponding input format */ fmt_in = av_find_input_format(feed->fmt->name); if (!fmt_in) goto fail; pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer, 0, NULL, NULL, NULL, NULL); if (!pb) goto fail; pb->seekable = 0; s->pb = pb; if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) { av_freep(&pb); goto fail; } /* Now we have the actual streams */ if (s->nb_streams != feed->nb_streams) { avformat_close_input(&s); av_freep(&pb); http_log("Feed '%s' stream number does not match registered feed\n", c->stream->feed_filename); goto fail; } for (i = 0; i < s->nb_streams; i++) { LayeredAVStream *fst = feed->streams[i]; AVStream *st = s->streams[i]; avcodec_parameters_to_context(fst->codec, st->codecpar); avcodec_parameters_from_context(fst->codecpar, fst->codec); } avformat_close_input(&s); av_freep(&pb); } c->buffer_ptr = c->buffer; } return 0; fail: c->stream->feed_opened = 0; close(c->feed_fd); /* wake up any waiting connections to stop waiting for feed */ for(c1 = first_http_ctx; c1; c1 = c1->next) { if (c1->state == HTTPSTATE_WAIT_FEED && c1->stream->feed == c->stream->feed) c1->state = HTTPSTATE_SEND_DATA_TRAILER; } return -1; } /********************************************************************/ /* RTSP handling */ static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number) { const char *str; time_t ti; struct tm *tm; char buf2[32]; str = RTSP_STATUS_CODE2STRING(error_number); if (!str) str = "Unknown Error"; avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str); avio_printf(c->pb, "CSeq: %d\r\n", c->seq); /* output GMT time */ ti = time(NULL); tm = gmtime(&ti); strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm); avio_printf(c->pb, "Date: %s GMT\r\n", buf2); } static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number) { rtsp_reply_header(c, error_number); avio_printf(c->pb, "\r\n"); } static int rtsp_parse_request(HTTPContext *c) { const char *p, *p1, *p2; char cmd[32]; char url[1024]; char protocol[32]; char line[1024]; int len; RTSPMessageHeader header1 = { 0 }, *header = &header1; c->buffer_ptr[0] = '\0'; p = c->buffer; get_word(cmd, sizeof(cmd), &p); get_word(url, sizeof(url), &p); get_word(protocol, sizeof(protocol), &p); av_strlcpy(c->method, cmd, sizeof(c->method)); av_strlcpy(c->url, url, sizeof(c->url)); av_strlcpy(c->protocol, protocol, sizeof(c->protocol)); if (avio_open_dyn_buf(&c->pb) < 0) { /* XXX: cannot do more */ c->pb = NULL; /* safety */ return -1; } /* check version name */ if (strcmp(protocol, "RTSP/1.0")) { rtsp_reply_error(c, RTSP_STATUS_VERSION); goto the_end; } /* parse each header line */ /* skip to next line */ while (*p != '\n' && *p != '\0') p++; if (*p == '\n') p++; while (*p != '\0') { p1 = memchr(p, '\n', (char *)c->buffer_ptr - p); if (!p1) break; p2 = p1; if (p2 > p && p2[-1] == '\r') p2--; /* skip empty line */ if (p2 == p) break; len = p2 - p; if (len > sizeof(line) - 1) len = sizeof(line) - 1; memcpy(line, p, len); line[len] = '\0'; ff_rtsp_parse_line(NULL, header, line, NULL, NULL); p = p1 + 1; } /* handle sequence number */ c->seq = header->seq; if (!strcmp(cmd, "DESCRIBE")) rtsp_cmd_describe(c, url); else if (!strcmp(cmd, "OPTIONS")) rtsp_cmd_options(c, url); else if (!strcmp(cmd, "SETUP")) rtsp_cmd_setup(c, url, header); else if (!strcmp(cmd, "PLAY")) rtsp_cmd_play(c, url, header); else if (!strcmp(cmd, "PAUSE")) rtsp_cmd_interrupt(c, url, header, 1); else if (!strcmp(cmd, "TEARDOWN")) rtsp_cmd_interrupt(c, url, header, 0); else rtsp_reply_error(c, RTSP_STATUS_METHOD); the_end: len = avio_close_dyn_buf(c->pb, &c->pb_buffer); c->pb = NULL; /* safety */ if (len < 0) /* XXX: cannot do more */ return -1; c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; c->state = RTSPSTATE_SEND_REPLY; return 0; } static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer, struct in_addr my_ip) { AVFormatContext *avc; AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL); AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0); int i; *pbuffer = NULL; avc = avformat_alloc_context(); if (!avc || !rtp_format) return -1; avc->oformat = rtp_format; av_dict_set(&avc->metadata, "title", entry ? entry->value : "No Title", 0); if (stream->is_multicast) { snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d", inet_ntoa(stream->multicast_ip), stream->multicast_port, stream->multicast_ttl); } else snprintf(avc->filename, 1024, "rtp://0.0.0.0"); for(i = 0; i < stream->nb_streams; i++) { AVStream *st = avformat_new_stream(avc, NULL); if (!st) goto sdp_done; avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec); unlayer_stream(st, stream->streams[i]); } #define PBUFFER_SIZE 2048 *pbuffer = av_mallocz(PBUFFER_SIZE); if (!*pbuffer) goto sdp_done; av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE); sdp_done: av_freep(&avc->streams); av_dict_free(&avc->metadata); av_free(avc); return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM); } static void rtsp_cmd_options(HTTPContext *c, const char *url) { /* rtsp_reply_header(c, RTSP_STATUS_OK); */ avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK"); avio_printf(c->pb, "CSeq: %d\r\n", c->seq); avio_printf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE"); avio_printf(c->pb, "\r\n"); } static void rtsp_cmd_describe(HTTPContext *c, const char *url) { FFServerStream *stream; char path1[1024]; const char *path; uint8_t *content; int content_length; socklen_t len; struct sockaddr_in my_addr; /* find which URL is asked */ av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; for(stream = config.first_stream; stream; stream = stream->next) { if (!stream->is_feed && stream->fmt && !strcmp(stream->fmt->name, "rtp") && !strcmp(path, stream->filename)) { goto found; } } /* no stream found */ rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND); return; found: /* prepare the media description in SDP format */ /* get the host IP */ len = sizeof(my_addr); getsockname(c->fd, (struct sockaddr *)&my_addr, &len); content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr); if (content_length < 0) { rtsp_reply_error(c, RTSP_STATUS_INTERNAL); return; } rtsp_reply_header(c, RTSP_STATUS_OK); avio_printf(c->pb, "Content-Base: %s/\r\n", url); avio_printf(c->pb, "Content-Type: application/sdp\r\n"); avio_printf(c->pb, "Content-Length: %d\r\n", content_length); avio_printf(c->pb, "\r\n"); avio_write(c->pb, content, content_length); av_free(content); } static HTTPContext *find_rtp_session(const char *session_id) { HTTPContext *c; if (session_id[0] == '\0') return NULL; for(c = first_http_ctx; c; c = c->next) { if (!strcmp(c->session_id, session_id)) return c; } return NULL; } static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport) { RTSPTransportField *th; int i; for(i=0;i<h->nb_transports;i++) { th = &h->transports[i]; if (th->lower_transport == lower_transport) return th; } return NULL; } static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPMessageHeader *h) { FFServerStream *stream; int stream_index, rtp_port, rtcp_port; char buf[1024]; char path1[1024]; const char *path; HTTPContext *rtp_c; RTSPTransportField *th; struct sockaddr_in dest_addr; RTSPActionServerSetup setup; /* find which URL is asked */ av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; /* now check each stream */ for(stream = config.first_stream; stream; stream = stream->next) { if (stream->is_feed || !stream->fmt || strcmp(stream->fmt->name, "rtp")) { continue; } /* accept aggregate filenames only if single stream */ if (!strcmp(path, stream->filename)) { if (stream->nb_streams != 1) { rtsp_reply_error(c, RTSP_STATUS_AGGREGATE); return; } stream_index = 0; goto found; } for(stream_index = 0; stream_index < stream->nb_streams; stream_index++) { snprintf(buf, sizeof(buf), "%s/streamid=%d", stream->filename, stream_index); if (!strcmp(path, buf)) goto found; } } /* no stream found */ rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */ return; found: /* generate session id if needed */ if (h->session_id[0] == '\0') { unsigned random0 = av_lfg_get(&random_state); unsigned random1 = av_lfg_get(&random_state); snprintf(h->session_id, sizeof(h->session_id), "%08x%08x", random0, random1); } /* find RTP session, and create it if none found */ rtp_c = find_rtp_session(h->session_id); if (!rtp_c) { /* always prefer UDP */ th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP); if (!th) { th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP); if (!th) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } } rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id, th->lower_transport); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH); return; } /* open input stream */ if (open_input_stream(rtp_c, "") < 0) { rtsp_reply_error(c, RTSP_STATUS_INTERNAL); return; } } /* test if stream is OK (test needed because several SETUP needs * to be done for a given file) */ if (rtp_c->stream != stream) { rtsp_reply_error(c, RTSP_STATUS_SERVICE); return; } /* test if stream is already set up */ if (rtp_c->rtp_ctx[stream_index]) { rtsp_reply_error(c, RTSP_STATUS_STATE); return; } /* check transport */ th = find_transport(h, rtp_c->rtp_protocol); if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP && th->client_port_min <= 0)) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } /* setup default options */ setup.transport_option[0] = '\0'; dest_addr = rtp_c->from_addr; dest_addr.sin_port = htons(th->client_port_min); /* setup stream */ if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id); switch(rtp_c->rtp_protocol) { case RTSP_LOWER_TRANSPORT_UDP: rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]); rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]); avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;" "client_port=%d-%d;server_port=%d-%d", th->client_port_min, th->client_port_max, rtp_port, rtcp_port); break; case RTSP_LOWER_TRANSPORT_TCP: avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d", stream_index * 2, stream_index * 2 + 1); break; default: break; } if (setup.transport_option[0] != '\0') avio_printf(c->pb, ";%s", setup.transport_option); avio_printf(c->pb, "\r\n"); avio_printf(c->pb, "\r\n"); } /** * find an RTP connection by using the session ID. Check consistency * with filename */ static HTTPContext *find_rtp_session_with_url(const char *url, const char *session_id) { HTTPContext *rtp_c; char path1[1024]; const char *path; char buf[1024]; int s, len; rtp_c = find_rtp_session(session_id); if (!rtp_c) return NULL; /* find which URL is asked */ av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; if(!strcmp(path, rtp_c->stream->filename)) return rtp_c; for(s=0; s<rtp_c->stream->nb_streams; ++s) { snprintf(buf, sizeof(buf), "%s/streamid=%d", rtp_c->stream->filename, s); if(!strncmp(path, buf, sizeof(buf))) /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE * if nb_streams>1? */ return rtp_c; } len = strlen(path); if (len > 0 && path[len - 1] == '/' && !strncmp(path, rtp_c->stream->filename, len - 1)) return rtp_c; return NULL; } static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h) { HTTPContext *rtp_c; rtp_c = find_rtp_session_with_url(url, h->session_id); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_SESSION); return; } if (rtp_c->state != HTTPSTATE_SEND_DATA && rtp_c->state != HTTPSTATE_WAIT_FEED && rtp_c->state != HTTPSTATE_READY) { rtsp_reply_error(c, RTSP_STATUS_STATE); return; } rtp_c->state = HTTPSTATE_SEND_DATA; /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id); avio_printf(c->pb, "\r\n"); } static void rtsp_cmd_interrupt(HTTPContext *c, const char *url, RTSPMessageHeader *h, int pause_only) { HTTPContext *rtp_c; rtp_c = find_rtp_session_with_url(url, h->session_id); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_SESSION); return; } if (pause_only) { if (rtp_c->state != HTTPSTATE_SEND_DATA && rtp_c->state != HTTPSTATE_WAIT_FEED) { rtsp_reply_error(c, RTSP_STATUS_STATE); return; } rtp_c->state = HTTPSTATE_READY; rtp_c->first_pts = AV_NOPTS_VALUE; } /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id); avio_printf(c->pb, "\r\n"); if (!pause_only) close_connection(rtp_c); } /********************************************************************/ /* RTP handling */ static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr, FFServerStream *stream, const char *session_id, enum RTSPLowerTransport rtp_protocol) { HTTPContext *c = NULL; const char *proto_str; /* XXX: should output a warning page when coming * close to the connection limit */ if (nb_connections >= config.nb_max_connections) goto fail; /* add a new connection */ c = av_mallocz(sizeof(HTTPContext)); if (!c) goto fail; c->fd = -1; c->poll_entry = NULL; c->from_addr = *from_addr; c->buffer_size = IOBUFFER_INIT_SIZE; c->buffer = av_malloc(c->buffer_size); if (!c->buffer) goto fail; nb_connections++; c->stream = stream; av_strlcpy(c->session_id, session_id, sizeof(c->session_id)); c->state = HTTPSTATE_READY; c->is_packetized = 1; c->rtp_protocol = rtp_protocol; /* protocol is shown in statistics */ switch(c->rtp_protocol) { case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: proto_str = "MCAST"; break; case RTSP_LOWER_TRANSPORT_UDP: proto_str = "UDP"; break; case RTSP_LOWER_TRANSPORT_TCP: proto_str = "TCP"; break; default: proto_str = "???"; break; } av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol)); av_strlcat(c->protocol, proto_str, sizeof(c->protocol)); current_bandwidth += stream->bandwidth; c->next = first_http_ctx; first_http_ctx = c; return c; fail: if (c) { av_freep(&c->buffer); av_free(c); } return NULL; } /** * add a new RTP stream in an RTP connection (used in RTSP SETUP * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is * used. */ static int rtp_new_av_stream(HTTPContext *c, int stream_index, struct sockaddr_in *dest_addr, HTTPContext *rtsp_c) { AVFormatContext *ctx; AVStream *st; char *ipaddr; URLContext *h = NULL; uint8_t *dummy_buf; int max_packet_size; void *st_internal; /* now we can open the relevant output stream */ ctx = avformat_alloc_context(); if (!ctx) return -1; ctx->oformat = av_guess_format("rtp", NULL, NULL); st = avformat_new_stream(ctx, NULL); if (!st) goto fail; st_internal = st->internal; if (!c->stream->feed || c->stream->feed == c->stream) unlayer_stream(st, c->stream->streams[stream_index]); else unlayer_stream(st, c->stream->feed->streams[c->stream->feed_streams[stream_index]]); av_assert0(st->priv_data == NULL); av_assert0(st->internal == st_internal); /* build destination RTP address */ ipaddr = inet_ntoa(dest_addr->sin_addr); switch(c->rtp_protocol) { case RTSP_LOWER_TRANSPORT_UDP: case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: /* RTP/UDP case */ /* XXX: also pass as parameter to function ? */ if (c->stream->is_multicast) { int ttl; ttl = c->stream->multicast_ttl; if (!ttl) ttl = 16; snprintf(ctx->filename, sizeof(ctx->filename), "rtp://%s:%d?multicast=1&ttl=%d", ipaddr, ntohs(dest_addr->sin_port), ttl); } else { snprintf(ctx->filename, sizeof(ctx->filename), "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port)); } if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0) goto fail; c->rtp_handles[stream_index] = h; max_packet_size = h->max_packet_size; break; case RTSP_LOWER_TRANSPORT_TCP: /* RTP/TCP case */ c->rtsp_c = rtsp_c; max_packet_size = RTSP_TCP_MAX_PACKET_SIZE; break; default: goto fail; } http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n", ipaddr, ntohs(dest_addr->sin_port), c->stream->filename, stream_index, c->protocol); /* normally, no packets should be output here, but the packet size may * be checked */ if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) /* XXX: close stream */ goto fail; if (avformat_write_header(ctx, NULL) < 0) { fail: if (h) ffurl_close(h); av_free(st); av_free(ctx); return -1; } avio_close_dyn_buf(ctx->pb, &dummy_buf); ctx->pb = NULL; av_free(dummy_buf); c->rtp_ctx[stream_index] = ctx; return 0; } /********************************************************************/ /* ffserver initialization */ /* FIXME: This code should use avformat_new_stream() */ static LayeredAVStream *add_av_stream1(FFServerStream *stream, AVCodecContext *codec, int copy) { LayeredAVStream *fst; if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams)) return NULL; fst = av_mallocz(sizeof(*fst)); if (!fst) return NULL; if (copy) { fst->codec = avcodec_alloc_context3(codec->codec); if (!fst->codec) { av_free(fst); return NULL; } avcodec_copy_context(fst->codec, codec); } else /* live streams must use the actual feed's codec since it may be * updated later to carry extradata needed by them. */ fst->codec = codec; //NOTE we previously allocated internal & internal->avctx, these seemed uneeded though fst->codecpar = avcodec_parameters_alloc(); fst->index = stream->nb_streams; fst->time_base = codec->time_base; fst->pts_wrap_bits = 33; fst->sample_aspect_ratio = codec->sample_aspect_ratio; stream->streams[stream->nb_streams++] = fst; return fst; } /* return the stream number in the feed */ static int add_av_stream(FFServerStream *feed, LayeredAVStream *st) { LayeredAVStream *fst; AVCodecContext *av, *av1; int i; av = st->codec; for(i=0;i<feed->nb_streams;i++) { av1 = feed->streams[i]->codec; if (av1->codec_id == av->codec_id && av1->codec_type == av->codec_type && av1->bit_rate == av->bit_rate) { switch(av->codec_type) { case AVMEDIA_TYPE_AUDIO: if (av1->channels == av->channels && av1->sample_rate == av->sample_rate) return i; break; case AVMEDIA_TYPE_VIDEO: if (av1->width == av->width && av1->height == av->height && av1->time_base.den == av->time_base.den && av1->time_base.num == av->time_base.num && av1->gop_size == av->gop_size) return i; break; default: abort(); } } } fst = add_av_stream1(feed, av, 0); if (!fst) return -1; if (st->recommended_encoder_configuration) fst->recommended_encoder_configuration = av_strdup(st->recommended_encoder_configuration); return feed->nb_streams - 1; } static void remove_stream(FFServerStream *stream) { FFServerStream **ps; ps = &config.first_stream; while (*ps) { if (*ps == stream) *ps = (*ps)->next; else ps = &(*ps)->next; } } /* compute the needed AVStream for each file */ static void build_file_streams(void) { FFServerStream *stream; AVFormatContext *infile; int i, ret; /* gather all streams */ for(stream = config.first_stream; stream; stream = stream->next) { infile = NULL; if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed) continue; /* the stream comes from a file */ /* try to open the file */ /* open stream */ /* specific case: if transport stream output to RTP, * we use a raw transport stream reader */ if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0); if (!stream->feed_filename[0]) { http_log("Unspecified feed file for stream '%s'\n", stream->filename); goto fail; } http_log("Opening feed file '%s' for stream '%s'\n", stream->feed_filename, stream->filename); ret = avformat_open_input(&infile, stream->feed_filename, stream->ifmt, &stream->in_opts); if (ret < 0) { http_log("Could not open '%s': %s\n", stream->feed_filename, av_err2str(ret)); /* remove stream (no need to spend more time on it) */ fail: remove_stream(stream); } else { /* find all the AVStreams inside and reference them in * 'stream' */ if (avformat_find_stream_info(infile, NULL) < 0) { http_log("Could not find codec parameters from '%s'\n", stream->feed_filename); avformat_close_input(&infile); goto fail; } for(i=0;i<infile->nb_streams;i++) add_av_stream1(stream, infile->streams[i]->codec, 1); avformat_close_input(&infile); } } } static inline int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream) { int matches = 1; /* FIXME: Missed check on AVCodecContext.flags */ #define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x) if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) { http_log("Codecs do not match for stream %d\n", stream); matches = 0; } else if (CHECK_CODEC(bit_rate)) { http_log("Codec bitrates do not match for stream %d\n", stream); matches = 0; } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (av_cmp_q(ccf->time_base, ccs->time_base) || CHECK_CODEC(width) || CHECK_CODEC(height)) { http_log("Codec width, height or framerate do not match for stream %d\n", stream); matches = 0; } } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if (CHECK_CODEC(sample_rate) || CHECK_CODEC(channels) || CHECK_CODEC(frame_size)) { http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream); matches = 0; } } else { http_log("Unknown codec type for stream %d\n", stream); matches = 0; } return matches; } /* compute the needed AVStream for each feed */ static int build_feed_streams(void) { FFServerStream *stream, *feed; int i, fd; /* gather all streams */ for(stream = config.first_stream; stream; stream = stream->next) { feed = stream->feed; if (!feed) continue; if (stream->is_feed) { for(i=0;i<stream->nb_streams;i++) stream->feed_streams[i] = i; continue; } /* we handle a stream coming from a feed */ for(i=0;i<stream->nb_streams;i++) stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]); } /* create feed files if needed */ for(feed = config.first_feed; feed; feed = feed->next_feed) { if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) { AVFormatContext *s = NULL; int matches = 0; /* See if it matches */ if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) { http_log("Deleting feed file '%s' as it appears " "to be corrupt\n", feed->feed_filename); goto drop; } /* set buffer size */ if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) { http_log("Failed to set buffer size\n"); avformat_close_input(&s); goto bail; } /* Now see if it matches */ if (s->nb_streams != feed->nb_streams) { http_log("Deleting feed file '%s' as stream counts " "differ (%d != %d)\n", feed->feed_filename, s->nb_streams, feed->nb_streams); goto drop; } matches = 1; for(i=0;i<s->nb_streams;i++) { AVStream *ss; LayeredAVStream *sf; sf = feed->streams[i]; ss = s->streams[i]; if (sf->index != ss->index || sf->id != ss->id) { http_log("Index & Id do not match for stream %d (%s)\n", i, feed->feed_filename); matches = 0; break; } matches = check_codec_match (sf, ss, i); if (!matches) break; } drop: if (s) avformat_close_input(&s); if (!matches) { if (feed->readonly) { http_log("Unable to delete read-only feed file '%s'\n", feed->feed_filename); goto bail; } unlink(feed->feed_filename); } } if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) { AVFormatContext *s = avformat_alloc_context(); if (!s) { http_log("Failed to allocate context\n"); goto bail; } if (feed->readonly) { http_log("Unable to create feed file '%s' as it is " "marked readonly\n", feed->feed_filename); avformat_free_context(s); goto bail; } /* only write the header of the ffm file */ if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) { http_log("Could not open output feed file '%s'\n", feed->feed_filename); avformat_free_context(s); goto bail; } s->oformat = feed->fmt; for (i = 0; i<feed->nb_streams; i++) { AVStream *st = avformat_new_stream(s, NULL); // FIXME free this if (!st) { http_log("Failed to allocate stream\n"); goto bail; } unlayer_stream(st, feed->streams[i]); } if (avformat_write_header(s, NULL) < 0) { http_log("Container doesn't support the required parameters\n"); avio_closep(&s->pb); s->streams = NULL; s->nb_streams = 0; avformat_free_context(s); goto bail; } /* XXX: need better API */ av_freep(&s->priv_data); avio_closep(&s->pb); s->streams = NULL; s->nb_streams = 0; avformat_free_context(s); } /* get feed size and write index */ fd = open(feed->feed_filename, O_RDONLY); if (fd < 0) { http_log("Could not open output feed file '%s'\n", feed->feed_filename); goto bail; } feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE); feed->feed_size = lseek(fd, 0, SEEK_END); /* ensure that we do not wrap before the end of file */ if (feed->feed_max_size && feed->feed_max_size < feed->feed_size) feed->feed_max_size = feed->feed_size; close(fd); } return 0; bail: return -1; } /* compute the bandwidth used by each stream */ static void compute_bandwidth(void) { unsigned bandwidth; int i; FFServerStream *stream; for(stream = config.first_stream; stream; stream = stream->next) { bandwidth = 0; for(i=0;i<stream->nb_streams;i++) { LayeredAVStream *st = stream->streams[i]; switch(st->codec->codec_type) { case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_VIDEO: bandwidth += st->codec->bit_rate; break; default: break; } } stream->bandwidth = (bandwidth + 999) / 1000; } } static void handle_child_exit(int sig) { pid_t pid; int status; time_t uptime; while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { FFServerStream *feed; for (feed = config.first_feed; feed; feed = feed->next) { if (feed->pid != pid) continue; uptime = time(0) - feed->pid_start; feed->pid = 0; fprintf(stderr, "%s: Pid %"PRId64" exited with status %d after %"PRId64" " "seconds\n", feed->filename, (int64_t) pid, status, (int64_t)uptime); if (uptime < 30) /* Turn off any more restarts */ ffserver_free_child_args(&feed->child_argv); } } need_to_start_children = 1; } static void opt_debug(void) { config.debug = 1; snprintf(config.logfilename, sizeof(config.logfilename), "-"); } void show_help_default(const char *opt, const char *arg) { printf("usage: ffserver [options]\n" "Hyper fast multi format Audio/Video streaming server\n"); printf("\n"); show_help_options(options, "Main options:", 0, 0, 0); } static const OptionDef options[] = { #include "cmdutils_common_opts.h" { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" }, { "d", 0, {(void*)opt_debug}, "enable debug mode" }, { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" }, { NULL }, }; int main(int argc, char **argv) { struct sigaction sigact = { { 0 } }; int cfg_parsed; int ret = EXIT_FAILURE; init_dynload(); config.filename = av_strdup("/etc/ffserver.conf"); parse_loglevel(argc, argv, options); av_register_all(); avformat_network_init(); show_banner(argc, argv, options); my_program_name = argv[0]; parse_options(NULL, argc, argv, options, NULL); unsetenv("http_proxy"); /* Kill the http_proxy */ av_lfg_init(&random_state, av_get_random_seed()); sigact.sa_handler = handle_child_exit; sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART; sigaction(SIGCHLD, &sigact, 0); if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) { fprintf(stderr, "Error reading configuration file '%s': %s\n", config.filename, av_err2str(cfg_parsed)); goto bail; } /* open log file if needed */ if (config.logfilename[0] != '\0') { if (!strcmp(config.logfilename, "-")) logfile = stdout; else logfile = fopen(config.logfilename, "a"); av_log_set_callback(http_av_log); } build_file_streams(); if (build_feed_streams() < 0) { http_log("Could not setup feed streams\n"); goto bail; } compute_bandwidth(); /* signal init */ signal(SIGPIPE, SIG_IGN); if (http_server() < 0) { http_log("Could not start server\n"); goto bail; } ret=EXIT_SUCCESS; bail: av_freep (&config.filename); avformat_network_deinit(); return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4837_0
crossvul-cpp_data_good_395_1
/* Copyright 1996-2013 Han The Thanh <thanh@pdftex.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dvips.h" /* * The external declarations: */ #include "protos.h" #include "ptexmac.h" #undef fm_extend #define fm_extend(f) 0 #undef fm_slant #define fm_slant(f) 0 #undef is_reencoded #define is_reencoded(f) (cur_enc_name != NULL) #undef is_subsetted #define is_subsetted(f) true #undef is_included #define is_included(f) true #undef set_cur_file_name #define set_cur_file_name(s) cur_file_name = s #define external_enc() ext_glyph_names #define full_file_name() cur_file_name #define is_used_char(c) (grid[c] == 1) #define end_last_eexec_line() \ hexline_length = HEXLINE_WIDTH; \ end_hexline(); \ t1_eexec_encrypt = false #define t1_scan_only() #define t1_scan_keys() #define embed_all_glyphs(tex_font) false #undef pdfmovechars #ifdef SHIFTLOWCHARS #define pdfmovechars shiftlowchars #define t1_char(c) T1Char(c) #else /* SHIFTLOWCHARS */ #define t1_char(c) c #define pdfmovechars 0 #endif /* SHIFTLOWCHARS */ #define extra_charset() dvips_extra_charset #define make_subset_tag(a, b) #define update_subset_tag() static char *dvips_extra_charset; static char *cur_file_name; static char *cur_enc_name; static unsigned char *grid; static char *ext_glyph_names[256]; static char print_buf[PRINTF_BUF_SIZE]; static int hexline_length; static char notdef[] = ".notdef"; static size_t last_ptr_index; #include <stdarg.h> #define t1_log(str) #define get_length1() #define get_length2() #define get_length3() #define save_offset() #define t1_open() \ ((t1_file = search(type1path, cur_file_name, FOPEN_RBIN_MODE)) != NULL) #define t1_close() xfclose(t1_file, cur_file_name) #define t1_getchar() getc(t1_file) #define t1_putchar(c) fputc(c, bitfile) #define t1_ungetchar(c) ungetc(c, t1_file) #define t1_eof() feof(t1_file) #define str_prefix(s1, s2) (strncmp(s1, s2, strlen(s2)) == 0) #define t1_prefix(s) str_prefix(t1_line_array, s) #define t1_buf_prefix(s) str_prefix(t1_buf_array, s) #define t1_suffix(s) str_suffix(t1_line_array, t1_line_ptr, s) #define t1_buf_suffix(s) str_suffix(t1_buf_array, t1_buf_ptr, s) #define t1_charstrings() strstr(t1_line_array, charstringname) #define t1_subrs() t1_prefix("/Subrs") #define t1_end_eexec() t1_suffix("mark currentfile closefile") #define t1_cleartomark() t1_prefix("cleartomark") #define enc_open() \ ((enc_file = search(encpath, cur_file_name, FOPEN_RBIN_MODE)) != NULL) #define enc_close() xfclose(enc_file, cur_file_name) #define enc_getchar() getc(enc_file) #define enc_eof() feof(enc_file) #define valid_code(c) (c >= 0 && c < 256) #define fixedcontent true /* false for pdfTeX, true for dvips */ static const char *standard_glyph_names[256] = { /* 0x00 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0x10 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0x20 */ "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", /* 0x30 */ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", /* 0x40 */ "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", /* 0x50 */ "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", /* 0x60 */ "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", /* 0x70 */ "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", notdef, /* 0x80 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0x90 */ notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0xa0 */ notdef, "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", /* 0xb0 */ notdef, "endash", "dagger", "daggerdbl", "periodcentered", notdef, "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", notdef, "questiondown", /* 0xc0 */ notdef, "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", notdef, "ring", "cedilla", notdef, "hungarumlaut", "ogonek", "caron", /* 0xd0 */ "emdash", notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, /* 0xe0 */ notdef, "AE", notdef, "ordfeminine", notdef, notdef, notdef, notdef, "Lslash", "Oslash", "OE", "ordmasculine", notdef, notdef, notdef, notdef, /* 0xf0 */ notdef, "ae", notdef, notdef, notdef, "dotlessi", notdef, notdef, "lslash", "oslash", "oe", "germandbls", notdef, notdef, notdef, notdef }; char **t1_glyph_names; char *t1_builtin_glyph_names[256]; static boolean read_encoding_only; static char charstringname[] = "/CharStrings"; enum { ENC_STANDARD, ENC_BUILTIN } t1_encoding; #define T1_BUF_SIZE 0x10 #define ENC_BUF_SIZE 0x1000 #define CS_HSTEM 1 #define CS_VSTEM 3 #define CS_VMOVETO 4 #define CS_RLINETO 5 #define CS_HLINETO 6 #define CS_VLINETO 7 #define CS_RRCURVETO 8 #define CS_CLOSEPATH 9 #define CS_CALLSUBR 10 #define CS_RETURN 11 #define CS_ESCAPE 12 #define CS_HSBW 13 #define CS_ENDCHAR 14 #define CS_RMOVETO 21 #define CS_HMOVETO 22 #define CS_VHCURVETO 30 #define CS_HVCURVETO 31 #define CS_1BYTE_MAX (CS_HVCURVETO + 1) #define CS_DOTSECTION CS_1BYTE_MAX + 0 #define CS_VSTEM3 CS_1BYTE_MAX + 1 #define CS_HSTEM3 CS_1BYTE_MAX + 2 #define CS_SEAC CS_1BYTE_MAX + 6 #define CS_SBW CS_1BYTE_MAX + 7 #define CS_DIV CS_1BYTE_MAX + 12 #define CS_CALLOTHERSUBR CS_1BYTE_MAX + 16 #define CS_POP CS_1BYTE_MAX + 17 #define CS_SETCURRENTPOINT CS_1BYTE_MAX + 33 #define CS_2BYTE_MAX (CS_SETCURRENTPOINT + 1) #define CS_MAX CS_2BYTE_MAX typedef unsigned char byte; typedef struct { byte nargs; /* number of arguments */ boolean bottom; /* take arguments from bottom of stack? */ boolean clear; /* clear stack? */ boolean valid; } cc_entry; /* CharString Command */ typedef struct { char *name; /* glyph name (or notdef for Subrs entry) */ byte *data; unsigned short len; /* length of the whole string */ unsigned short cslen; /* length of the encoded part of the string */ boolean used; boolean valid; } cs_entry; static unsigned short t1_dr, t1_er; static const unsigned short t1_c1 = 52845, t1_c2 = 22719; static unsigned short t1_cslen; static short t1_lenIV; static char enc_line[ENC_BUF_SIZE]; /* define t1_line_ptr, t1_line_array & t1_line_limit */ typedef char t1_line_entry; define_array(t1_line); /* define t1_buf_ptr, t1_buf_array & t1_buf_limit */ typedef char t1_buf_entry; define_array(t1_buf); static int cs_start; static cs_entry *cs_tab, *cs_ptr, *cs_notdef; static char *cs_dict_start, *cs_dict_end; static int cs_count, cs_size, cs_size_pos; static cs_entry *subr_tab; static char *subr_array_start, *subr_array_end; static int subr_max, subr_size, subr_size_pos; /* This list contains the begin/end tokens commonly used in the */ /* /Subrs array of a Type 1 font. */ static const char *cs_token_pairs_list[][2] = { {" RD", "NP"}, {" -|", "|"}, {" RD", "noaccess put"}, {" -|", "noaccess put"}, {NULL, NULL} }; static const char **cs_token_pair; static boolean t1_pfa, t1_cs, t1_scan, t1_eexec_encrypt, t1_synthetic; static int t1_in_eexec; /* 0 before eexec-encrypted, 1 during, 2 after */ static long t1_block_length; static int last_hexbyte; static FILE *t1_file; static FILE *enc_file; static void pdftex_fail(const char *fmt, ...) { va_list args; va_start(args, fmt); fputs("\nError: module writet1", stderr); if (cur_file_name) fprintf(stderr, " (file %s)", cur_file_name); fputs(": ", stderr); vsprintf(print_buf, fmt, args); fputs(print_buf, stderr); fputs("\n ==> Fatal error occurred, the output PS file is not finished!\n", stderr); va_end(args); exit(-1); } static void pdftex_warn(const char *fmt, ...) { va_list args; va_start(args, fmt); fputs("\nWarning: module writet1 of dvips", stderr); if (cur_file_name) fprintf(stderr, " (file %s)", cur_file_name); fputs(": ", stderr); vsprintf(print_buf, fmt, args); fputs(print_buf, stderr); fputs("\n", stderr); va_end(args); } #define HEXLINE_WIDTH 64 static void end_hexline(void) { if (hexline_length == HEXLINE_WIDTH) { fputs("\n", bitfile); hexline_length = 0; } } static void t1_outhex(byte b) { static const char *hexdigits = "0123456789ABCDEF"; t1_putchar(hexdigits[b/16]); t1_putchar(hexdigits[b%16]); hexline_length += 2; end_hexline(); } static void enc_getline(void) { char *p; int c; restart: if (enc_eof()) pdftex_fail("unexpected end of file"); p = enc_line; do { c = enc_getchar(); append_char_to_buf(c, p, enc_line, ENC_BUF_SIZE); } while (c != 10); append_eol(p, enc_line, ENC_BUF_SIZE); if (p - enc_line < 2 || *enc_line == '%') goto restart; } /* read encoding from .enc file, return glyph_names array, or pdffail() */ char **load_enc_file(char *enc_name) { char buf[ENC_BUF_SIZE], *p, *r; int i, names_count; char **glyph_names; set_cur_file_name(enc_name); glyph_names = (char **) mymalloc(256 * sizeof(char *)); for (i = 0; i < 256; i++) glyph_names[i] = notdef; if (!enc_open()) { pdftex_warn("cannot open encoding file for reading"); cur_file_name = NULL; return glyph_names; } t1_log("{"); t1_log(cur_file_name = full_file_name()); enc_getline(); if (*enc_line != '/' || (r = strchr(enc_line, '[')) == NULL) { remove_eol(r, enc_line); pdftex_fail ("invalid encoding vector (a name or `[' missing): `%s'", enc_line); } names_count = 0; r++; /* skip '[' */ skip(r, ' '); for (;;) { while (*r == '/') { for (p = buf, r++; *r != ' ' && *r != 10 && *r != ']' && *r != '/'; *p++ = *r++); *p = 0; skip(r, ' '); if (names_count > 255) pdftex_fail("encoding vector contains more than 256 names"); if (strcmp(buf, notdef) != 0) glyph_names[names_count] = xstrdup(buf); names_count++; } if (*r != 10 && *r != '%') { if (str_prefix(r, "] def")) goto done; else { remove_eol(r, enc_line); pdftex_fail ("invalid encoding vector: a name or `] def' expected: `%s'", enc_line); } } enc_getline(); r = enc_line; } done: enc_close(); t1_log("}"); cur_file_name = NULL; return glyph_names; } static void t1_check_pfa(void) { const int c = t1_getchar(); t1_pfa = (c != 128) ? true : false; t1_ungetchar(c); } static int t1_getbyte(void) { int c = t1_getchar(); if (t1_pfa) return c; if (t1_block_length == 0) { if (c != 128) pdftex_fail("invalid marker"); c = t1_getchar(); if (c == 3) { while (!t1_eof()) t1_getchar(); return EOF; } t1_block_length = t1_getchar() & 0xff; t1_block_length |= (t1_getchar() & 0xff) << 8; t1_block_length |= (t1_getchar() & 0xff) << 16; t1_block_length |= (t1_getchar() & 0xff) << 24; c = t1_getchar(); } t1_block_length--; return c; } static int hexval(int c) { if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else if (c >= '0' && c <= '9') return c - '0'; else return -1; } static byte edecrypt(byte cipher) { byte plain; if (t1_pfa) { while (cipher == 10 || cipher == 13) cipher = t1_getbyte(); last_hexbyte = cipher = (hexval(cipher) << 4) + hexval(t1_getbyte()); } plain = (cipher ^ (t1_dr >> 8)); t1_dr = (cipher + t1_dr) * t1_c1 + t1_c2; return plain; } static byte cdecrypt(byte cipher, unsigned short *cr) { const byte plain = (cipher ^ (*cr >> 8)); *cr = (cipher + *cr) * t1_c1 + t1_c2; return plain; } static byte eencrypt(byte plain) { const byte cipher = (plain ^ (t1_er >> 8)); t1_er = (cipher + t1_er) * t1_c1 + t1_c2; return cipher; } static byte cencrypt(byte plain, unsigned short *cr) { const byte cipher = (plain ^ (*cr >> 8)); *cr = (cipher + *cr) * t1_c1 + t1_c2; return cipher; } static char *eol(char *s) { char *p = strend(s); if (p - s > 1 && p[-1] != 10) { *p++ = 10; *p = 0; } return p; } static float t1_scan_num(char *p, char **r) { float f; skip(p, ' '); if (sscanf(p, "%g", &f) != 1) { remove_eol(p, t1_line_array); pdftex_fail("a number expected: `%s'", t1_line_array); } if (r != NULL) { for (; isdigit((unsigned char)*p) || *p == '.' || *p == 'e' || *p == 'E' || *p == '+' || *p == '-'; p++); *r = p; } return f; } static boolean str_suffix(const char *begin_buf, const char *end_buf, const char *s) { const char *s1 = end_buf - 1, *s2 = strend(s) - 1; if (*s1 == 10) s1--; while (s1 >= begin_buf && s2 >= s) { if (*s1-- != *s2--) return false; } return s2 < s; } static void t1_getline(void) { int c, l, eexec_scan; char *p; static const char eexec_str[] = "currentfile eexec"; static int eexec_len = 17; /* strlen(eexec_str) */ restart: if (t1_eof()) pdftex_fail("unexpected end of file"); t1_line_ptr = t1_line_array; alloc_array(t1_line, 1, T1_BUF_SIZE); t1_cslen = 0; eexec_scan = 0; c = t1_getbyte(); if (c == EOF) goto exit; while (!t1_eof()) { if (t1_in_eexec == 1) c = edecrypt((byte)c); alloc_array(t1_line, 1, T1_BUF_SIZE); append_char_to_buf(c, t1_line_ptr, t1_line_array, t1_line_limit); if (t1_in_eexec == 0 && eexec_scan >= 0 && eexec_scan < eexec_len) { if (t1_line_array[eexec_scan] == eexec_str[eexec_scan]) eexec_scan++; else eexec_scan = -1; } if (c == 10 || (t1_pfa && eexec_scan == eexec_len && c == 32)) break; if (t1_cs && t1_cslen == 0 && (t1_line_ptr - t1_line_array > 4) && (t1_suffix(" RD ") || t1_suffix(" -| "))) { p = t1_line_ptr - 5; while (*p != ' ') p--; t1_cslen = l = t1_scan_num(p + 1, 0); cs_start = t1_line_ptr - t1_line_array; /* cs_start is an index now */ alloc_array(t1_line, l, T1_BUF_SIZE); while (l-- > 0) *t1_line_ptr++ = edecrypt((byte)t1_getbyte()); } c = t1_getbyte(); } alloc_array(t1_line, 2, T1_BUF_SIZE); /* append_eol can append 2 chars */ append_eol(t1_line_ptr, t1_line_array, t1_line_limit); if (t1_line_ptr - t1_line_array < 2) goto restart; if (eexec_scan == eexec_len) t1_in_eexec = 1; exit: /* ensure that t1_buf_array has as much room as t1_line_array */ t1_buf_ptr = t1_buf_array; alloc_array(t1_buf, t1_line_limit, t1_line_limit); } static void t1_putline(void) { char *p = t1_line_array; if (t1_line_ptr - t1_line_array <= 1) return; if (t1_eexec_encrypt) { while (p < t1_line_ptr) t1_outhex(eencrypt(*p++)); /* dvips outputs hex, unlike pdftex */ } else while (p < t1_line_ptr) t1_putchar(*p++); } static void t1_puts(const char *s) { if (s != t1_line_array) strcpy(t1_line_array, s); t1_line_ptr = strend(t1_line_array); t1_putline(); } static void t1_printf(const char *fmt, ...) { va_list args; va_start(args, fmt); vsprintf(t1_line_array, fmt, args); t1_puts(t1_line_array); va_end(args); } static void t1_init_params(const char *open_name_prefix) { t1_log(open_name_prefix); t1_log(cur_file_name); t1_lenIV = 4; t1_dr = 55665; t1_er = 55665; t1_in_eexec = 0; t1_cs = false; t1_scan = true; t1_synthetic = false; t1_eexec_encrypt = false; t1_block_length = 0; t1_check_pfa(); } static void t1_close_font_file(const char *close_name_suffix) { t1_log(close_name_suffix); t1_close(); cur_file_name = NULL; } static void t1_check_block_len(boolean decrypt) { int l, c; if (t1_block_length == 0) return; c = t1_getbyte(); if (decrypt) c = edecrypt((byte)c); l = t1_block_length; if (!(l == 0 && (c == 10 || c == 13))) { pdftex_warn("%i bytes more than expected were ignored", l + 1); while (l-- > 0) t1_getbyte(); } } static void t1_start_eexec(void) { int i; if (is_included(fm_cur)) { get_length1(); save_offset(); } if (!t1_pfa) t1_check_block_len(false); for (t1_line_ptr = t1_line_array, i = 0; i < 4; i++) { edecrypt((byte)t1_getbyte()); *t1_line_ptr++ = 0; } t1_eexec_encrypt = true; if (is_included(fm_cur)) t1_putline(); /* to put the first four bytes */ } static void t1_stop_eexec(void) { int c; if (is_included(fm_cur)) { get_length2(); save_offset(); } end_last_eexec_line(); if (!t1_pfa) t1_check_block_len(true); else { c = edecrypt((byte)t1_getbyte()); if (!(c == 10 || c == 13)) { if (last_hexbyte == 0) t1_puts("00"); else pdftex_warn("unexpected data after eexec"); } } t1_cs = false; t1_in_eexec = 2; } static void t1_scan_param(void) { static const char *lenIV = "/lenIV"; if (!t1_scan || *t1_line_array != '/') return; if (t1_prefix(lenIV)) { t1_lenIV = t1_scan_num(t1_line_array + strlen(lenIV), 0); if (t1_lenIV < 0) pdftex_fail("negative value of lenIV is not supported"); return; } t1_scan_keys(); } static void copy_glyph_names(char **glyph_names, int a, int b) { if (glyph_names[b] != notdef) { xfree(glyph_names[b]); glyph_names[b] = notdef; } if (glyph_names[a] != notdef) { glyph_names[b] = xstrdup(glyph_names[a]); } } /* read encoding from Type1 font file, return glyph_names array, or pdffail() */ static char **t1_builtin_enc(void) { int i, a, b, c, counter = 0; char *r, *p, **glyph_names; /* At this moment "/Encoding" is the prefix of t1_line_array */ glyph_names = t1_builtin_glyph_names; for (i = 0; i < 256; i++) glyph_names[i] = notdef; if (t1_suffix("def")) { /* predefined encoding */ if (sscanf(t1_line_array + strlen("/Encoding"), "%255s", t1_buf_array) == 1 && strcmp(t1_buf_array, "StandardEncoding") == 0) { t1_encoding = ENC_STANDARD; for (i = 0; i < 256; i++) { if (standard_glyph_names[i] != notdef) glyph_names[i] = xstrdup(standard_glyph_names[i]); } return glyph_names; } pdftex_fail("cannot subset font (unknown predefined encoding `%s')", t1_buf_array); } /* At this moment "/Encoding" is the prefix of t1_line_array, and the encoding is * not a predefined encoding. * * We have two possible forms of Encoding vector. The first case is * * /Encoding [/a /b /c...] readonly def * * and the second case can look like * * /Encoding 256 array 0 1 255 {1 index exch /.notdef put} for * dup 0 /x put * dup 1 /y put * ... * readonly def */ t1_encoding = ENC_BUILTIN; if (t1_prefix("/Encoding [") || t1_prefix("/Encoding[")) { /* the first case */ r = strchr(t1_line_array, '[') + 1; skip(r, ' '); for (;;) { while (*r == '/') { for (p = t1_buf_array, r++; *r != 32 && *r != 10 && *r != ']' && *r != '/'; *p++ = *r++); *p = 0; skip(r, ' '); if (counter > 255) pdftex_fail("encoding vector contains more than 256 names"); if (strcmp(t1_buf_array, notdef) != 0) glyph_names[counter] = xstrdup(t1_buf_array); counter++; } if (*r != 10 && *r != '%') { if (str_prefix(r, "] def") || str_prefix(r, "] readonly def")) break; else { remove_eol(r, t1_line_array); pdftex_fail ("a name or `] def' or `] readonly def' expected: `%s'", t1_line_array); } } t1_getline(); r = t1_line_array; } } else { /* the second case */ p = strchr(t1_line_array, 10); for (;;) { if (*p == 10) { t1_getline(); p = t1_line_array; } /* check for `dup <index> <glyph> put' */ if (sscanf(p, "dup %i%255s put", &i, t1_buf_array) == 2 && *t1_buf_array == '/' && valid_code(i)) { if (strcmp(t1_buf_array + 1, notdef) != 0) glyph_names[i] = xstrdup(t1_buf_array + 1); p = strstr(p, " put") + strlen(" put"); skip(p, ' '); } /* check for `dup dup <to> exch <from> get put' */ else if (sscanf(p, "dup dup %i exch %i get put", &b, &a) == 2 && valid_code(a) && valid_code(b)) { copy_glyph_names(glyph_names, a, b); p = strstr(p, " get put") + strlen(" get put"); skip(p, ' '); } /* check for `dup dup <from> <size> getinterval <to> exch putinterval' */ else if (sscanf(p, "dup dup %i %i getinterval %i exch putinterval", &a, &c, &b) == 3 && valid_code(a) && valid_code(b) && valid_code(c)) { for (i = 0; i < c; i++) copy_glyph_names(glyph_names, a + i, b + i); p = strstr(p, " putinterval") + strlen(" putinterval"); skip(p, ' '); } /* check for `def' or `readonly def' */ else if ((p == t1_line_array || (p > t1_line_array && p[-1] == ' ')) && strcmp(p, "def\n") == 0) return glyph_names; /* skip an unrecognizable word */ else { while (*p != ' ' && *p != 10) p++; skip(p, ' '); } } } return glyph_names; } static void t1_check_end(void) { if (t1_eof()) return; t1_getline(); if (t1_prefix("{restore}")) t1_putline(); } static boolean t1_open_fontfile(const char *open_name_prefix) { if (!t1_open()) { char *msg = concat ("! Couldn't find font file ", cur_file_name); error(msg); } t1_init_params(open_name_prefix); return true; /* font file found */ } #define t1_include() #define check_subr(subr) \ if (subr >= subr_size || subr < 0) \ pdftex_fail("Subrs array: entry index out of range (%i)", subr); static const char **check_cs_token_pair(void) { const char **p = (const char **) cs_token_pairs_list; for (; p[0] != NULL; ++p) if (t1_buf_prefix(p[0]) && t1_buf_suffix(p[1])) return p; return NULL; } static void cs_store(boolean is_subr) { char *p; cs_entry *ptr; int subr; for (p = t1_line_array, t1_buf_ptr = t1_buf_array; *p != ' '; *t1_buf_ptr++ = *p++); *t1_buf_ptr = 0; if (is_subr) { subr = t1_scan_num(p + 1, 0); check_subr(subr); ptr = subr_tab + subr; } else { ptr = cs_ptr++; if (cs_ptr - cs_tab > cs_size) pdftex_fail ("CharStrings dict: more entries than dict size (%i)", cs_size); if (strcmp(t1_buf_array + 1, notdef) == 0) /* skip the slash */ ptr->name = notdef; else ptr->name = xstrdup(t1_buf_array + 1); } /* copy " RD " + cs data to t1_buf_array */ memcpy(t1_buf_array, t1_line_array + cs_start - 4, (unsigned) (t1_cslen + 4)); /* copy the end of cs data to t1_buf_array */ for (p = t1_line_array + cs_start + t1_cslen, t1_buf_ptr = t1_buf_array + t1_cslen + 4; *p != 10; *t1_buf_ptr++ = *p++); *t1_buf_ptr++ = 10; if (is_subr && cs_token_pair == NULL) cs_token_pair = check_cs_token_pair(); ptr->len = t1_buf_ptr - t1_buf_array; ptr->cslen = t1_cslen; ptr->data = xtalloc(ptr->len, byte); memcpy(ptr->data, t1_buf_array, ptr->len); ptr->valid = true; } #define store_subr() cs_store(true) #define store_cs() cs_store(false) #define CC_STACK_SIZE 24 static integer cc_stack[CC_STACK_SIZE], *stack_ptr = cc_stack; static cc_entry cc_tab[CS_MAX]; static boolean is_cc_init = false; #define cc_pop(N) \ if (stack_ptr - cc_stack < (N)) \ stack_error(N); \ stack_ptr -= N #define stack_error(N) { \ pdftex_fail("CharString: invalid access (%i) to stack (%i entries)", \ (int) N, (int)(stack_ptr - cc_stack)); \ goto cs_error; \ } /* static integer cc_get(integer index) { if (index < 0) { if (stack_ptr + index < cc_stack ) stack_error(stack_ptr - cc_stack + index); return *(stack_ptr + index); } else { if (cc_stack + index >= stack_ptr) stack_error(index); return cc_stack[index]; } } */ #define cc_get(N) ((N) < 0 ? *(stack_ptr + (N)) : *(cc_stack + (N))) #define cc_push(V) *stack_ptr++ = V #define cc_clear() stack_ptr = cc_stack #define set_cc(N, B, A, C) \ cc_tab[N].nargs = A; \ cc_tab[N].bottom = B; \ cc_tab[N].clear = C; \ cc_tab[N].valid = true static void cc_init(void) { int i; if (is_cc_init) return; for (i = 0; i < CS_MAX; i++) cc_tab[i].valid = false; set_cc(CS_HSTEM, true, 2, true); set_cc(CS_VSTEM, true, 2, true); set_cc(CS_VMOVETO, true, 1, true); set_cc(CS_RLINETO, true, 2, true); set_cc(CS_HLINETO, true, 1, true); set_cc(CS_VLINETO, true, 1, true); set_cc(CS_RRCURVETO, true, 6, true); set_cc(CS_CLOSEPATH, false, 0, true); set_cc(CS_CALLSUBR, false, 1, false); set_cc(CS_RETURN, false, 0, false); /* set_cc(CS_ESCAPE, false, 0, false); */ set_cc(CS_HSBW, true, 2, true); set_cc(CS_ENDCHAR, false, 0, true); set_cc(CS_RMOVETO, true, 2, true); set_cc(CS_HMOVETO, true, 1, true); set_cc(CS_VHCURVETO, true, 4, true); set_cc(CS_HVCURVETO, true, 4, true); set_cc(CS_DOTSECTION, false, 0, true); set_cc(CS_VSTEM3, true, 6, true); set_cc(CS_HSTEM3, true, 6, true); set_cc(CS_SEAC, true, 5, true); set_cc(CS_SBW, true, 4, true); set_cc(CS_DIV, false, 2, false); set_cc(CS_CALLOTHERSUBR, false, 0, false); set_cc(CS_POP, false, 0, false); set_cc(CS_SETCURRENTPOINT, true, 2, true); is_cc_init = true; } #define cs_getchar() cdecrypt(*data++, &cr) #define mark_subr(n) cs_mark(0, n) #define mark_cs(s) cs_mark(s, 0) static void cs_fail(const char *cs_name, int subr, const char *fmt, ...) { char buf[SMALL_BUF_SIZE]; va_list args; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); if (cs_name == NULL) pdftex_warn("Subr (%i): %s", (int) subr, buf); else pdftex_warn("CharString (/%s): %s", cs_name, buf); } /* fix a return-less subr by appending CS_RETURN */ static void append_cs_return(cs_entry *ptr) { unsigned short cr; int i; byte *p, *q, *data, *new_data; assert(ptr != NULL && ptr->valid && ptr->used); /* decrypt the cs data to t1_buf_array, append CS_RETURN */ p = (byte *) t1_buf_array; data = ptr->data + 4; cr = 4330; for (i = 0; i < ptr->cslen; i++) *p++ = cs_getchar(); *p = CS_RETURN; /* encrypt the new cs data to new_data */ new_data = xtalloc(ptr->len + 1, byte); memcpy(new_data, ptr->data, 4); p = new_data + 4; q = (byte *) t1_buf_array; cr = 4330; for (i = 0; i < ptr->cslen + 1; i++) *p++ = cencrypt(*q++, &cr); memcpy(p, ptr->data + 4 + ptr->cslen, ptr->len - ptr->cslen - 4); /* update *ptr */ xfree(ptr->data); ptr->data = new_data; ptr->len++; ptr->cslen++; } static void cs_mark(const char *cs_name, int subr) { byte *data; int i, b, cs_len; int last_cmd = 0; integer a, a1, a2; unsigned short cr; static integer lastargOtherSubr3 = 3; /* the argument of last call to OtherSubrs[3] */ cs_entry *ptr; cc_entry *cc; if (cs_name == NULL) { check_subr(subr); ptr = subr_tab + subr; if (!ptr->valid) return; } else { if (cs_notdef != NULL && (cs_name == notdef || strcmp(cs_name, notdef) == 0)) ptr = cs_notdef; else { for (ptr = cs_tab; ptr < cs_ptr; ptr++) if (strcmp(ptr->name, cs_name) == 0) break; if (ptr == cs_ptr) { pdftex_warn("glyph `%s' undefined", cs_name); return; } if (ptr->name == notdef) cs_notdef = ptr; } } /* only marked CharString entries and invalid entries can be skipped; valid marked subrs must be parsed to keep the stack in sync */ if (!ptr->valid || (ptr->used && cs_name != NULL)) return; ptr->used = true; cr = 4330; cs_len = ptr->cslen; data = ptr->data + 4; for (i = 0; i < t1_lenIV; i++, cs_len--) cs_getchar(); while (cs_len > 0) { --cs_len; b = cs_getchar(); if (b >= 32) { if (b <= 246) a = b - 139; else if (b <= 250) { --cs_len; a = ((b - 247) << 8) + 108 + cs_getchar(); } else if (b <= 254) { --cs_len; a = -((b - 251) << 8) - 108 - cs_getchar(); } else { cs_len -= 4; a = (cs_getchar() & 0xff) << 24; a |= (cs_getchar() & 0xff) << 16; a |= (cs_getchar() & 0xff) << 8; a |= (cs_getchar() & 0xff) << 0; if (sizeof(integer) > 4 && (a & 0x80000000)) a |= ~0x7FFFFFFF; } cc_push(a); } else { if (b == CS_ESCAPE) { b = cs_getchar() + CS_1BYTE_MAX; cs_len--; } if (b >= CS_MAX) { cs_fail(cs_name, subr, "command value out of range: %i", (int) b); goto cs_error; } cc = cc_tab + b; if (!cc->valid) { cs_fail(cs_name, subr, "command not valid: %i", (int) b); goto cs_error; } if (cc->bottom) { if (stack_ptr - cc_stack < cc->nargs) cs_fail(cs_name, subr, "less arguments on stack (%i) than required (%i)", (int) (stack_ptr - cc_stack), (int) cc->nargs); else if (stack_ptr - cc_stack > cc->nargs) cs_fail(cs_name, subr, "more arguments on stack (%i) than required (%i)", (int) (stack_ptr - cc_stack), (int) cc->nargs); } last_cmd = b; switch (cc - cc_tab) { case CS_CALLSUBR: a1 = cc_get(-1); cc_pop(1); mark_subr(a1); if (!subr_tab[a1].valid) { cs_fail(cs_name, subr, "cannot call subr (%i)", (int) a1); goto cs_error; } break; case CS_DIV: cc_pop(2); cc_push(0); break; case CS_CALLOTHERSUBR: if (cc_get(-1) == 3) lastargOtherSubr3 = cc_get(-3); a1 = cc_get(-2) + 2; cc_pop(a1); break; case CS_POP: cc_push(lastargOtherSubr3); /* the only case when we care about the value being pushed onto stack is when POP follows CALLOTHERSUBR (changing hints by OtherSubrs[3]) */ break; case CS_SEAC: a1 = cc_get(3); a2 = cc_get(4); cc_clear(); mark_cs(standard_glyph_names[a1]); mark_cs(standard_glyph_names[a2]); break; default: if (cc->clear) cc_clear(); } } } if (cs_name == NULL && last_cmd != CS_RETURN) { pdftex_warn("last command in subr `%i' is not a RETURN; " "I will add it now but please consider fixing the font", (int) subr); append_cs_return(ptr); } return; cs_error: /* an error occured during parsing */ cc_clear(); ptr->valid = false; ptr->used = false; } static void t1_subset_ascii_part(void) { int i, j; t1_getline(); while (!t1_prefix("/Encoding")) { t1_scan_param(); if (!(t1_prefix("/UniqueID") && !strncmp(t1_line_array + strlen(t1_line_array) -4, "def", 3))) t1_putline(); t1_getline(); } if (is_reencoded(fm_cur)) t1_glyph_names = external_enc(); else t1_glyph_names = t1_builtin_enc(); if (is_included(fm_cur) && is_subsetted(fm_cur)) { make_subset_tag(fm_cur, t1_glyph_names); update_subset_tag(); } if (t1_encoding == ENC_STANDARD) t1_puts("/Encoding StandardEncoding def\n"); else { t1_puts ("/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n"); for (i = 0, j = 0; i < 256; i++) { if (is_used_char(i) && t1_glyph_names[i] != notdef) { j++; t1_printf("dup %i /%s put\n", (int)t1_char(i), t1_glyph_names[i]); } } if (j == 0) /* We didn't mark anything for the Encoding array. */ /* We add "dup 0 /.notdef put" for compatibility */ /* with Acrobat 5.0. */ t1_puts("dup 0 /.notdef put\n"); t1_puts("readonly def\n"); } do { t1_getline(); t1_scan_param(); if (!t1_prefix("/UniqueID")) /* ignore UniqueID for subsetted fonts */ t1_putline(); } while (t1_in_eexec == 0); } static void cs_init(void) { cs_ptr = cs_tab = NULL; cs_dict_start = cs_dict_end = NULL; cs_count = cs_size = cs_size_pos = 0; cs_token_pair = NULL; subr_tab = NULL; subr_array_start = subr_array_end = NULL; subr_max = subr_size = subr_size_pos = 0; } static void init_cs_entry(cs_entry *cs) { cs->data = NULL; cs->name = NULL; cs->len = 0; cs->cslen = 0; cs->used = false; cs->valid = false; } static void t1_read_subrs(void) { int i, s; cs_entry *ptr; t1_getline(); while (!(t1_charstrings() || t1_subrs())) { t1_scan_param(); t1_putline(); t1_getline(); } found: t1_cs = true; t1_scan = false; if (!t1_subrs()) return; subr_size_pos = strlen("/Subrs") + 1; /* subr_size_pos points to the number indicating dict size after "/Subrs" */ subr_size = t1_scan_num(t1_line_array + subr_size_pos, 0); if (subr_size == 0) { while (!t1_charstrings()) t1_getline(); return; } subr_tab = xtalloc(subr_size, cs_entry); for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) init_cs_entry(ptr); subr_array_start = xstrdup(t1_line_array); t1_getline(); while (t1_cslen) { store_subr(); t1_getline(); } /* mark the first four entries without parsing */ for (i = 0; i < subr_size && i < 4; i++) subr_tab[i].used = true; /* the end of the Subrs array might have more than one line so we need to concatnate them to subr_array_end. Unfortunately some fonts don't have the Subrs array followed by the CharStrings dict immediately (synthetic fonts). If we cannot find CharStrings in next POST_SUBRS_SCAN lines then we will treat the font as synthetic and ignore everything until next Subrs is found */ #define POST_SUBRS_SCAN 5 s = 0; *t1_buf_array = 0; for (i = 0; i < POST_SUBRS_SCAN; i++) { if (t1_charstrings()) break; s += t1_line_ptr - t1_line_array; alloc_array(t1_buf, s, T1_BUF_SIZE); strcat(t1_buf_array, t1_line_array); t1_getline(); } subr_array_end = xstrdup(t1_buf_array); if (i == POST_SUBRS_SCAN) { /* CharStrings not found; suppose synthetic font */ for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) if (ptr->valid) xfree(ptr->data); xfree(subr_tab); xfree(subr_array_start); xfree(subr_array_end); cs_init(); t1_cs = false; t1_synthetic = true; while (!(t1_charstrings() || t1_subrs())) t1_getline(); goto found; } } #define t1_subr_flush() t1_flush_cs(true) #define t1_cs_flush() t1_flush_cs(false) static void t1_flush_cs(boolean is_subr) { char *p; byte *r, *return_cs = NULL; cs_entry *tab, *end_tab, *ptr; char *start_line, *line_end; int count, size_pos; unsigned short cr, cs_len = 0; /* to avoid warning about uninitialized use of cs_len */ if (is_subr) { start_line = subr_array_start; line_end = subr_array_end; size_pos = subr_size_pos; tab = subr_tab; count = subr_max + 1; end_tab = subr_tab + count; } else { start_line = cs_dict_start; line_end = cs_dict_end; size_pos = cs_size_pos; tab = cs_tab; end_tab = cs_ptr; count = cs_count; } t1_line_ptr = t1_line_array; for (p = start_line; p - start_line < size_pos;) *t1_line_ptr++ = *p++; while (isdigit((unsigned char)*p)) p++; sprintf(t1_line_ptr, "%u", count); strcat(t1_line_ptr, p); t1_line_ptr = eol(t1_line_array); t1_putline(); /* create return_cs to replace unused subr's */ if (is_subr) { cr = 4330; cs_len = 0; /* at this point we have t1_lenIV >= 0; * a negative value would be caught in t1_scan_param() */ return_cs = xtalloc(t1_lenIV + 1, byte); for (cs_len = 0, r = return_cs; cs_len < t1_lenIV; cs_len++, r++) *r = cencrypt(0x00, &cr); *r = cencrypt(CS_RETURN, &cr); cs_len++; } for (ptr = tab; ptr < end_tab; ptr++) { if (ptr->used) { if (is_subr) sprintf(t1_line_array, "dup %lu %u", (unsigned long) (ptr - tab), ptr->cslen); else sprintf(t1_line_array, "/%s %u", ptr->name, ptr->cslen); p = strend(t1_line_array); memcpy(p, ptr->data, ptr->len); t1_line_ptr = p + ptr->len; t1_putline(); } else { /* replace unsused subr's by return_cs */ if (is_subr) { sprintf(t1_line_array, "dup %lu %u%s ", (unsigned long) (ptr - tab), cs_len, cs_token_pair[0]); p = strend(t1_line_array); memcpy(p, return_cs, cs_len); t1_line_ptr = p + cs_len; t1_putline(); sprintf(t1_line_array, " %s", cs_token_pair[1]); t1_line_ptr = eol(t1_line_array); t1_putline(); } } xfree(ptr->data); if (ptr->name != notdef) xfree(ptr->name); } sprintf(t1_line_array, "%s", line_end); t1_line_ptr = eol(t1_line_array); t1_putline(); if (is_subr) xfree(return_cs); xfree(tab); xfree(start_line); xfree(line_end); } static void t1_mark_glyphs(void) { int i; char *charset = extra_charset(); char *g, *s, *r; cs_entry *ptr; if (t1_synthetic || embed_all_glyphs(tex_font)) { /* mark everything */ if (cs_tab != NULL) for (ptr = cs_tab; ptr < cs_ptr; ptr++) if (ptr->valid) ptr->used = true; if (subr_tab != NULL) { for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) if (ptr->valid) ptr->used = true; subr_max = subr_size - 1; } return; } mark_cs(notdef); for (i = 0; i < 256; i++) if (is_used_char(i)) { if (t1_glyph_names[i] == notdef) pdftex_warn("character %i is mapped to %s", i, notdef); else mark_cs(t1_glyph_names[i]); } if (charset == NULL) goto set_subr_max; g = s = charset + 1; /* skip the first '/' */ r = strend(g); while (g < r) { while (*s != '/' && s < r) s++; *s = 0; /* terminate g by rewriting '/' to 0 */ mark_cs(g); g = s + 1; } set_subr_max: if (subr_tab != NULL) for (subr_max = -1, ptr = subr_tab; ptr - subr_tab < subr_size; ptr++) if (ptr->used && ptr - subr_tab > subr_max) subr_max = ptr - subr_tab; } static void t1_check_unusual_charstring(void) { char *p = strstr(t1_line_array, charstringname) + strlen(charstringname); int i; /* if no number follows "/CharStrings", let's read the next line */ if (sscanf(p, "%i", &i) != 1) { /* pdftex_warn("no number found after `%s', I assume it's on the next line", charstringname); */ strcpy(t1_buf_array, t1_line_array); /* t1_getline always appends EOL to t1_line_array; let's change it to * space before appending the next line */ *(strend(t1_buf_array) - 1) = ' '; t1_getline(); alloc_array(t1_buf, strlen(t1_line_array) + strlen(t1_buf_array) + 1, T1_BUF_SIZE); strcat(t1_buf_array, t1_line_array); alloc_array(t1_line, strlen(t1_buf_array) + 1, T1_BUF_SIZE); strcpy(t1_line_array, t1_buf_array); t1_line_ptr = eol(t1_line_array); } } static void t1_subset_charstrings(void) { cs_entry *ptr; /* at this point t1_line_array contains "/CharStrings". when we hit a case like this: dup/CharStrings 229 dict dup begin we read the next line and concatenate to t1_line_array before moving on */ t1_check_unusual_charstring(); cs_size_pos = strstr(t1_line_array, charstringname) + strlen(charstringname) - t1_line_array + 1; /* cs_size_pos points to the number indicating dict size after "/CharStrings" */ cs_size = t1_scan_num(t1_line_array + cs_size_pos, 0); cs_ptr = cs_tab = xtalloc(cs_size, cs_entry); for (ptr = cs_tab; ptr - cs_tab < cs_size; ptr++) init_cs_entry(ptr); cs_notdef = NULL; cs_dict_start = xstrdup(t1_line_array); t1_getline(); while (t1_cslen) { store_cs(); t1_getline(); } cs_dict_end = xstrdup(t1_line_array); t1_mark_glyphs(); if (subr_tab != NULL) { if (cs_token_pair == NULL) pdftex_fail ("This Type 1 font uses mismatched subroutine begin/end token pairs."); t1_subr_flush(); } for (cs_count = 0, ptr = cs_tab; ptr < cs_ptr; ptr++) if (ptr->used) cs_count++; t1_cs_flush(); } static void t1_subset_end(void) { if (t1_synthetic) { /* copy to "dup /FontName get exch definefont pop" */ while (!strstr(t1_line_array, "definefont")) { t1_getline(); t1_putline(); } while (!t1_end_eexec()) t1_getline(); /* ignore the rest */ t1_putline(); /* write "mark currentfile closefile" */ } else while (!t1_end_eexec()) { /* copy to "mark currentfile closefile" */ t1_getline(); t1_putline(); } t1_stop_eexec(); if (fixedcontent) { /* copy 512 zeros (not needed for PDF) */ while (!t1_cleartomark()) { t1_getline(); t1_putline(); } if (!t1_synthetic) /* don't check "{restore}if" for synthetic fonts */ t1_check_end(); /* write "{restore}if" if found */ } get_length3(); } static void writet1(void) { read_encoding_only = false; if (!is_included(fm_cur)) { /* scan parameters from font file */ if (!t1_open_fontfile("{")) return; t1_scan_only(); t1_close_font_file("}"); return; } if (!is_subsetted(fm_cur)) { /* include entire font */ if (!t1_open_fontfile("<<")) return; t1_include(); t1_close_font_file(">>"); return; } /* partial downloading */ if (!t1_open_fontfile("<")) return; t1_subset_ascii_part(); t1_start_eexec(); cc_init(); cs_init(); t1_read_subrs(); t1_subset_charstrings(); t1_subset_end(); t1_close_font_file(">"); } boolean t1_subset_2(char *fontfile, unsigned char *g, char *extraGlyphs) { int i; for (i = 0; i < 256; i++) ext_glyph_names[i] = (char*) notdef; grid = g; cur_file_name = fontfile; hexline_length = 0; dvips_extra_charset = extraGlyphs; writet1(); for (i = 0; i < 256; i++) if (ext_glyph_names[i] != notdef) free(ext_glyph_names[i]); return 1; /* note: there *is* no unsuccessful return */ }
./CrossVul/dataset_final_sorted/CWE-119/c/good_395_1
crossvul-cpp_data_good_5610_0
/* * tg3.c: Broadcom Tigon3 ethernet driver. * * Copyright (C) 2001, 2002, 2003, 2004 David S. Miller (davem@redhat.com) * Copyright (C) 2001, 2002, 2003 Jeff Garzik (jgarzik@pobox.com) * Copyright (C) 2004 Sun Microsystems Inc. * Copyright (C) 2005-2013 Broadcom Corporation. * * Firmware is: * Derived from proprietary unpublished source code, * Copyright (C) 2000-2003 Broadcom Corporation. * * Permission is hereby granted for the distribution of this firmware * data in hexadecimal or equivalent format, provided this copyright * notice is accompanying it. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/stringify.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/compiler.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/in.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/pci.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/ethtool.h> #include <linux/mdio.h> #include <linux/mii.h> #include <linux/phy.h> #include <linux/brcmphy.h> #include <linux/if_vlan.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/workqueue.h> #include <linux/prefetch.h> #include <linux/dma-mapping.h> #include <linux/firmware.h> #include <linux/ssb/ssb_driver_gige.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <net/checksum.h> #include <net/ip.h> #include <linux/io.h> #include <asm/byteorder.h> #include <linux/uaccess.h> #include <uapi/linux/net_tstamp.h> #include <linux/ptp_clock_kernel.h> #ifdef CONFIG_SPARC #include <asm/idprom.h> #include <asm/prom.h> #endif #define BAR_0 0 #define BAR_2 2 #include "tg3.h" /* Functions & macros to verify TG3_FLAGS types */ static inline int _tg3_flag(enum TG3_FLAGS flag, unsigned long *bits) { return test_bit(flag, bits); } static inline void _tg3_flag_set(enum TG3_FLAGS flag, unsigned long *bits) { set_bit(flag, bits); } static inline void _tg3_flag_clear(enum TG3_FLAGS flag, unsigned long *bits) { clear_bit(flag, bits); } #define tg3_flag(tp, flag) \ _tg3_flag(TG3_FLAG_##flag, (tp)->tg3_flags) #define tg3_flag_set(tp, flag) \ _tg3_flag_set(TG3_FLAG_##flag, (tp)->tg3_flags) #define tg3_flag_clear(tp, flag) \ _tg3_flag_clear(TG3_FLAG_##flag, (tp)->tg3_flags) #define DRV_MODULE_NAME "tg3" #define TG3_MAJ_NUM 3 #define TG3_MIN_NUM 130 #define DRV_MODULE_VERSION \ __stringify(TG3_MAJ_NUM) "." __stringify(TG3_MIN_NUM) #define DRV_MODULE_RELDATE "February 14, 2013" #define RESET_KIND_SHUTDOWN 0 #define RESET_KIND_INIT 1 #define RESET_KIND_SUSPEND 2 #define TG3_DEF_RX_MODE 0 #define TG3_DEF_TX_MODE 0 #define TG3_DEF_MSG_ENABLE \ (NETIF_MSG_DRV | \ NETIF_MSG_PROBE | \ NETIF_MSG_LINK | \ NETIF_MSG_TIMER | \ NETIF_MSG_IFDOWN | \ NETIF_MSG_IFUP | \ NETIF_MSG_RX_ERR | \ NETIF_MSG_TX_ERR) #define TG3_GRC_LCLCTL_PWRSW_DELAY 100 /* length of time before we decide the hardware is borked, * and dev->tx_timeout() should be called to fix the problem */ #define TG3_TX_TIMEOUT (5 * HZ) /* hardware minimum and maximum for a single frame's data payload */ #define TG3_MIN_MTU 60 #define TG3_MAX_MTU(tp) \ (tg3_flag(tp, JUMBO_CAPABLE) ? 9000 : 1500) /* These numbers seem to be hard coded in the NIC firmware somehow. * You can't change the ring sizes, but you can change where you place * them in the NIC onboard memory. */ #define TG3_RX_STD_RING_SIZE(tp) \ (tg3_flag(tp, LRG_PROD_RING_CAP) ? \ TG3_RX_STD_MAX_SIZE_5717 : TG3_RX_STD_MAX_SIZE_5700) #define TG3_DEF_RX_RING_PENDING 200 #define TG3_RX_JMB_RING_SIZE(tp) \ (tg3_flag(tp, LRG_PROD_RING_CAP) ? \ TG3_RX_JMB_MAX_SIZE_5717 : TG3_RX_JMB_MAX_SIZE_5700) #define TG3_DEF_RX_JUMBO_RING_PENDING 100 /* Do not place this n-ring entries value into the tp struct itself, * we really want to expose these constants to GCC so that modulo et * al. operations are done with shifts and masks instead of with * hw multiply/modulo instructions. Another solution would be to * replace things like '% foo' with '& (foo - 1)'. */ #define TG3_TX_RING_SIZE 512 #define TG3_DEF_TX_RING_PENDING (TG3_TX_RING_SIZE - 1) #define TG3_RX_STD_RING_BYTES(tp) \ (sizeof(struct tg3_rx_buffer_desc) * TG3_RX_STD_RING_SIZE(tp)) #define TG3_RX_JMB_RING_BYTES(tp) \ (sizeof(struct tg3_ext_rx_buffer_desc) * TG3_RX_JMB_RING_SIZE(tp)) #define TG3_RX_RCB_RING_BYTES(tp) \ (sizeof(struct tg3_rx_buffer_desc) * (tp->rx_ret_ring_mask + 1)) #define TG3_TX_RING_BYTES (sizeof(struct tg3_tx_buffer_desc) * \ TG3_TX_RING_SIZE) #define NEXT_TX(N) (((N) + 1) & (TG3_TX_RING_SIZE - 1)) #define TG3_DMA_BYTE_ENAB 64 #define TG3_RX_STD_DMA_SZ 1536 #define TG3_RX_JMB_DMA_SZ 9046 #define TG3_RX_DMA_TO_MAP_SZ(x) ((x) + TG3_DMA_BYTE_ENAB) #define TG3_RX_STD_MAP_SZ TG3_RX_DMA_TO_MAP_SZ(TG3_RX_STD_DMA_SZ) #define TG3_RX_JMB_MAP_SZ TG3_RX_DMA_TO_MAP_SZ(TG3_RX_JMB_DMA_SZ) #define TG3_RX_STD_BUFF_RING_SIZE(tp) \ (sizeof(struct ring_info) * TG3_RX_STD_RING_SIZE(tp)) #define TG3_RX_JMB_BUFF_RING_SIZE(tp) \ (sizeof(struct ring_info) * TG3_RX_JMB_RING_SIZE(tp)) /* Due to a hardware bug, the 5701 can only DMA to memory addresses * that are at least dword aligned when used in PCIX mode. The driver * works around this bug by double copying the packet. This workaround * is built into the normal double copy length check for efficiency. * * However, the double copy is only necessary on those architectures * where unaligned memory accesses are inefficient. For those architectures * where unaligned memory accesses incur little penalty, we can reintegrate * the 5701 in the normal rx path. Doing so saves a device structure * dereference by hardcoding the double copy threshold in place. */ #define TG3_RX_COPY_THRESHOLD 256 #if NET_IP_ALIGN == 0 || defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) #define TG3_RX_COPY_THRESH(tp) TG3_RX_COPY_THRESHOLD #else #define TG3_RX_COPY_THRESH(tp) ((tp)->rx_copy_thresh) #endif #if (NET_IP_ALIGN != 0) #define TG3_RX_OFFSET(tp) ((tp)->rx_offset) #else #define TG3_RX_OFFSET(tp) (NET_SKB_PAD) #endif /* minimum number of free TX descriptors required to wake up TX process */ #define TG3_TX_WAKEUP_THRESH(tnapi) ((tnapi)->tx_pending / 4) #define TG3_TX_BD_DMA_MAX_2K 2048 #define TG3_TX_BD_DMA_MAX_4K 4096 #define TG3_RAW_IP_ALIGN 2 #define TG3_FW_UPDATE_TIMEOUT_SEC 5 #define TG3_FW_UPDATE_FREQ_SEC (TG3_FW_UPDATE_TIMEOUT_SEC / 2) #define FIRMWARE_TG3 "tigon/tg3.bin" #define FIRMWARE_TG3TSO "tigon/tg3_tso.bin" #define FIRMWARE_TG3TSO5 "tigon/tg3_tso5.bin" static char version[] = DRV_MODULE_NAME ".c:v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")"; MODULE_AUTHOR("David S. Miller (davem@redhat.com) and Jeff Garzik (jgarzik@pobox.com)"); MODULE_DESCRIPTION("Broadcom Tigon3 ethernet driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_MODULE_VERSION); MODULE_FIRMWARE(FIRMWARE_TG3); MODULE_FIRMWARE(FIRMWARE_TG3TSO); MODULE_FIRMWARE(FIRMWARE_TG3TSO5); static int tg3_debug = -1; /* -1 == use TG3_DEF_MSG_ENABLE as value */ module_param(tg3_debug, int, 0); MODULE_PARM_DESC(tg3_debug, "Tigon3 bitmapped debugging message enable value"); #define TG3_DRV_DATA_FLAG_10_100_ONLY 0x0001 #define TG3_DRV_DATA_FLAG_5705_10_100 0x0002 static DEFINE_PCI_DEVICE_TABLE(tg3_pci_tbl) = { {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5700)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5701)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702FE)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705_2)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705M_2)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702X)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703X)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704S)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702A3)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703A3)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5782)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5788)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5789)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5901), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY | TG3_DRV_DATA_FLAG_5705_10_100}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5901_2), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY | TG3_DRV_DATA_FLAG_5705_10_100}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704S_2)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705F), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY | TG3_DRV_DATA_FLAG_5705_10_100}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5721)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5722)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5750)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751F), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5752)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5752M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753F), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5754)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5754M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5755)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5755M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5756)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5786)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787)}, {PCI_DEVICE_SUB(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5787M, PCI_VENDOR_ID_LENOVO, TG3PCI_SUBDEVICE_ID_LENOVO_5787M), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787F), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714S)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715S)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780S)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5781)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5906)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5906M)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5784)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5764)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5723)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5761)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5761E)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5761S)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5761SE)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5785_G)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5785_F)}, {PCI_DEVICE_SUB(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780, PCI_VENDOR_ID_AI, TG3PCI_SUBDEVICE_ID_ACER_57780_A), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE_SUB(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780, PCI_VENDOR_ID_AI, TG3PCI_SUBDEVICE_ID_ACER_57780_B), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57760)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57790), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57788)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5717)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5717_C)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5718)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57781)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57785)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57761)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57765)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57791), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57795), .driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5719)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5720)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57762)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57766)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5762)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5725)}, {PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5727)}, {PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, PCI_DEVICE_ID_SYSKONNECT_9DXX)}, {PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, PCI_DEVICE_ID_SYSKONNECT_9MXX)}, {PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1000)}, {PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1001)}, {PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1003)}, {PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC9100)}, {PCI_DEVICE(PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_TIGON3)}, {PCI_DEVICE(0x10cf, 0x11a2)}, /* Fujitsu 1000base-SX with BCM5703SKHB */ {} }; MODULE_DEVICE_TABLE(pci, tg3_pci_tbl); static const struct { const char string[ETH_GSTRING_LEN]; } ethtool_stats_keys[] = { { "rx_octets" }, { "rx_fragments" }, { "rx_ucast_packets" }, { "rx_mcast_packets" }, { "rx_bcast_packets" }, { "rx_fcs_errors" }, { "rx_align_errors" }, { "rx_xon_pause_rcvd" }, { "rx_xoff_pause_rcvd" }, { "rx_mac_ctrl_rcvd" }, { "rx_xoff_entered" }, { "rx_frame_too_long_errors" }, { "rx_jabbers" }, { "rx_undersize_packets" }, { "rx_in_length_errors" }, { "rx_out_length_errors" }, { "rx_64_or_less_octet_packets" }, { "rx_65_to_127_octet_packets" }, { "rx_128_to_255_octet_packets" }, { "rx_256_to_511_octet_packets" }, { "rx_512_to_1023_octet_packets" }, { "rx_1024_to_1522_octet_packets" }, { "rx_1523_to_2047_octet_packets" }, { "rx_2048_to_4095_octet_packets" }, { "rx_4096_to_8191_octet_packets" }, { "rx_8192_to_9022_octet_packets" }, { "tx_octets" }, { "tx_collisions" }, { "tx_xon_sent" }, { "tx_xoff_sent" }, { "tx_flow_control" }, { "tx_mac_errors" }, { "tx_single_collisions" }, { "tx_mult_collisions" }, { "tx_deferred" }, { "tx_excessive_collisions" }, { "tx_late_collisions" }, { "tx_collide_2times" }, { "tx_collide_3times" }, { "tx_collide_4times" }, { "tx_collide_5times" }, { "tx_collide_6times" }, { "tx_collide_7times" }, { "tx_collide_8times" }, { "tx_collide_9times" }, { "tx_collide_10times" }, { "tx_collide_11times" }, { "tx_collide_12times" }, { "tx_collide_13times" }, { "tx_collide_14times" }, { "tx_collide_15times" }, { "tx_ucast_packets" }, { "tx_mcast_packets" }, { "tx_bcast_packets" }, { "tx_carrier_sense_errors" }, { "tx_discards" }, { "tx_errors" }, { "dma_writeq_full" }, { "dma_write_prioq_full" }, { "rxbds_empty" }, { "rx_discards" }, { "rx_errors" }, { "rx_threshold_hit" }, { "dma_readq_full" }, { "dma_read_prioq_full" }, { "tx_comp_queue_full" }, { "ring_set_send_prod_index" }, { "ring_status_update" }, { "nic_irqs" }, { "nic_avoided_irqs" }, { "nic_tx_threshold_hit" }, { "mbuf_lwm_thresh_hit" }, }; #define TG3_NUM_STATS ARRAY_SIZE(ethtool_stats_keys) #define TG3_NVRAM_TEST 0 #define TG3_LINK_TEST 1 #define TG3_REGISTER_TEST 2 #define TG3_MEMORY_TEST 3 #define TG3_MAC_LOOPB_TEST 4 #define TG3_PHY_LOOPB_TEST 5 #define TG3_EXT_LOOPB_TEST 6 #define TG3_INTERRUPT_TEST 7 static const struct { const char string[ETH_GSTRING_LEN]; } ethtool_test_keys[] = { [TG3_NVRAM_TEST] = { "nvram test (online) " }, [TG3_LINK_TEST] = { "link test (online) " }, [TG3_REGISTER_TEST] = { "register test (offline)" }, [TG3_MEMORY_TEST] = { "memory test (offline)" }, [TG3_MAC_LOOPB_TEST] = { "mac loopback test (offline)" }, [TG3_PHY_LOOPB_TEST] = { "phy loopback test (offline)" }, [TG3_EXT_LOOPB_TEST] = { "ext loopback test (offline)" }, [TG3_INTERRUPT_TEST] = { "interrupt test (offline)" }, }; #define TG3_NUM_TEST ARRAY_SIZE(ethtool_test_keys) static void tg3_write32(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->regs + off); } static u32 tg3_read32(struct tg3 *tp, u32 off) { return readl(tp->regs + off); } static void tg3_ape_write32(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->aperegs + off); } static u32 tg3_ape_read32(struct tg3 *tp, u32 off) { return readl(tp->aperegs + off); } static void tg3_write_indirect_reg32(struct tg3 *tp, u32 off, u32 val) { unsigned long flags; spin_lock_irqsave(&tp->indirect_lock, flags); pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off); pci_write_config_dword(tp->pdev, TG3PCI_REG_DATA, val); spin_unlock_irqrestore(&tp->indirect_lock, flags); } static void tg3_write_flush_reg32(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->regs + off); readl(tp->regs + off); } static u32 tg3_read_indirect_reg32(struct tg3 *tp, u32 off) { unsigned long flags; u32 val; spin_lock_irqsave(&tp->indirect_lock, flags); pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off); pci_read_config_dword(tp->pdev, TG3PCI_REG_DATA, &val); spin_unlock_irqrestore(&tp->indirect_lock, flags); return val; } static void tg3_write_indirect_mbox(struct tg3 *tp, u32 off, u32 val) { unsigned long flags; if (off == (MAILBOX_RCVRET_CON_IDX_0 + TG3_64BIT_REG_LOW)) { pci_write_config_dword(tp->pdev, TG3PCI_RCV_RET_RING_CON_IDX + TG3_64BIT_REG_LOW, val); return; } if (off == TG3_RX_STD_PROD_IDX_REG) { pci_write_config_dword(tp->pdev, TG3PCI_STD_RING_PROD_IDX + TG3_64BIT_REG_LOW, val); return; } spin_lock_irqsave(&tp->indirect_lock, flags); pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off + 0x5600); pci_write_config_dword(tp->pdev, TG3PCI_REG_DATA, val); spin_unlock_irqrestore(&tp->indirect_lock, flags); /* In indirect mode when disabling interrupts, we also need * to clear the interrupt bit in the GRC local ctrl register. */ if ((off == (MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW)) && (val == 0x1)) { pci_write_config_dword(tp->pdev, TG3PCI_MISC_LOCAL_CTRL, tp->grc_local_ctrl|GRC_LCLCTRL_CLEARINT); } } static u32 tg3_read_indirect_mbox(struct tg3 *tp, u32 off) { unsigned long flags; u32 val; spin_lock_irqsave(&tp->indirect_lock, flags); pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off + 0x5600); pci_read_config_dword(tp->pdev, TG3PCI_REG_DATA, &val); spin_unlock_irqrestore(&tp->indirect_lock, flags); return val; } /* usec_wait specifies the wait time in usec when writing to certain registers * where it is unsafe to read back the register without some delay. * GRC_LOCAL_CTRL is one example if the GPIOs are toggled to switch power. * TG3PCI_CLOCK_CTRL is another example if the clock frequencies are changed. */ static void _tw32_flush(struct tg3 *tp, u32 off, u32 val, u32 usec_wait) { if (tg3_flag(tp, PCIX_TARGET_HWBUG) || tg3_flag(tp, ICH_WORKAROUND)) /* Non-posted methods */ tp->write32(tp, off, val); else { /* Posted method */ tg3_write32(tp, off, val); if (usec_wait) udelay(usec_wait); tp->read32(tp, off); } /* Wait again after the read for the posted method to guarantee that * the wait time is met. */ if (usec_wait) udelay(usec_wait); } static inline void tw32_mailbox_flush(struct tg3 *tp, u32 off, u32 val) { tp->write32_mbox(tp, off, val); if (tg3_flag(tp, FLUSH_POSTED_WRITES) || (!tg3_flag(tp, MBOX_WRITE_REORDER) && !tg3_flag(tp, ICH_WORKAROUND))) tp->read32_mbox(tp, off); } static void tg3_write32_tx_mbox(struct tg3 *tp, u32 off, u32 val) { void __iomem *mbox = tp->regs + off; writel(val, mbox); if (tg3_flag(tp, TXD_MBOX_HWBUG)) writel(val, mbox); if (tg3_flag(tp, MBOX_WRITE_REORDER) || tg3_flag(tp, FLUSH_POSTED_WRITES)) readl(mbox); } static u32 tg3_read32_mbox_5906(struct tg3 *tp, u32 off) { return readl(tp->regs + off + GRCMBOX_BASE); } static void tg3_write32_mbox_5906(struct tg3 *tp, u32 off, u32 val) { writel(val, tp->regs + off + GRCMBOX_BASE); } #define tw32_mailbox(reg, val) tp->write32_mbox(tp, reg, val) #define tw32_mailbox_f(reg, val) tw32_mailbox_flush(tp, (reg), (val)) #define tw32_rx_mbox(reg, val) tp->write32_rx_mbox(tp, reg, val) #define tw32_tx_mbox(reg, val) tp->write32_tx_mbox(tp, reg, val) #define tr32_mailbox(reg) tp->read32_mbox(tp, reg) #define tw32(reg, val) tp->write32(tp, reg, val) #define tw32_f(reg, val) _tw32_flush(tp, (reg), (val), 0) #define tw32_wait_f(reg, val, us) _tw32_flush(tp, (reg), (val), (us)) #define tr32(reg) tp->read32(tp, reg) static void tg3_write_mem(struct tg3 *tp, u32 off, u32 val) { unsigned long flags; if (tg3_asic_rev(tp) == ASIC_REV_5906 && (off >= NIC_SRAM_STATS_BLK) && (off < NIC_SRAM_TX_BUFFER_DESC)) return; spin_lock_irqsave(&tp->indirect_lock, flags); if (tg3_flag(tp, SRAM_USE_CONFIG)) { pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, off); pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val); /* Always leave this as zero. */ pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0); } else { tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, off); tw32_f(TG3PCI_MEM_WIN_DATA, val); /* Always leave this as zero. */ tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, 0); } spin_unlock_irqrestore(&tp->indirect_lock, flags); } static void tg3_read_mem(struct tg3 *tp, u32 off, u32 *val) { unsigned long flags; if (tg3_asic_rev(tp) == ASIC_REV_5906 && (off >= NIC_SRAM_STATS_BLK) && (off < NIC_SRAM_TX_BUFFER_DESC)) { *val = 0; return; } spin_lock_irqsave(&tp->indirect_lock, flags); if (tg3_flag(tp, SRAM_USE_CONFIG)) { pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, off); pci_read_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val); /* Always leave this as zero. */ pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0); } else { tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, off); *val = tr32(TG3PCI_MEM_WIN_DATA); /* Always leave this as zero. */ tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, 0); } spin_unlock_irqrestore(&tp->indirect_lock, flags); } static void tg3_ape_lock_init(struct tg3 *tp) { int i; u32 regbase, bit; if (tg3_asic_rev(tp) == ASIC_REV_5761) regbase = TG3_APE_LOCK_GRANT; else regbase = TG3_APE_PER_LOCK_GRANT; /* Make sure the driver hasn't any stale locks. */ for (i = TG3_APE_LOCK_PHY0; i <= TG3_APE_LOCK_GPIO; i++) { switch (i) { case TG3_APE_LOCK_PHY0: case TG3_APE_LOCK_PHY1: case TG3_APE_LOCK_PHY2: case TG3_APE_LOCK_PHY3: bit = APE_LOCK_GRANT_DRIVER; break; default: if (!tp->pci_fn) bit = APE_LOCK_GRANT_DRIVER; else bit = 1 << tp->pci_fn; } tg3_ape_write32(tp, regbase + 4 * i, bit); } } static int tg3_ape_lock(struct tg3 *tp, int locknum) { int i, off; int ret = 0; u32 status, req, gnt, bit; if (!tg3_flag(tp, ENABLE_APE)) return 0; switch (locknum) { case TG3_APE_LOCK_GPIO: if (tg3_asic_rev(tp) == ASIC_REV_5761) return 0; case TG3_APE_LOCK_GRC: case TG3_APE_LOCK_MEM: if (!tp->pci_fn) bit = APE_LOCK_REQ_DRIVER; else bit = 1 << tp->pci_fn; break; case TG3_APE_LOCK_PHY0: case TG3_APE_LOCK_PHY1: case TG3_APE_LOCK_PHY2: case TG3_APE_LOCK_PHY3: bit = APE_LOCK_REQ_DRIVER; break; default: return -EINVAL; } if (tg3_asic_rev(tp) == ASIC_REV_5761) { req = TG3_APE_LOCK_REQ; gnt = TG3_APE_LOCK_GRANT; } else { req = TG3_APE_PER_LOCK_REQ; gnt = TG3_APE_PER_LOCK_GRANT; } off = 4 * locknum; tg3_ape_write32(tp, req + off, bit); /* Wait for up to 1 millisecond to acquire lock. */ for (i = 0; i < 100; i++) { status = tg3_ape_read32(tp, gnt + off); if (status == bit) break; udelay(10); } if (status != bit) { /* Revoke the lock request. */ tg3_ape_write32(tp, gnt + off, bit); ret = -EBUSY; } return ret; } static void tg3_ape_unlock(struct tg3 *tp, int locknum) { u32 gnt, bit; if (!tg3_flag(tp, ENABLE_APE)) return; switch (locknum) { case TG3_APE_LOCK_GPIO: if (tg3_asic_rev(tp) == ASIC_REV_5761) return; case TG3_APE_LOCK_GRC: case TG3_APE_LOCK_MEM: if (!tp->pci_fn) bit = APE_LOCK_GRANT_DRIVER; else bit = 1 << tp->pci_fn; break; case TG3_APE_LOCK_PHY0: case TG3_APE_LOCK_PHY1: case TG3_APE_LOCK_PHY2: case TG3_APE_LOCK_PHY3: bit = APE_LOCK_GRANT_DRIVER; break; default: return; } if (tg3_asic_rev(tp) == ASIC_REV_5761) gnt = TG3_APE_LOCK_GRANT; else gnt = TG3_APE_PER_LOCK_GRANT; tg3_ape_write32(tp, gnt + 4 * locknum, bit); } static int tg3_ape_event_lock(struct tg3 *tp, u32 timeout_us) { u32 apedata; while (timeout_us) { if (tg3_ape_lock(tp, TG3_APE_LOCK_MEM)) return -EBUSY; apedata = tg3_ape_read32(tp, TG3_APE_EVENT_STATUS); if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING)) break; tg3_ape_unlock(tp, TG3_APE_LOCK_MEM); udelay(10); timeout_us -= (timeout_us > 10) ? 10 : timeout_us; } return timeout_us ? 0 : -EBUSY; } static int tg3_ape_wait_for_event(struct tg3 *tp, u32 timeout_us) { u32 i, apedata; for (i = 0; i < timeout_us / 10; i++) { apedata = tg3_ape_read32(tp, TG3_APE_EVENT_STATUS); if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING)) break; udelay(10); } return i == timeout_us / 10; } static int tg3_ape_scratchpad_read(struct tg3 *tp, u32 *data, u32 base_off, u32 len) { int err; u32 i, bufoff, msgoff, maxlen, apedata; if (!tg3_flag(tp, APE_HAS_NCSI)) return 0; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) return -ENODEV; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return -EAGAIN; bufoff = tg3_ape_read32(tp, TG3_APE_SEG_MSG_BUF_OFF) + TG3_APE_SHMEM_BASE; msgoff = bufoff + 2 * sizeof(u32); maxlen = tg3_ape_read32(tp, TG3_APE_SEG_MSG_BUF_LEN); while (len) { u32 length; /* Cap xfer sizes to scratchpad limits. */ length = (len > maxlen) ? maxlen : len; len -= length; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return -EAGAIN; /* Wait for up to 1 msec for APE to service previous event. */ err = tg3_ape_event_lock(tp, 1000); if (err) return err; apedata = APE_EVENT_STATUS_DRIVER_EVNT | APE_EVENT_STATUS_SCRTCHPD_READ | APE_EVENT_STATUS_EVENT_PENDING; tg3_ape_write32(tp, TG3_APE_EVENT_STATUS, apedata); tg3_ape_write32(tp, bufoff, base_off); tg3_ape_write32(tp, bufoff + sizeof(u32), length); tg3_ape_unlock(tp, TG3_APE_LOCK_MEM); tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1); base_off += length; if (tg3_ape_wait_for_event(tp, 30000)) return -EAGAIN; for (i = 0; length; i += 4, length -= 4) { u32 val = tg3_ape_read32(tp, msgoff + i); memcpy(data, &val, sizeof(u32)); data++; } } return 0; } static int tg3_ape_send_event(struct tg3 *tp, u32 event) { int err; u32 apedata; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) return -EAGAIN; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return -EAGAIN; /* Wait for up to 1 millisecond for APE to service previous event. */ err = tg3_ape_event_lock(tp, 1000); if (err) return err; tg3_ape_write32(tp, TG3_APE_EVENT_STATUS, event | APE_EVENT_STATUS_EVENT_PENDING); tg3_ape_unlock(tp, TG3_APE_LOCK_MEM); tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1); return 0; } static void tg3_ape_driver_state_change(struct tg3 *tp, int kind) { u32 event; u32 apedata; if (!tg3_flag(tp, ENABLE_APE)) return; switch (kind) { case RESET_KIND_INIT: tg3_ape_write32(tp, TG3_APE_HOST_SEG_SIG, APE_HOST_SEG_SIG_MAGIC); tg3_ape_write32(tp, TG3_APE_HOST_SEG_LEN, APE_HOST_SEG_LEN_MAGIC); apedata = tg3_ape_read32(tp, TG3_APE_HOST_INIT_COUNT); tg3_ape_write32(tp, TG3_APE_HOST_INIT_COUNT, ++apedata); tg3_ape_write32(tp, TG3_APE_HOST_DRIVER_ID, APE_HOST_DRIVER_ID_MAGIC(TG3_MAJ_NUM, TG3_MIN_NUM)); tg3_ape_write32(tp, TG3_APE_HOST_BEHAVIOR, APE_HOST_BEHAV_NO_PHYLOCK); tg3_ape_write32(tp, TG3_APE_HOST_DRVR_STATE, TG3_APE_HOST_DRVR_STATE_START); event = APE_EVENT_STATUS_STATE_START; break; case RESET_KIND_SHUTDOWN: /* With the interface we are currently using, * APE does not track driver state. Wiping * out the HOST SEGMENT SIGNATURE forces * the APE to assume OS absent status. */ tg3_ape_write32(tp, TG3_APE_HOST_SEG_SIG, 0x0); if (device_may_wakeup(&tp->pdev->dev) && tg3_flag(tp, WOL_ENABLE)) { tg3_ape_write32(tp, TG3_APE_HOST_WOL_SPEED, TG3_APE_HOST_WOL_SPEED_AUTO); apedata = TG3_APE_HOST_DRVR_STATE_WOL; } else apedata = TG3_APE_HOST_DRVR_STATE_UNLOAD; tg3_ape_write32(tp, TG3_APE_HOST_DRVR_STATE, apedata); event = APE_EVENT_STATUS_STATE_UNLOAD; break; case RESET_KIND_SUSPEND: event = APE_EVENT_STATUS_STATE_SUSPEND; break; default: return; } event |= APE_EVENT_STATUS_DRIVER_EVNT | APE_EVENT_STATUS_STATE_CHNGE; tg3_ape_send_event(tp, event); } static void tg3_disable_ints(struct tg3 *tp) { int i; tw32(TG3PCI_MISC_HOST_CTRL, (tp->misc_host_ctrl | MISC_HOST_CTRL_MASK_PCI_INT)); for (i = 0; i < tp->irq_max; i++) tw32_mailbox_f(tp->napi[i].int_mbox, 0x00000001); } static void tg3_enable_ints(struct tg3 *tp) { int i; tp->irq_sync = 0; wmb(); tw32(TG3PCI_MISC_HOST_CTRL, (tp->misc_host_ctrl & ~MISC_HOST_CTRL_MASK_PCI_INT)); tp->coal_now = tp->coalesce_mode | HOSTCC_MODE_ENABLE; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24); if (tg3_flag(tp, 1SHOT_MSI)) tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24); tp->coal_now |= tnapi->coal_now; } /* Force an initial interrupt */ if (!tg3_flag(tp, TAGGED_STATUS) && (tp->napi[0].hw_status->status & SD_STATUS_UPDATED)) tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl | GRC_LCLCTRL_SETINT); else tw32(HOSTCC_MODE, tp->coal_now); tp->coal_now &= ~(tp->napi[0].coal_now | tp->napi[1].coal_now); } static inline unsigned int tg3_has_work(struct tg3_napi *tnapi) { struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; unsigned int work_exists = 0; /* check for phy events */ if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) { if (sblk->status & SD_STATUS_LINK_CHG) work_exists = 1; } /* check for TX work to do */ if (sblk->idx[0].tx_consumer != tnapi->tx_cons) work_exists = 1; /* check for RX work to do */ if (tnapi->rx_rcb_prod_idx && *(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr) work_exists = 1; return work_exists; } /* tg3_int_reenable * similar to tg3_enable_ints, but it accurately determines whether there * is new work pending and can return without flushing the PIO write * which reenables interrupts */ static void tg3_int_reenable(struct tg3_napi *tnapi) { struct tg3 *tp = tnapi->tp; tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24); mmiowb(); /* When doing tagged status, this work check is unnecessary. * The last_tag we write above tells the chip which piece of * work we've completed. */ if (!tg3_flag(tp, TAGGED_STATUS) && tg3_has_work(tnapi)) tw32(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | tnapi->coal_now); } static void tg3_switch_clocks(struct tg3 *tp) { u32 clock_ctrl; u32 orig_clock_ctrl; if (tg3_flag(tp, CPMU_PRESENT) || tg3_flag(tp, 5780_CLASS)) return; clock_ctrl = tr32(TG3PCI_CLOCK_CTRL); orig_clock_ctrl = clock_ctrl; clock_ctrl &= (CLOCK_CTRL_FORCE_CLKRUN | CLOCK_CTRL_CLKRUN_OENABLE | 0x1f); tp->pci_clock_ctrl = clock_ctrl; if (tg3_flag(tp, 5705_PLUS)) { if (orig_clock_ctrl & CLOCK_CTRL_625_CORE) { tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl | CLOCK_CTRL_625_CORE, 40); } } else if ((orig_clock_ctrl & CLOCK_CTRL_44MHZ_CORE) != 0) { tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl | (CLOCK_CTRL_44MHZ_CORE | CLOCK_CTRL_ALTCLK), 40); tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl | (CLOCK_CTRL_ALTCLK), 40); } tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl, 40); } #define PHY_BUSY_LOOPS 5000 static int __tg3_readphy(struct tg3 *tp, unsigned int phy_addr, int reg, u32 *val) { u32 frame_val; unsigned int loops; int ret; if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) { tw32_f(MAC_MI_MODE, (tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL)); udelay(80); } tg3_ape_lock(tp, tp->phy_ape_lock); *val = 0x0; frame_val = ((phy_addr << MI_COM_PHY_ADDR_SHIFT) & MI_COM_PHY_ADDR_MASK); frame_val |= ((reg << MI_COM_REG_ADDR_SHIFT) & MI_COM_REG_ADDR_MASK); frame_val |= (MI_COM_CMD_READ | MI_COM_START); tw32_f(MAC_MI_COM, frame_val); loops = PHY_BUSY_LOOPS; while (loops != 0) { udelay(10); frame_val = tr32(MAC_MI_COM); if ((frame_val & MI_COM_BUSY) == 0) { udelay(5); frame_val = tr32(MAC_MI_COM); break; } loops -= 1; } ret = -EBUSY; if (loops != 0) { *val = frame_val & MI_COM_DATA_MASK; ret = 0; } if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) { tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); } tg3_ape_unlock(tp, tp->phy_ape_lock); return ret; } static int tg3_readphy(struct tg3 *tp, int reg, u32 *val) { return __tg3_readphy(tp, tp->phy_addr, reg, val); } static int __tg3_writephy(struct tg3 *tp, unsigned int phy_addr, int reg, u32 val) { u32 frame_val; unsigned int loops; int ret; if ((tp->phy_flags & TG3_PHYFLG_IS_FET) && (reg == MII_CTRL1000 || reg == MII_TG3_AUX_CTRL)) return 0; if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) { tw32_f(MAC_MI_MODE, (tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL)); udelay(80); } tg3_ape_lock(tp, tp->phy_ape_lock); frame_val = ((phy_addr << MI_COM_PHY_ADDR_SHIFT) & MI_COM_PHY_ADDR_MASK); frame_val |= ((reg << MI_COM_REG_ADDR_SHIFT) & MI_COM_REG_ADDR_MASK); frame_val |= (val & MI_COM_DATA_MASK); frame_val |= (MI_COM_CMD_WRITE | MI_COM_START); tw32_f(MAC_MI_COM, frame_val); loops = PHY_BUSY_LOOPS; while (loops != 0) { udelay(10); frame_val = tr32(MAC_MI_COM); if ((frame_val & MI_COM_BUSY) == 0) { udelay(5); frame_val = tr32(MAC_MI_COM); break; } loops -= 1; } ret = -EBUSY; if (loops != 0) ret = 0; if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) { tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); } tg3_ape_unlock(tp, tp->phy_ape_lock); return ret; } static int tg3_writephy(struct tg3 *tp, int reg, u32 val) { return __tg3_writephy(tp, tp->phy_addr, reg, val); } static int tg3_phy_cl45_write(struct tg3 *tp, u32 devad, u32 addr, u32 val) { int err; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, MII_TG3_MMD_CTRL_DATA_NOINC | devad); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, val); done: return err; } static int tg3_phy_cl45_read(struct tg3 *tp, u32 devad, u32 addr, u32 *val) { int err; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr); if (err) goto done; err = tg3_writephy(tp, MII_TG3_MMD_CTRL, MII_TG3_MMD_CTRL_DATA_NOINC | devad); if (err) goto done; err = tg3_readphy(tp, MII_TG3_MMD_ADDRESS, val); done: return err; } static int tg3_phydsp_read(struct tg3 *tp, u32 reg, u32 *val) { int err; err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg); if (!err) err = tg3_readphy(tp, MII_TG3_DSP_RW_PORT, val); return err; } static int tg3_phydsp_write(struct tg3 *tp, u32 reg, u32 val) { int err; err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg); if (!err) err = tg3_writephy(tp, MII_TG3_DSP_RW_PORT, val); return err; } static int tg3_phy_auxctl_read(struct tg3 *tp, int reg, u32 *val) { int err; err = tg3_writephy(tp, MII_TG3_AUX_CTRL, (reg << MII_TG3_AUXCTL_MISC_RDSEL_SHIFT) | MII_TG3_AUXCTL_SHDWSEL_MISC); if (!err) err = tg3_readphy(tp, MII_TG3_AUX_CTRL, val); return err; } static int tg3_phy_auxctl_write(struct tg3 *tp, int reg, u32 set) { if (reg == MII_TG3_AUXCTL_SHDWSEL_MISC) set |= MII_TG3_AUXCTL_MISC_WREN; return tg3_writephy(tp, MII_TG3_AUX_CTRL, set | reg); } static int tg3_phy_toggle_auxctl_smdsp(struct tg3 *tp, bool enable) { u32 val; int err; err = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val); if (err) return err; if (enable) val |= MII_TG3_AUXCTL_ACTL_SMDSP_ENA; else val &= ~MII_TG3_AUXCTL_ACTL_SMDSP_ENA; err = tg3_phy_auxctl_write((tp), MII_TG3_AUXCTL_SHDWSEL_AUXCTL, val | MII_TG3_AUXCTL_ACTL_TX_6DB); return err; } static int tg3_bmcr_reset(struct tg3 *tp) { u32 phy_control; int limit, err; /* OK, reset it, and poll the BMCR_RESET bit until it * clears or we time out. */ phy_control = BMCR_RESET; err = tg3_writephy(tp, MII_BMCR, phy_control); if (err != 0) return -EBUSY; limit = 5000; while (limit--) { err = tg3_readphy(tp, MII_BMCR, &phy_control); if (err != 0) return -EBUSY; if ((phy_control & BMCR_RESET) == 0) { udelay(40); break; } udelay(10); } if (limit < 0) return -EBUSY; return 0; } static int tg3_mdio_read(struct mii_bus *bp, int mii_id, int reg) { struct tg3 *tp = bp->priv; u32 val; spin_lock_bh(&tp->lock); if (tg3_readphy(tp, reg, &val)) val = -EIO; spin_unlock_bh(&tp->lock); return val; } static int tg3_mdio_write(struct mii_bus *bp, int mii_id, int reg, u16 val) { struct tg3 *tp = bp->priv; u32 ret = 0; spin_lock_bh(&tp->lock); if (tg3_writephy(tp, reg, val)) ret = -EIO; spin_unlock_bh(&tp->lock); return ret; } static int tg3_mdio_reset(struct mii_bus *bp) { return 0; } static void tg3_mdio_config_5785(struct tg3 *tp) { u32 val; struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) { case PHY_ID_BCM50610: case PHY_ID_BCM50610M: val = MAC_PHYCFG2_50610_LED_MODES; break; case PHY_ID_BCMAC131: val = MAC_PHYCFG2_AC131_LED_MODES; break; case PHY_ID_RTL8211C: val = MAC_PHYCFG2_RTL8211C_LED_MODES; break; case PHY_ID_RTL8201E: val = MAC_PHYCFG2_RTL8201E_LED_MODES; break; default: return; } if (phydev->interface != PHY_INTERFACE_MODE_RGMII) { tw32(MAC_PHYCFG2, val); val = tr32(MAC_PHYCFG1); val &= ~(MAC_PHYCFG1_RGMII_INT | MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK); val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT; tw32(MAC_PHYCFG1, val); return; } if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) val |= MAC_PHYCFG2_EMODE_MASK_MASK | MAC_PHYCFG2_FMODE_MASK_MASK | MAC_PHYCFG2_GMODE_MASK_MASK | MAC_PHYCFG2_ACT_MASK_MASK | MAC_PHYCFG2_QUAL_MASK_MASK | MAC_PHYCFG2_INBAND_ENABLE; tw32(MAC_PHYCFG2, val); val = tr32(MAC_PHYCFG1); val &= ~(MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK | MAC_PHYCFG1_RGMII_EXT_RX_DEC | MAC_PHYCFG1_RGMII_SND_STAT_EN); if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) { if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN)) val |= MAC_PHYCFG1_RGMII_EXT_RX_DEC; if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN)) val |= MAC_PHYCFG1_RGMII_SND_STAT_EN; } val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT | MAC_PHYCFG1_RGMII_INT | MAC_PHYCFG1_TXC_DRV; tw32(MAC_PHYCFG1, val); val = tr32(MAC_EXT_RGMII_MODE); val &= ~(MAC_RGMII_MODE_RX_INT_B | MAC_RGMII_MODE_RX_QUALITY | MAC_RGMII_MODE_RX_ACTIVITY | MAC_RGMII_MODE_RX_ENG_DET | MAC_RGMII_MODE_TX_ENABLE | MAC_RGMII_MODE_TX_LOWPWR | MAC_RGMII_MODE_TX_RESET); if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) { if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN)) val |= MAC_RGMII_MODE_RX_INT_B | MAC_RGMII_MODE_RX_QUALITY | MAC_RGMII_MODE_RX_ACTIVITY | MAC_RGMII_MODE_RX_ENG_DET; if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN)) val |= MAC_RGMII_MODE_TX_ENABLE | MAC_RGMII_MODE_TX_LOWPWR | MAC_RGMII_MODE_TX_RESET; } tw32(MAC_EXT_RGMII_MODE, val); } static void tg3_mdio_start(struct tg3 *tp) { tp->mi_mode &= ~MAC_MI_MODE_AUTO_POLL; tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); if (tg3_flag(tp, MDIOBUS_INITED) && tg3_asic_rev(tp) == ASIC_REV_5785) tg3_mdio_config_5785(tp); } static int tg3_mdio_init(struct tg3 *tp) { int i; u32 reg; struct phy_device *phydev; if (tg3_flag(tp, 5717_PLUS)) { u32 is_serdes; tp->phy_addr = tp->pci_fn + 1; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5717_A0) is_serdes = tr32(SG_DIG_STATUS) & SG_DIG_IS_SERDES; else is_serdes = tr32(TG3_CPMU_PHY_STRAP) & TG3_CPMU_PHY_STRAP_IS_SERDES; if (is_serdes) tp->phy_addr += 7; } else tp->phy_addr = TG3_PHY_MII_ADDR; tg3_mdio_start(tp); if (!tg3_flag(tp, USE_PHYLIB) || tg3_flag(tp, MDIOBUS_INITED)) return 0; tp->mdio_bus = mdiobus_alloc(); if (tp->mdio_bus == NULL) return -ENOMEM; tp->mdio_bus->name = "tg3 mdio bus"; snprintf(tp->mdio_bus->id, MII_BUS_ID_SIZE, "%x", (tp->pdev->bus->number << 8) | tp->pdev->devfn); tp->mdio_bus->priv = tp; tp->mdio_bus->parent = &tp->pdev->dev; tp->mdio_bus->read = &tg3_mdio_read; tp->mdio_bus->write = &tg3_mdio_write; tp->mdio_bus->reset = &tg3_mdio_reset; tp->mdio_bus->phy_mask = ~(1 << TG3_PHY_MII_ADDR); tp->mdio_bus->irq = &tp->mdio_irq[0]; for (i = 0; i < PHY_MAX_ADDR; i++) tp->mdio_bus->irq[i] = PHY_POLL; /* The bus registration will look for all the PHYs on the mdio bus. * Unfortunately, it does not ensure the PHY is powered up before * accessing the PHY ID registers. A chip reset is the * quickest way to bring the device back to an operational state.. */ if (tg3_readphy(tp, MII_BMCR, &reg) || (reg & BMCR_PDOWN)) tg3_bmcr_reset(tp); i = mdiobus_register(tp->mdio_bus); if (i) { dev_warn(&tp->pdev->dev, "mdiobus_reg failed (0x%x)\n", i); mdiobus_free(tp->mdio_bus); return i; } phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; if (!phydev || !phydev->drv) { dev_warn(&tp->pdev->dev, "No PHY devices\n"); mdiobus_unregister(tp->mdio_bus); mdiobus_free(tp->mdio_bus); return -ENODEV; } switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) { case PHY_ID_BCM57780: phydev->interface = PHY_INTERFACE_MODE_GMII; phydev->dev_flags |= PHY_BRCM_AUTO_PWRDWN_ENABLE; break; case PHY_ID_BCM50610: case PHY_ID_BCM50610M: phydev->dev_flags |= PHY_BRCM_CLEAR_RGMII_MODE | PHY_BRCM_RX_REFCLK_UNUSED | PHY_BRCM_DIS_TXCRXC_NOENRGY | PHY_BRCM_AUTO_PWRDWN_ENABLE; if (tg3_flag(tp, RGMII_INBAND_DISABLE)) phydev->dev_flags |= PHY_BRCM_STD_IBND_DISABLE; if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN)) phydev->dev_flags |= PHY_BRCM_EXT_IBND_RX_ENABLE; if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN)) phydev->dev_flags |= PHY_BRCM_EXT_IBND_TX_ENABLE; /* fallthru */ case PHY_ID_RTL8211C: phydev->interface = PHY_INTERFACE_MODE_RGMII; break; case PHY_ID_RTL8201E: case PHY_ID_BCMAC131: phydev->interface = PHY_INTERFACE_MODE_MII; phydev->dev_flags |= PHY_BRCM_AUTO_PWRDWN_ENABLE; tp->phy_flags |= TG3_PHYFLG_IS_FET; break; } tg3_flag_set(tp, MDIOBUS_INITED); if (tg3_asic_rev(tp) == ASIC_REV_5785) tg3_mdio_config_5785(tp); return 0; } static void tg3_mdio_fini(struct tg3 *tp) { if (tg3_flag(tp, MDIOBUS_INITED)) { tg3_flag_clear(tp, MDIOBUS_INITED); mdiobus_unregister(tp->mdio_bus); mdiobus_free(tp->mdio_bus); } } /* tp->lock is held. */ static inline void tg3_generate_fw_event(struct tg3 *tp) { u32 val; val = tr32(GRC_RX_CPU_EVENT); val |= GRC_RX_CPU_DRIVER_EVENT; tw32_f(GRC_RX_CPU_EVENT, val); tp->last_event_jiffies = jiffies; } #define TG3_FW_EVENT_TIMEOUT_USEC 2500 /* tp->lock is held. */ static void tg3_wait_for_event_ack(struct tg3 *tp) { int i; unsigned int delay_cnt; long time_remain; /* If enough time has passed, no wait is necessary. */ time_remain = (long)(tp->last_event_jiffies + 1 + usecs_to_jiffies(TG3_FW_EVENT_TIMEOUT_USEC)) - (long)jiffies; if (time_remain < 0) return; /* Check if we can shorten the wait time. */ delay_cnt = jiffies_to_usecs(time_remain); if (delay_cnt > TG3_FW_EVENT_TIMEOUT_USEC) delay_cnt = TG3_FW_EVENT_TIMEOUT_USEC; delay_cnt = (delay_cnt >> 3) + 1; for (i = 0; i < delay_cnt; i++) { if (!(tr32(GRC_RX_CPU_EVENT) & GRC_RX_CPU_DRIVER_EVENT)) break; udelay(8); } } /* tp->lock is held. */ static void tg3_phy_gather_ump_data(struct tg3 *tp, u32 *data) { u32 reg, val; val = 0; if (!tg3_readphy(tp, MII_BMCR, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_BMSR, &reg)) val |= (reg & 0xffff); *data++ = val; val = 0; if (!tg3_readphy(tp, MII_ADVERTISE, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_LPA, &reg)) val |= (reg & 0xffff); *data++ = val; val = 0; if (!(tp->phy_flags & TG3_PHYFLG_MII_SERDES)) { if (!tg3_readphy(tp, MII_CTRL1000, &reg)) val = reg << 16; if (!tg3_readphy(tp, MII_STAT1000, &reg)) val |= (reg & 0xffff); } *data++ = val; if (!tg3_readphy(tp, MII_PHYADDR, &reg)) val = reg << 16; else val = 0; *data++ = val; } /* tp->lock is held. */ static void tg3_ump_link_report(struct tg3 *tp) { u32 data[4]; if (!tg3_flag(tp, 5780_CLASS) || !tg3_flag(tp, ENABLE_ASF)) return; tg3_phy_gather_ump_data(tp, data); tg3_wait_for_event_ack(tp); tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_LINK_UPDATE); tg3_write_mem(tp, NIC_SRAM_FW_CMD_LEN_MBOX, 14); tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x0, data[0]); tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x4, data[1]); tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x8, data[2]); tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0xc, data[3]); tg3_generate_fw_event(tp); } /* tp->lock is held. */ static void tg3_stop_fw(struct tg3 *tp) { if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) { /* Wait for RX cpu to ACK the previous event. */ tg3_wait_for_event_ack(tp); tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_PAUSE_FW); tg3_generate_fw_event(tp); /* Wait for RX cpu to ACK this event. */ tg3_wait_for_event_ack(tp); } } /* tp->lock is held. */ static void tg3_write_sig_pre_reset(struct tg3 *tp, int kind) { tg3_write_mem(tp, NIC_SRAM_FIRMWARE_MBOX, NIC_SRAM_FIRMWARE_MBOX_MAGIC1); if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) { switch (kind) { case RESET_KIND_INIT: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_START); break; case RESET_KIND_SHUTDOWN: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_UNLOAD); break; case RESET_KIND_SUSPEND: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_SUSPEND); break; default: break; } } if (kind == RESET_KIND_INIT || kind == RESET_KIND_SUSPEND) tg3_ape_driver_state_change(tp, kind); } /* tp->lock is held. */ static void tg3_write_sig_post_reset(struct tg3 *tp, int kind) { if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) { switch (kind) { case RESET_KIND_INIT: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_START_DONE); break; case RESET_KIND_SHUTDOWN: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_UNLOAD_DONE); break; default: break; } } if (kind == RESET_KIND_SHUTDOWN) tg3_ape_driver_state_change(tp, kind); } /* tp->lock is held. */ static void tg3_write_sig_legacy(struct tg3 *tp, int kind) { if (tg3_flag(tp, ENABLE_ASF)) { switch (kind) { case RESET_KIND_INIT: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_START); break; case RESET_KIND_SHUTDOWN: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_UNLOAD); break; case RESET_KIND_SUSPEND: tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX, DRV_STATE_SUSPEND); break; default: break; } } } static int tg3_poll_fw(struct tg3 *tp) { int i; u32 val; if (tg3_flag(tp, IS_SSB_CORE)) { /* We don't use firmware. */ return 0; } if (tg3_asic_rev(tp) == ASIC_REV_5906) { /* Wait up to 20ms for init done. */ for (i = 0; i < 200; i++) { if (tr32(VCPU_STATUS) & VCPU_STATUS_INIT_DONE) return 0; udelay(100); } return -ENODEV; } /* Wait for firmware initialization to complete. */ for (i = 0; i < 100000; i++) { tg3_read_mem(tp, NIC_SRAM_FIRMWARE_MBOX, &val); if (val == ~NIC_SRAM_FIRMWARE_MBOX_MAGIC1) break; udelay(10); } /* Chip might not be fitted with firmware. Some Sun onboard * parts are configured like that. So don't signal the timeout * of the above loop as an error, but do report the lack of * running firmware once. */ if (i >= 100000 && !tg3_flag(tp, NO_FWARE_REPORTED)) { tg3_flag_set(tp, NO_FWARE_REPORTED); netdev_info(tp->dev, "No firmware running\n"); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) { /* The 57765 A0 needs a little more * time to do some important work. */ mdelay(10); } return 0; } static void tg3_link_report(struct tg3 *tp) { if (!netif_carrier_ok(tp->dev)) { netif_info(tp, link, tp->dev, "Link is down\n"); tg3_ump_link_report(tp); } else if (netif_msg_link(tp)) { netdev_info(tp->dev, "Link is up at %d Mbps, %s duplex\n", (tp->link_config.active_speed == SPEED_1000 ? 1000 : (tp->link_config.active_speed == SPEED_100 ? 100 : 10)), (tp->link_config.active_duplex == DUPLEX_FULL ? "full" : "half")); netdev_info(tp->dev, "Flow control is %s for TX and %s for RX\n", (tp->link_config.active_flowctrl & FLOW_CTRL_TX) ? "on" : "off", (tp->link_config.active_flowctrl & FLOW_CTRL_RX) ? "on" : "off"); if (tp->phy_flags & TG3_PHYFLG_EEE_CAP) netdev_info(tp->dev, "EEE is %s\n", tp->setlpicnt ? "enabled" : "disabled"); tg3_ump_link_report(tp); } tp->link_up = netif_carrier_ok(tp->dev); } static u16 tg3_advert_flowctrl_1000X(u8 flow_ctrl) { u16 miireg; if ((flow_ctrl & FLOW_CTRL_TX) && (flow_ctrl & FLOW_CTRL_RX)) miireg = ADVERTISE_1000XPAUSE; else if (flow_ctrl & FLOW_CTRL_TX) miireg = ADVERTISE_1000XPSE_ASYM; else if (flow_ctrl & FLOW_CTRL_RX) miireg = ADVERTISE_1000XPAUSE | ADVERTISE_1000XPSE_ASYM; else miireg = 0; return miireg; } static u8 tg3_resolve_flowctrl_1000X(u16 lcladv, u16 rmtadv) { u8 cap = 0; if (lcladv & rmtadv & ADVERTISE_1000XPAUSE) { cap = FLOW_CTRL_TX | FLOW_CTRL_RX; } else if (lcladv & rmtadv & ADVERTISE_1000XPSE_ASYM) { if (lcladv & ADVERTISE_1000XPAUSE) cap = FLOW_CTRL_RX; if (rmtadv & ADVERTISE_1000XPAUSE) cap = FLOW_CTRL_TX; } return cap; } static void tg3_setup_flow_control(struct tg3 *tp, u32 lcladv, u32 rmtadv) { u8 autoneg; u8 flowctrl = 0; u32 old_rx_mode = tp->rx_mode; u32 old_tx_mode = tp->tx_mode; if (tg3_flag(tp, USE_PHYLIB)) autoneg = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]->autoneg; else autoneg = tp->link_config.autoneg; if (autoneg == AUTONEG_ENABLE && tg3_flag(tp, PAUSE_AUTONEG)) { if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES) flowctrl = tg3_resolve_flowctrl_1000X(lcladv, rmtadv); else flowctrl = mii_resolve_flowctrl_fdx(lcladv, rmtadv); } else flowctrl = tp->link_config.flowctrl; tp->link_config.active_flowctrl = flowctrl; if (flowctrl & FLOW_CTRL_RX) tp->rx_mode |= RX_MODE_FLOW_CTRL_ENABLE; else tp->rx_mode &= ~RX_MODE_FLOW_CTRL_ENABLE; if (old_rx_mode != tp->rx_mode) tw32_f(MAC_RX_MODE, tp->rx_mode); if (flowctrl & FLOW_CTRL_TX) tp->tx_mode |= TX_MODE_FLOW_CTRL_ENABLE; else tp->tx_mode &= ~TX_MODE_FLOW_CTRL_ENABLE; if (old_tx_mode != tp->tx_mode) tw32_f(MAC_TX_MODE, tp->tx_mode); } static void tg3_adjust_link(struct net_device *dev) { u8 oldflowctrl, linkmesg = 0; u32 mac_mode, lcl_adv, rmt_adv; struct tg3 *tp = netdev_priv(dev); struct phy_device *phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; spin_lock_bh(&tp->lock); mac_mode = tp->mac_mode & ~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX); oldflowctrl = tp->link_config.active_flowctrl; if (phydev->link) { lcl_adv = 0; rmt_adv = 0; if (phydev->speed == SPEED_100 || phydev->speed == SPEED_10) mac_mode |= MAC_MODE_PORT_MODE_MII; else if (phydev->speed == SPEED_1000 || tg3_asic_rev(tp) != ASIC_REV_5785) mac_mode |= MAC_MODE_PORT_MODE_GMII; else mac_mode |= MAC_MODE_PORT_MODE_MII; if (phydev->duplex == DUPLEX_HALF) mac_mode |= MAC_MODE_HALF_DUPLEX; else { lcl_adv = mii_advertise_flowctrl( tp->link_config.flowctrl); if (phydev->pause) rmt_adv = LPA_PAUSE_CAP; if (phydev->asym_pause) rmt_adv |= LPA_PAUSE_ASYM; } tg3_setup_flow_control(tp, lcl_adv, rmt_adv); } else mac_mode |= MAC_MODE_PORT_MODE_GMII; if (mac_mode != tp->mac_mode) { tp->mac_mode = mac_mode; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); } if (tg3_asic_rev(tp) == ASIC_REV_5785) { if (phydev->speed == SPEED_10) tw32(MAC_MI_STAT, MAC_MI_STAT_10MBPS_MODE | MAC_MI_STAT_LNKSTAT_ATTN_ENAB); else tw32(MAC_MI_STAT, MAC_MI_STAT_LNKSTAT_ATTN_ENAB); } if (phydev->speed == SPEED_1000 && phydev->duplex == DUPLEX_HALF) tw32(MAC_TX_LENGTHS, ((2 << TX_LENGTHS_IPG_CRS_SHIFT) | (6 << TX_LENGTHS_IPG_SHIFT) | (0xff << TX_LENGTHS_SLOT_TIME_SHIFT))); else tw32(MAC_TX_LENGTHS, ((2 << TX_LENGTHS_IPG_CRS_SHIFT) | (6 << TX_LENGTHS_IPG_SHIFT) | (32 << TX_LENGTHS_SLOT_TIME_SHIFT))); if (phydev->link != tp->old_link || phydev->speed != tp->link_config.active_speed || phydev->duplex != tp->link_config.active_duplex || oldflowctrl != tp->link_config.active_flowctrl) linkmesg = 1; tp->old_link = phydev->link; tp->link_config.active_speed = phydev->speed; tp->link_config.active_duplex = phydev->duplex; spin_unlock_bh(&tp->lock); if (linkmesg) tg3_link_report(tp); } static int tg3_phy_init(struct tg3 *tp) { struct phy_device *phydev; if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) return 0; /* Bring the PHY back to a known state. */ tg3_bmcr_reset(tp); phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; /* Attach the MAC to the PHY. */ phydev = phy_connect(tp->dev, dev_name(&phydev->dev), tg3_adjust_link, phydev->interface); if (IS_ERR(phydev)) { dev_err(&tp->pdev->dev, "Could not attach to PHY\n"); return PTR_ERR(phydev); } /* Mask with MAC supported features. */ switch (phydev->interface) { case PHY_INTERFACE_MODE_GMII: case PHY_INTERFACE_MODE_RGMII: if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) { phydev->supported &= (PHY_GBIT_FEATURES | SUPPORTED_Pause | SUPPORTED_Asym_Pause); break; } /* fallthru */ case PHY_INTERFACE_MODE_MII: phydev->supported &= (PHY_BASIC_FEATURES | SUPPORTED_Pause | SUPPORTED_Asym_Pause); break; default: phy_disconnect(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]); return -EINVAL; } tp->phy_flags |= TG3_PHYFLG_IS_CONNECTED; phydev->advertising = phydev->supported; return 0; } static void tg3_phy_start(struct tg3 *tp) { struct phy_device *phydev; if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)) return; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) { tp->phy_flags &= ~TG3_PHYFLG_IS_LOW_POWER; phydev->speed = tp->link_config.speed; phydev->duplex = tp->link_config.duplex; phydev->autoneg = tp->link_config.autoneg; phydev->advertising = tp->link_config.advertising; } phy_start(phydev); phy_start_aneg(phydev); } static void tg3_phy_stop(struct tg3 *tp) { if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)) return; phy_stop(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]); } static void tg3_phy_fini(struct tg3 *tp) { if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) { phy_disconnect(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]); tp->phy_flags &= ~TG3_PHYFLG_IS_CONNECTED; } } static int tg3_phy_set_extloopbk(struct tg3 *tp) { int err; u32 val; if (tp->phy_flags & TG3_PHYFLG_IS_FET) return 0; if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { /* Cannot do read-modify-write on 5401 */ err = tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, MII_TG3_AUXCTL_ACTL_EXTLOOPBK | 0x4c20); goto done; } err = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val); if (err) return err; val |= MII_TG3_AUXCTL_ACTL_EXTLOOPBK; err = tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, val); done: return err; } static void tg3_phy_fet_toggle_apd(struct tg3 *tp, bool enable) { u32 phytest; if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) { u32 phy; tg3_writephy(tp, MII_TG3_FET_TEST, phytest | MII_TG3_FET_SHADOW_EN); if (!tg3_readphy(tp, MII_TG3_FET_SHDW_AUXSTAT2, &phy)) { if (enable) phy |= MII_TG3_FET_SHDW_AUXSTAT2_APD; else phy &= ~MII_TG3_FET_SHDW_AUXSTAT2_APD; tg3_writephy(tp, MII_TG3_FET_SHDW_AUXSTAT2, phy); } tg3_writephy(tp, MII_TG3_FET_TEST, phytest); } } static void tg3_phy_toggle_apd(struct tg3 *tp, bool enable) { u32 reg; if (!tg3_flag(tp, 5705_PLUS) || (tg3_flag(tp, 5717_PLUS) && (tp->phy_flags & TG3_PHYFLG_MII_SERDES))) return; if (tp->phy_flags & TG3_PHYFLG_IS_FET) { tg3_phy_fet_toggle_apd(tp, enable); return; } reg = MII_TG3_MISC_SHDW_WREN | MII_TG3_MISC_SHDW_SCR5_SEL | MII_TG3_MISC_SHDW_SCR5_LPED | MII_TG3_MISC_SHDW_SCR5_DLPTLM | MII_TG3_MISC_SHDW_SCR5_SDTL | MII_TG3_MISC_SHDW_SCR5_C125OE; if (tg3_asic_rev(tp) != ASIC_REV_5784 || !enable) reg |= MII_TG3_MISC_SHDW_SCR5_DLLAPD; tg3_writephy(tp, MII_TG3_MISC_SHDW, reg); reg = MII_TG3_MISC_SHDW_WREN | MII_TG3_MISC_SHDW_APD_SEL | MII_TG3_MISC_SHDW_APD_WKTM_84MS; if (enable) reg |= MII_TG3_MISC_SHDW_APD_ENABLE; tg3_writephy(tp, MII_TG3_MISC_SHDW, reg); } static void tg3_phy_toggle_automdix(struct tg3 *tp, int enable) { u32 phy; if (!tg3_flag(tp, 5705_PLUS) || (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) return; if (tp->phy_flags & TG3_PHYFLG_IS_FET) { u32 ephy; if (!tg3_readphy(tp, MII_TG3_FET_TEST, &ephy)) { u32 reg = MII_TG3_FET_SHDW_MISCCTRL; tg3_writephy(tp, MII_TG3_FET_TEST, ephy | MII_TG3_FET_SHADOW_EN); if (!tg3_readphy(tp, reg, &phy)) { if (enable) phy |= MII_TG3_FET_SHDW_MISCCTRL_MDIX; else phy &= ~MII_TG3_FET_SHDW_MISCCTRL_MDIX; tg3_writephy(tp, reg, phy); } tg3_writephy(tp, MII_TG3_FET_TEST, ephy); } } else { int ret; ret = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_MISC, &phy); if (!ret) { if (enable) phy |= MII_TG3_AUXCTL_MISC_FORCE_AMDIX; else phy &= ~MII_TG3_AUXCTL_MISC_FORCE_AMDIX; tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_MISC, phy); } } } static void tg3_phy_set_wirespeed(struct tg3 *tp) { int ret; u32 val; if (tp->phy_flags & TG3_PHYFLG_NO_ETH_WIRE_SPEED) return; ret = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_MISC, &val); if (!ret) tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_MISC, val | MII_TG3_AUXCTL_MISC_WIRESPD_EN); } static void tg3_phy_apply_otp(struct tg3 *tp) { u32 otp, phy; if (!tp->phy_otp) return; otp = tp->phy_otp; if (tg3_phy_toggle_auxctl_smdsp(tp, true)) return; phy = ((otp & TG3_OTP_AGCTGT_MASK) >> TG3_OTP_AGCTGT_SHIFT); phy |= MII_TG3_DSP_TAP1_AGCTGT_DFLT; tg3_phydsp_write(tp, MII_TG3_DSP_TAP1, phy); phy = ((otp & TG3_OTP_HPFFLTR_MASK) >> TG3_OTP_HPFFLTR_SHIFT) | ((otp & TG3_OTP_HPFOVER_MASK) >> TG3_OTP_HPFOVER_SHIFT); tg3_phydsp_write(tp, MII_TG3_DSP_AADJ1CH0, phy); phy = ((otp & TG3_OTP_LPFDIS_MASK) >> TG3_OTP_LPFDIS_SHIFT); phy |= MII_TG3_DSP_AADJ1CH3_ADCCKADJ; tg3_phydsp_write(tp, MII_TG3_DSP_AADJ1CH3, phy); phy = ((otp & TG3_OTP_VDAC_MASK) >> TG3_OTP_VDAC_SHIFT); tg3_phydsp_write(tp, MII_TG3_DSP_EXP75, phy); phy = ((otp & TG3_OTP_10BTAMP_MASK) >> TG3_OTP_10BTAMP_SHIFT); tg3_phydsp_write(tp, MII_TG3_DSP_EXP96, phy); phy = ((otp & TG3_OTP_ROFF_MASK) >> TG3_OTP_ROFF_SHIFT) | ((otp & TG3_OTP_RCOFF_MASK) >> TG3_OTP_RCOFF_SHIFT); tg3_phydsp_write(tp, MII_TG3_DSP_EXP97, phy); tg3_phy_toggle_auxctl_smdsp(tp, false); } static void tg3_phy_eee_adjust(struct tg3 *tp, u32 current_link_up) { u32 val; if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) return; tp->setlpicnt = 0; if (tp->link_config.autoneg == AUTONEG_ENABLE && current_link_up == 1 && tp->link_config.active_duplex == DUPLEX_FULL && (tp->link_config.active_speed == SPEED_100 || tp->link_config.active_speed == SPEED_1000)) { u32 eeectl; if (tp->link_config.active_speed == SPEED_1000) eeectl = TG3_CPMU_EEE_CTRL_EXIT_16_5_US; else eeectl = TG3_CPMU_EEE_CTRL_EXIT_36_US; tw32(TG3_CPMU_EEE_CTRL, eeectl); tg3_phy_cl45_read(tp, MDIO_MMD_AN, TG3_CL45_D7_EEERES_STAT, &val); if (val == TG3_CL45_D7_EEERES_STAT_LP_1000T || val == TG3_CL45_D7_EEERES_STAT_LP_100TX) tp->setlpicnt = 2; } if (!tp->setlpicnt) { if (current_link_up == 1 && !tg3_phy_toggle_auxctl_smdsp(tp, true)) { tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, 0x0000); tg3_phy_toggle_auxctl_smdsp(tp, false); } val = tr32(TG3_CPMU_EEE_MODE); tw32(TG3_CPMU_EEE_MODE, val & ~TG3_CPMU_EEEMD_LPI_ENABLE); } } static void tg3_phy_eee_enable(struct tg3 *tp) { u32 val; if (tp->link_config.active_speed == SPEED_1000 && (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_flag(tp, 57765_CLASS)) && !tg3_phy_toggle_auxctl_smdsp(tp, true)) { val = MII_TG3_DSP_TAP26_ALNOKO | MII_TG3_DSP_TAP26_RMRXSTO; tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val); tg3_phy_toggle_auxctl_smdsp(tp, false); } val = tr32(TG3_CPMU_EEE_MODE); tw32(TG3_CPMU_EEE_MODE, val | TG3_CPMU_EEEMD_LPI_ENABLE); } static int tg3_wait_macro_done(struct tg3 *tp) { int limit = 100; while (limit--) { u32 tmp32; if (!tg3_readphy(tp, MII_TG3_DSP_CONTROL, &tmp32)) { if ((tmp32 & 0x1000) == 0) break; } } if (limit < 0) return -EBUSY; return 0; } static int tg3_phy_write_and_check_testpat(struct tg3 *tp, int *resetp) { static const u32 test_pat[4][6] = { { 0x00005555, 0x00000005, 0x00002aaa, 0x0000000a, 0x00003456, 0x00000003 }, { 0x00002aaa, 0x0000000a, 0x00003333, 0x00000003, 0x0000789a, 0x00000005 }, { 0x00005a5a, 0x00000005, 0x00002a6a, 0x0000000a, 0x00001bcd, 0x00000003 }, { 0x00002a5a, 0x0000000a, 0x000033c3, 0x00000003, 0x00002ef1, 0x00000005 } }; int chan; for (chan = 0; chan < 4; chan++) { int i; tg3_writephy(tp, MII_TG3_DSP_ADDRESS, (chan * 0x2000) | 0x0200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002); for (i = 0; i < 6; i++) tg3_writephy(tp, MII_TG3_DSP_RW_PORT, test_pat[chan][i]); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202); if (tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } tg3_writephy(tp, MII_TG3_DSP_ADDRESS, (chan * 0x2000) | 0x0200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0082); if (tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0802); if (tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } for (i = 0; i < 6; i += 2) { u32 low, high; if (tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &low) || tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &high) || tg3_wait_macro_done(tp)) { *resetp = 1; return -EBUSY; } low &= 0x7fff; high &= 0x000f; if (low != test_pat[chan][i] || high != test_pat[chan][i+1]) { tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000b); tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4001); tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4005); return -EBUSY; } } } return 0; } static int tg3_phy_reset_chanpat(struct tg3 *tp) { int chan; for (chan = 0; chan < 4; chan++) { int i; tg3_writephy(tp, MII_TG3_DSP_ADDRESS, (chan * 0x2000) | 0x0200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002); for (i = 0; i < 6; i++) tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x000); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202); if (tg3_wait_macro_done(tp)) return -EBUSY; } return 0; } static int tg3_phy_reset_5703_4_5(struct tg3 *tp) { u32 reg32, phy9_orig; int retries, do_phy_reset, err; retries = 10; do_phy_reset = 1; do { if (do_phy_reset) { err = tg3_bmcr_reset(tp); if (err) return err; do_phy_reset = 0; } /* Disable transmitter and interrupt. */ if (tg3_readphy(tp, MII_TG3_EXT_CTRL, &reg32)) continue; reg32 |= 0x3000; tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32); /* Set full-duplex, 1000 mbps. */ tg3_writephy(tp, MII_BMCR, BMCR_FULLDPLX | BMCR_SPEED1000); /* Set to master mode. */ if (tg3_readphy(tp, MII_CTRL1000, &phy9_orig)) continue; tg3_writephy(tp, MII_CTRL1000, CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER); err = tg3_phy_toggle_auxctl_smdsp(tp, true); if (err) return err; /* Block the PHY control access. */ tg3_phydsp_write(tp, 0x8005, 0x0800); err = tg3_phy_write_and_check_testpat(tp, &do_phy_reset); if (!err) break; } while (--retries); err = tg3_phy_reset_chanpat(tp); if (err) return err; tg3_phydsp_write(tp, 0x8005, 0x0000); tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x8200); tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0000); tg3_phy_toggle_auxctl_smdsp(tp, false); tg3_writephy(tp, MII_CTRL1000, phy9_orig); if (!tg3_readphy(tp, MII_TG3_EXT_CTRL, &reg32)) { reg32 &= ~0x3000; tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32); } else if (!err) err = -EBUSY; return err; } static void tg3_carrier_off(struct tg3 *tp) { netif_carrier_off(tp->dev); tp->link_up = false; } /* This will reset the tigon3 PHY if there is no valid * link unless the FORCE argument is non-zero. */ static int tg3_phy_reset(struct tg3 *tp) { u32 val, cpmuctrl; int err; if (tg3_asic_rev(tp) == ASIC_REV_5906) { val = tr32(GRC_MISC_CFG); tw32_f(GRC_MISC_CFG, val & ~GRC_MISC_CFG_EPHY_IDDQ); udelay(40); } err = tg3_readphy(tp, MII_BMSR, &val); err |= tg3_readphy(tp, MII_BMSR, &val); if (err != 0) return -EBUSY; if (netif_running(tp->dev) && tp->link_up) { netif_carrier_off(tp->dev); tg3_link_report(tp); } if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_asic_rev(tp) == ASIC_REV_5705) { err = tg3_phy_reset_5703_4_5(tp); if (err) return err; goto out; } cpmuctrl = 0; if (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX) { cpmuctrl = tr32(TG3_CPMU_CTRL); if (cpmuctrl & CPMU_CTRL_GPHY_10MB_RXONLY) tw32(TG3_CPMU_CTRL, cpmuctrl & ~CPMU_CTRL_GPHY_10MB_RXONLY); } err = tg3_bmcr_reset(tp); if (err) return err; if (cpmuctrl & CPMU_CTRL_GPHY_10MB_RXONLY) { val = MII_TG3_DSP_EXP8_AEDW | MII_TG3_DSP_EXP8_REJ2MHz; tg3_phydsp_write(tp, MII_TG3_DSP_EXP8, val); tw32(TG3_CPMU_CTRL, cpmuctrl); } if (tg3_chip_rev(tp) == CHIPREV_5784_AX || tg3_chip_rev(tp) == CHIPREV_5761_AX) { val = tr32(TG3_CPMU_LSPD_1000MB_CLK); if ((val & CPMU_LSPD_1000MB_MACCLK_MASK) == CPMU_LSPD_1000MB_MACCLK_12_5) { val &= ~CPMU_LSPD_1000MB_MACCLK_MASK; udelay(40); tw32_f(TG3_CPMU_LSPD_1000MB_CLK, val); } } if (tg3_flag(tp, 5717_PLUS) && (tp->phy_flags & TG3_PHYFLG_MII_SERDES)) return 0; tg3_phy_apply_otp(tp); if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD) tg3_phy_toggle_apd(tp, true); else tg3_phy_toggle_apd(tp, false); out: if ((tp->phy_flags & TG3_PHYFLG_ADC_BUG) && !tg3_phy_toggle_auxctl_smdsp(tp, true)) { tg3_phydsp_write(tp, 0x201f, 0x2aaa); tg3_phydsp_write(tp, 0x000a, 0x0323); tg3_phy_toggle_auxctl_smdsp(tp, false); } if (tp->phy_flags & TG3_PHYFLG_5704_A0_BUG) { tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68); } if (tp->phy_flags & TG3_PHYFLG_BER_BUG) { if (!tg3_phy_toggle_auxctl_smdsp(tp, true)) { tg3_phydsp_write(tp, 0x000a, 0x310b); tg3_phydsp_write(tp, 0x201f, 0x9506); tg3_phydsp_write(tp, 0x401f, 0x14e2); tg3_phy_toggle_auxctl_smdsp(tp, false); } } else if (tp->phy_flags & TG3_PHYFLG_JITTER_BUG) { if (!tg3_phy_toggle_auxctl_smdsp(tp, true)) { tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000a); if (tp->phy_flags & TG3_PHYFLG_ADJUST_TRIM) { tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x110b); tg3_writephy(tp, MII_TG3_TEST1, MII_TG3_TEST1_TRIM_EN | 0x4); } else tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x010b); tg3_phy_toggle_auxctl_smdsp(tp, false); } } /* Set Extended packet length bit (bit 14) on all chips that */ /* support jumbo frames */ if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { /* Cannot do read-modify-write on 5401 */ tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, 0x4c20); } else if (tg3_flag(tp, JUMBO_CAPABLE)) { /* Set bit 14 with read-modify-write to preserve other bits */ err = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val); if (!err) tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, val | MII_TG3_AUXCTL_ACTL_EXTPKTLEN); } /* Set phy register 0x10 bit 0 to high fifo elasticity to support * jumbo frames transmission. */ if (tg3_flag(tp, JUMBO_CAPABLE)) { if (!tg3_readphy(tp, MII_TG3_EXT_CTRL, &val)) tg3_writephy(tp, MII_TG3_EXT_CTRL, val | MII_TG3_EXT_CTRL_FIFO_ELASTIC); } if (tg3_asic_rev(tp) == ASIC_REV_5906) { /* adjust output voltage */ tg3_writephy(tp, MII_TG3_FET_PTEST, 0x12); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5762_A0) tg3_phydsp_write(tp, 0xffb, 0x4000); tg3_phy_toggle_automdix(tp, 1); tg3_phy_set_wirespeed(tp); return 0; } #define TG3_GPIO_MSG_DRVR_PRES 0x00000001 #define TG3_GPIO_MSG_NEED_VAUX 0x00000002 #define TG3_GPIO_MSG_MASK (TG3_GPIO_MSG_DRVR_PRES | \ TG3_GPIO_MSG_NEED_VAUX) #define TG3_GPIO_MSG_ALL_DRVR_PRES_MASK \ ((TG3_GPIO_MSG_DRVR_PRES << 0) | \ (TG3_GPIO_MSG_DRVR_PRES << 4) | \ (TG3_GPIO_MSG_DRVR_PRES << 8) | \ (TG3_GPIO_MSG_DRVR_PRES << 12)) #define TG3_GPIO_MSG_ALL_NEED_VAUX_MASK \ ((TG3_GPIO_MSG_NEED_VAUX << 0) | \ (TG3_GPIO_MSG_NEED_VAUX << 4) | \ (TG3_GPIO_MSG_NEED_VAUX << 8) | \ (TG3_GPIO_MSG_NEED_VAUX << 12)) static inline u32 tg3_set_function_status(struct tg3 *tp, u32 newstat) { u32 status, shift; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719) status = tg3_ape_read32(tp, TG3_APE_GPIO_MSG); else status = tr32(TG3_CPMU_DRV_STATUS); shift = TG3_APE_GPIO_MSG_SHIFT + 4 * tp->pci_fn; status &= ~(TG3_GPIO_MSG_MASK << shift); status |= (newstat << shift); if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719) tg3_ape_write32(tp, TG3_APE_GPIO_MSG, status); else tw32(TG3_CPMU_DRV_STATUS, status); return status >> TG3_APE_GPIO_MSG_SHIFT; } static inline int tg3_pwrsrc_switch_to_vmain(struct tg3 *tp) { if (!tg3_flag(tp, IS_NIC)) return 0; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO)) return -EIO; tg3_set_function_status(tp, TG3_GPIO_MSG_DRVR_PRES); tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO); } else { tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); } return 0; } static void tg3_pwrsrc_die_with_vmain(struct tg3 *tp) { u32 grc_local_ctrl; if (!tg3_flag(tp, IS_NIC) || tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) return; grc_local_ctrl = tp->grc_local_ctrl | GRC_LCLCTRL_GPIO_OE1; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl | GRC_LCLCTRL_GPIO_OUTPUT1, TG3_GRC_LCLCTL_PWRSW_DELAY); tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl | GRC_LCLCTRL_GPIO_OUTPUT1, TG3_GRC_LCLCTL_PWRSW_DELAY); } static void tg3_pwrsrc_switch_to_vaux(struct tg3 *tp) { if (!tg3_flag(tp, IS_NIC)) return; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | (GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OE1 | GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT0 | GRC_LCLCTRL_GPIO_OUTPUT1), TG3_GRC_LCLCTL_PWRSW_DELAY); } else if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S) { /* The 5761 non-e device swaps GPIO 0 and GPIO 2. */ u32 grc_local_ctrl = GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OE1 | GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT0 | GRC_LCLCTRL_GPIO_OUTPUT1 | tp->grc_local_ctrl; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); grc_local_ctrl |= GRC_LCLCTRL_GPIO_OUTPUT2; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); grc_local_ctrl &= ~GRC_LCLCTRL_GPIO_OUTPUT0; tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); } else { u32 no_gpio2; u32 grc_local_ctrl = 0; /* Workaround to prevent overdrawing Amps. */ if (tg3_asic_rev(tp) == ASIC_REV_5714) { grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE3; tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); } /* On 5753 and variants, GPIO2 cannot be used. */ no_gpio2 = tp->nic_sram_data_cfg & NIC_SRAM_DATA_CFG_NO_GPIO2; grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OE1 | GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT1 | GRC_LCLCTRL_GPIO_OUTPUT2; if (no_gpio2) { grc_local_ctrl &= ~(GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT2); } tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); grc_local_ctrl |= GRC_LCLCTRL_GPIO_OUTPUT0; tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); if (!no_gpio2) { grc_local_ctrl &= ~GRC_LCLCTRL_GPIO_OUTPUT2; tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl | grc_local_ctrl, TG3_GRC_LCLCTL_PWRSW_DELAY); } } } static void tg3_frob_aux_power_5717(struct tg3 *tp, bool wol_enable) { u32 msg = 0; /* Serialize power state transitions */ if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO)) return; if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE) || wol_enable) msg = TG3_GPIO_MSG_NEED_VAUX; msg = tg3_set_function_status(tp, msg); if (msg & TG3_GPIO_MSG_ALL_DRVR_PRES_MASK) goto done; if (msg & TG3_GPIO_MSG_ALL_NEED_VAUX_MASK) tg3_pwrsrc_switch_to_vaux(tp); else tg3_pwrsrc_die_with_vmain(tp); done: tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO); } static void tg3_frob_aux_power(struct tg3 *tp, bool include_wol) { bool need_vaux = false; /* The GPIOs do something completely different on 57765. */ if (!tg3_flag(tp, IS_NIC) || tg3_flag(tp, 57765_CLASS)) return; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { tg3_frob_aux_power_5717(tp, include_wol ? tg3_flag(tp, WOL_ENABLE) != 0 : 0); return; } if (tp->pdev_peer && tp->pdev_peer != tp->pdev) { struct net_device *dev_peer; dev_peer = pci_get_drvdata(tp->pdev_peer); /* remove_one() may have been run on the peer. */ if (dev_peer) { struct tg3 *tp_peer = netdev_priv(dev_peer); if (tg3_flag(tp_peer, INIT_COMPLETE)) return; if ((include_wol && tg3_flag(tp_peer, WOL_ENABLE)) || tg3_flag(tp_peer, ENABLE_ASF)) need_vaux = true; } } if ((include_wol && tg3_flag(tp, WOL_ENABLE)) || tg3_flag(tp, ENABLE_ASF)) need_vaux = true; if (need_vaux) tg3_pwrsrc_switch_to_vaux(tp); else tg3_pwrsrc_die_with_vmain(tp); } static int tg3_5700_link_polarity(struct tg3 *tp, u32 speed) { if (tp->led_ctrl == LED_CTRL_MODE_PHY_2) return 1; else if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411) { if (speed != SPEED_10) return 1; } else if (speed == SPEED_10) return 1; return 0; } static void tg3_power_down_phy(struct tg3 *tp, bool do_low_power) { u32 val; if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) { if (tg3_asic_rev(tp) == ASIC_REV_5704) { u32 sg_dig_ctrl = tr32(SG_DIG_CTRL); u32 serdes_cfg = tr32(MAC_SERDES_CFG); sg_dig_ctrl |= SG_DIG_USING_HW_AUTONEG | SG_DIG_SOFT_RESET; tw32(SG_DIG_CTRL, sg_dig_ctrl); tw32(MAC_SERDES_CFG, serdes_cfg | (1 << 15)); } return; } if (tg3_asic_rev(tp) == ASIC_REV_5906) { tg3_bmcr_reset(tp); val = tr32(GRC_MISC_CFG); tw32_f(GRC_MISC_CFG, val | GRC_MISC_CFG_EPHY_IDDQ); udelay(40); return; } else if (tp->phy_flags & TG3_PHYFLG_IS_FET) { u32 phytest; if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) { u32 phy; tg3_writephy(tp, MII_ADVERTISE, 0); tg3_writephy(tp, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART); tg3_writephy(tp, MII_TG3_FET_TEST, phytest | MII_TG3_FET_SHADOW_EN); if (!tg3_readphy(tp, MII_TG3_FET_SHDW_AUXMODE4, &phy)) { phy |= MII_TG3_FET_SHDW_AUXMODE4_SBPD; tg3_writephy(tp, MII_TG3_FET_SHDW_AUXMODE4, phy); } tg3_writephy(tp, MII_TG3_FET_TEST, phytest); } return; } else if (do_low_power) { tg3_writephy(tp, MII_TG3_EXT_CTRL, MII_TG3_EXT_CTRL_FORCE_LED_OFF); val = MII_TG3_AUXCTL_PCTL_100TX_LPWR | MII_TG3_AUXCTL_PCTL_SPR_ISOLATE | MII_TG3_AUXCTL_PCTL_VREG_11V; tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, val); } /* The PHY should not be powered down on some chips because * of bugs. */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5704 || (tg3_asic_rev(tp) == ASIC_REV_5780 && (tp->phy_flags & TG3_PHYFLG_MII_SERDES)) || (tg3_asic_rev(tp) == ASIC_REV_5717 && !tp->pci_fn)) return; if (tg3_chip_rev(tp) == CHIPREV_5784_AX || tg3_chip_rev(tp) == CHIPREV_5761_AX) { val = tr32(TG3_CPMU_LSPD_1000MB_CLK); val &= ~CPMU_LSPD_1000MB_MACCLK_MASK; val |= CPMU_LSPD_1000MB_MACCLK_12_5; tw32_f(TG3_CPMU_LSPD_1000MB_CLK, val); } tg3_writephy(tp, MII_BMCR, BMCR_PDOWN); } /* tp->lock is held. */ static int tg3_nvram_lock(struct tg3 *tp) { if (tg3_flag(tp, NVRAM)) { int i; if (tp->nvram_lock_cnt == 0) { tw32(NVRAM_SWARB, SWARB_REQ_SET1); for (i = 0; i < 8000; i++) { if (tr32(NVRAM_SWARB) & SWARB_GNT1) break; udelay(20); } if (i == 8000) { tw32(NVRAM_SWARB, SWARB_REQ_CLR1); return -ENODEV; } } tp->nvram_lock_cnt++; } return 0; } /* tp->lock is held. */ static void tg3_nvram_unlock(struct tg3 *tp) { if (tg3_flag(tp, NVRAM)) { if (tp->nvram_lock_cnt > 0) tp->nvram_lock_cnt--; if (tp->nvram_lock_cnt == 0) tw32_f(NVRAM_SWARB, SWARB_REQ_CLR1); } } /* tp->lock is held. */ static void tg3_enable_nvram_access(struct tg3 *tp) { if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) { u32 nvaccess = tr32(NVRAM_ACCESS); tw32(NVRAM_ACCESS, nvaccess | ACCESS_ENABLE); } } /* tp->lock is held. */ static void tg3_disable_nvram_access(struct tg3 *tp) { if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) { u32 nvaccess = tr32(NVRAM_ACCESS); tw32(NVRAM_ACCESS, nvaccess & ~ACCESS_ENABLE); } } static int tg3_nvram_read_using_eeprom(struct tg3 *tp, u32 offset, u32 *val) { u32 tmp; int i; if (offset > EEPROM_ADDR_ADDR_MASK || (offset % 4) != 0) return -EINVAL; tmp = tr32(GRC_EEPROM_ADDR) & ~(EEPROM_ADDR_ADDR_MASK | EEPROM_ADDR_DEVID_MASK | EEPROM_ADDR_READ); tw32(GRC_EEPROM_ADDR, tmp | (0 << EEPROM_ADDR_DEVID_SHIFT) | ((offset << EEPROM_ADDR_ADDR_SHIFT) & EEPROM_ADDR_ADDR_MASK) | EEPROM_ADDR_READ | EEPROM_ADDR_START); for (i = 0; i < 1000; i++) { tmp = tr32(GRC_EEPROM_ADDR); if (tmp & EEPROM_ADDR_COMPLETE) break; msleep(1); } if (!(tmp & EEPROM_ADDR_COMPLETE)) return -EBUSY; tmp = tr32(GRC_EEPROM_DATA); /* * The data will always be opposite the native endian * format. Perform a blind byteswap to compensate. */ *val = swab32(tmp); return 0; } #define NVRAM_CMD_TIMEOUT 10000 static int tg3_nvram_exec_cmd(struct tg3 *tp, u32 nvram_cmd) { int i; tw32(NVRAM_CMD, nvram_cmd); for (i = 0; i < NVRAM_CMD_TIMEOUT; i++) { udelay(10); if (tr32(NVRAM_CMD) & NVRAM_CMD_DONE) { udelay(10); break; } } if (i == NVRAM_CMD_TIMEOUT) return -EBUSY; return 0; } static u32 tg3_nvram_phys_addr(struct tg3 *tp, u32 addr) { if (tg3_flag(tp, NVRAM) && tg3_flag(tp, NVRAM_BUFFERED) && tg3_flag(tp, FLASH) && !tg3_flag(tp, NO_NVRAM_ADDR_TRANS) && (tp->nvram_jedecnum == JEDEC_ATMEL)) addr = ((addr / tp->nvram_pagesize) << ATMEL_AT45DB0X1B_PAGE_POS) + (addr % tp->nvram_pagesize); return addr; } static u32 tg3_nvram_logical_addr(struct tg3 *tp, u32 addr) { if (tg3_flag(tp, NVRAM) && tg3_flag(tp, NVRAM_BUFFERED) && tg3_flag(tp, FLASH) && !tg3_flag(tp, NO_NVRAM_ADDR_TRANS) && (tp->nvram_jedecnum == JEDEC_ATMEL)) addr = ((addr >> ATMEL_AT45DB0X1B_PAGE_POS) * tp->nvram_pagesize) + (addr & ((1 << ATMEL_AT45DB0X1B_PAGE_POS) - 1)); return addr; } /* NOTE: Data read in from NVRAM is byteswapped according to * the byteswapping settings for all other register accesses. * tg3 devices are BE devices, so on a BE machine, the data * returned will be exactly as it is seen in NVRAM. On a LE * machine, the 32-bit value will be byteswapped. */ static int tg3_nvram_read(struct tg3 *tp, u32 offset, u32 *val) { int ret; if (!tg3_flag(tp, NVRAM)) return tg3_nvram_read_using_eeprom(tp, offset, val); offset = tg3_nvram_phys_addr(tp, offset); if (offset > NVRAM_ADDR_MSK) return -EINVAL; ret = tg3_nvram_lock(tp); if (ret) return ret; tg3_enable_nvram_access(tp); tw32(NVRAM_ADDR, offset); ret = tg3_nvram_exec_cmd(tp, NVRAM_CMD_RD | NVRAM_CMD_GO | NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_DONE); if (ret == 0) *val = tr32(NVRAM_RDDATA); tg3_disable_nvram_access(tp); tg3_nvram_unlock(tp); return ret; } /* Ensures NVRAM data is in bytestream format. */ static int tg3_nvram_read_be32(struct tg3 *tp, u32 offset, __be32 *val) { u32 v; int res = tg3_nvram_read(tp, offset, &v); if (!res) *val = cpu_to_be32(v); return res; } static int tg3_nvram_write_block_using_eeprom(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int i, j, rc = 0; u32 val; for (i = 0; i < len; i += 4) { u32 addr; __be32 data; addr = offset + i; memcpy(&data, buf + i, 4); /* * The SEEPROM interface expects the data to always be opposite * the native endian format. We accomplish this by reversing * all the operations that would have been performed on the * data from a call to tg3_nvram_read_be32(). */ tw32(GRC_EEPROM_DATA, swab32(be32_to_cpu(data))); val = tr32(GRC_EEPROM_ADDR); tw32(GRC_EEPROM_ADDR, val | EEPROM_ADDR_COMPLETE); val &= ~(EEPROM_ADDR_ADDR_MASK | EEPROM_ADDR_DEVID_MASK | EEPROM_ADDR_READ); tw32(GRC_EEPROM_ADDR, val | (0 << EEPROM_ADDR_DEVID_SHIFT) | (addr & EEPROM_ADDR_ADDR_MASK) | EEPROM_ADDR_START | EEPROM_ADDR_WRITE); for (j = 0; j < 1000; j++) { val = tr32(GRC_EEPROM_ADDR); if (val & EEPROM_ADDR_COMPLETE) break; msleep(1); } if (!(val & EEPROM_ADDR_COMPLETE)) { rc = -EBUSY; break; } } return rc; } /* offset and length are dword aligned */ static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int ret = 0; u32 pagesize = tp->nvram_pagesize; u32 pagemask = pagesize - 1; u32 nvram_cmd; u8 *tmp; tmp = kmalloc(pagesize, GFP_KERNEL); if (tmp == NULL) return -ENOMEM; while (len) { int j; u32 phy_addr, page_off, size; phy_addr = offset & ~pagemask; for (j = 0; j < pagesize; j += 4) { ret = tg3_nvram_read_be32(tp, phy_addr + j, (__be32 *) (tmp + j)); if (ret) break; } if (ret) break; page_off = offset & pagemask; size = pagesize; if (len < size) size = len; len -= size; memcpy(tmp + page_off, buf, size); offset = offset + (pagesize - page_off); tg3_enable_nvram_access(tp); /* * Before we can erase the flash page, we need * to issue a special "write enable" command. */ nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE; if (tg3_nvram_exec_cmd(tp, nvram_cmd)) break; /* Erase the target page */ tw32(NVRAM_ADDR, phy_addr); nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR | NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_ERASE; if (tg3_nvram_exec_cmd(tp, nvram_cmd)) break; /* Issue another write enable to start the write. */ nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE; if (tg3_nvram_exec_cmd(tp, nvram_cmd)) break; for (j = 0; j < pagesize; j += 4) { __be32 data; data = *((__be32 *) (tmp + j)); tw32(NVRAM_WRDATA, be32_to_cpu(data)); tw32(NVRAM_ADDR, phy_addr + j); nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR; if (j == 0) nvram_cmd |= NVRAM_CMD_FIRST; else if (j == (pagesize - 4)) nvram_cmd |= NVRAM_CMD_LAST; ret = tg3_nvram_exec_cmd(tp, nvram_cmd); if (ret) break; } if (ret) break; } nvram_cmd = NVRAM_CMD_WRDI | NVRAM_CMD_GO | NVRAM_CMD_DONE; tg3_nvram_exec_cmd(tp, nvram_cmd); kfree(tmp); return ret; } /* offset and length are dword aligned */ static int tg3_nvram_write_block_buffered(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int i, ret = 0; for (i = 0; i < len; i += 4, offset += 4) { u32 page_off, phy_addr, nvram_cmd; __be32 data; memcpy(&data, buf + i, 4); tw32(NVRAM_WRDATA, be32_to_cpu(data)); page_off = offset % tp->nvram_pagesize; phy_addr = tg3_nvram_phys_addr(tp, offset); nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR; if (page_off == 0 || i == 0) nvram_cmd |= NVRAM_CMD_FIRST; if (page_off == (tp->nvram_pagesize - 4)) nvram_cmd |= NVRAM_CMD_LAST; if (i == (len - 4)) nvram_cmd |= NVRAM_CMD_LAST; if ((nvram_cmd & NVRAM_CMD_FIRST) || !tg3_flag(tp, FLASH) || !tg3_flag(tp, 57765_PLUS)) tw32(NVRAM_ADDR, phy_addr); if (tg3_asic_rev(tp) != ASIC_REV_5752 && !tg3_flag(tp, 5755_PLUS) && (tp->nvram_jedecnum == JEDEC_ST) && (nvram_cmd & NVRAM_CMD_FIRST)) { u32 cmd; cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE; ret = tg3_nvram_exec_cmd(tp, cmd); if (ret) break; } if (!tg3_flag(tp, FLASH)) { /* We always do complete word writes to eeprom. */ nvram_cmd |= (NVRAM_CMD_FIRST | NVRAM_CMD_LAST); } ret = tg3_nvram_exec_cmd(tp, nvram_cmd); if (ret) break; } return ret; } /* offset and length are dword aligned */ static int tg3_nvram_write_block(struct tg3 *tp, u32 offset, u32 len, u8 *buf) { int ret; if (tg3_flag(tp, EEPROM_WRITE_PROT)) { tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl & ~GRC_LCLCTRL_GPIO_OUTPUT1); udelay(40); } if (!tg3_flag(tp, NVRAM)) { ret = tg3_nvram_write_block_using_eeprom(tp, offset, len, buf); } else { u32 grc_mode; ret = tg3_nvram_lock(tp); if (ret) return ret; tg3_enable_nvram_access(tp); if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) tw32(NVRAM_WRITE1, 0x406); grc_mode = tr32(GRC_MODE); tw32(GRC_MODE, grc_mode | GRC_MODE_NVRAM_WR_ENABLE); if (tg3_flag(tp, NVRAM_BUFFERED) || !tg3_flag(tp, FLASH)) { ret = tg3_nvram_write_block_buffered(tp, offset, len, buf); } else { ret = tg3_nvram_write_block_unbuffered(tp, offset, len, buf); } grc_mode = tr32(GRC_MODE); tw32(GRC_MODE, grc_mode & ~GRC_MODE_NVRAM_WR_ENABLE); tg3_disable_nvram_access(tp); tg3_nvram_unlock(tp); } if (tg3_flag(tp, EEPROM_WRITE_PROT)) { tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl); udelay(40); } return ret; } #define RX_CPU_SCRATCH_BASE 0x30000 #define RX_CPU_SCRATCH_SIZE 0x04000 #define TX_CPU_SCRATCH_BASE 0x34000 #define TX_CPU_SCRATCH_SIZE 0x04000 /* tp->lock is held. */ static int tg3_halt_cpu(struct tg3 *tp, u32 offset) { int i; BUG_ON(offset == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS)); if (tg3_asic_rev(tp) == ASIC_REV_5906) { u32 val = tr32(GRC_VCPU_EXT_CTRL); tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_HALT_CPU); return 0; } if (offset == RX_CPU_BASE) { for (i = 0; i < 10000; i++) { tw32(offset + CPU_STATE, 0xffffffff); tw32(offset + CPU_MODE, CPU_MODE_HALT); if (tr32(offset + CPU_MODE) & CPU_MODE_HALT) break; } tw32(offset + CPU_STATE, 0xffffffff); tw32_f(offset + CPU_MODE, CPU_MODE_HALT); udelay(10); } else { /* * There is only an Rx CPU for the 5750 derivative in the * BCM4785. */ if (tg3_flag(tp, IS_SSB_CORE)) return 0; for (i = 0; i < 10000; i++) { tw32(offset + CPU_STATE, 0xffffffff); tw32(offset + CPU_MODE, CPU_MODE_HALT); if (tr32(offset + CPU_MODE) & CPU_MODE_HALT) break; } } if (i >= 10000) { netdev_err(tp->dev, "%s timed out, %s CPU\n", __func__, offset == RX_CPU_BASE ? "RX" : "TX"); return -ENODEV; } /* Clear firmware's nvram arbitration. */ if (tg3_flag(tp, NVRAM)) tw32(NVRAM_SWARB, SWARB_REQ_CLR0); return 0; } struct fw_info { unsigned int fw_base; unsigned int fw_len; const __be32 *fw_data; }; /* tp->lock is held. */ static int tg3_load_firmware_cpu(struct tg3 *tp, u32 cpu_base, u32 cpu_scratch_base, int cpu_scratch_size, struct fw_info *info) { int err, lock_err, i; void (*write_op)(struct tg3 *, u32, u32); if (cpu_base == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS)) { netdev_err(tp->dev, "%s: Trying to load TX cpu firmware which is 5705\n", __func__); return -EINVAL; } if (tg3_flag(tp, 5705_PLUS)) write_op = tg3_write_mem; else write_op = tg3_write_indirect_reg32; /* It is possible that bootcode is still loading at this point. * Get the nvram lock first before halting the cpu. */ lock_err = tg3_nvram_lock(tp); err = tg3_halt_cpu(tp, cpu_base); if (!lock_err) tg3_nvram_unlock(tp); if (err) goto out; for (i = 0; i < cpu_scratch_size; i += sizeof(u32)) write_op(tp, cpu_scratch_base + i, 0); tw32(cpu_base + CPU_STATE, 0xffffffff); tw32(cpu_base + CPU_MODE, tr32(cpu_base+CPU_MODE)|CPU_MODE_HALT); for (i = 0; i < (info->fw_len / sizeof(u32)); i++) write_op(tp, (cpu_scratch_base + (info->fw_base & 0xffff) + (i * sizeof(u32))), be32_to_cpu(info->fw_data[i])); err = 0; out: return err; } /* tp->lock is held. */ static int tg3_load_5701_a0_firmware_fix(struct tg3 *tp) { struct fw_info info; const __be32 *fw_data; int err, i; fw_data = (void *)tp->fw->data; /* Firmware blob starts with version numbers, followed by start address and length. We are setting complete length. length = end_address_of_bss - start_address_of_text. Remainder is the blob to be loaded contiguously from start address. */ info.fw_base = be32_to_cpu(fw_data[1]); info.fw_len = tp->fw->size - 12; info.fw_data = &fw_data[3]; err = tg3_load_firmware_cpu(tp, RX_CPU_BASE, RX_CPU_SCRATCH_BASE, RX_CPU_SCRATCH_SIZE, &info); if (err) return err; err = tg3_load_firmware_cpu(tp, TX_CPU_BASE, TX_CPU_SCRATCH_BASE, TX_CPU_SCRATCH_SIZE, &info); if (err) return err; /* Now startup only the RX cpu. */ tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff); tw32_f(RX_CPU_BASE + CPU_PC, info.fw_base); for (i = 0; i < 5; i++) { if (tr32(RX_CPU_BASE + CPU_PC) == info.fw_base) break; tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff); tw32(RX_CPU_BASE + CPU_MODE, CPU_MODE_HALT); tw32_f(RX_CPU_BASE + CPU_PC, info.fw_base); udelay(1000); } if (i >= 5) { netdev_err(tp->dev, "%s fails to set RX CPU PC, is %08x " "should be %08x\n", __func__, tr32(RX_CPU_BASE + CPU_PC), info.fw_base); return -ENODEV; } tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff); tw32_f(RX_CPU_BASE + CPU_MODE, 0x00000000); return 0; } /* tp->lock is held. */ static int tg3_load_tso_firmware(struct tg3 *tp) { struct fw_info info; const __be32 *fw_data; unsigned long cpu_base, cpu_scratch_base, cpu_scratch_size; int err, i; if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) return 0; fw_data = (void *)tp->fw->data; /* Firmware blob starts with version numbers, followed by start address and length. We are setting complete length. length = end_address_of_bss - start_address_of_text. Remainder is the blob to be loaded contiguously from start address. */ info.fw_base = be32_to_cpu(fw_data[1]); cpu_scratch_size = tp->fw_len; info.fw_len = tp->fw->size - 12; info.fw_data = &fw_data[3]; if (tg3_asic_rev(tp) == ASIC_REV_5705) { cpu_base = RX_CPU_BASE; cpu_scratch_base = NIC_SRAM_MBUF_POOL_BASE5705; } else { cpu_base = TX_CPU_BASE; cpu_scratch_base = TX_CPU_SCRATCH_BASE; cpu_scratch_size = TX_CPU_SCRATCH_SIZE; } err = tg3_load_firmware_cpu(tp, cpu_base, cpu_scratch_base, cpu_scratch_size, &info); if (err) return err; /* Now startup the cpu. */ tw32(cpu_base + CPU_STATE, 0xffffffff); tw32_f(cpu_base + CPU_PC, info.fw_base); for (i = 0; i < 5; i++) { if (tr32(cpu_base + CPU_PC) == info.fw_base) break; tw32(cpu_base + CPU_STATE, 0xffffffff); tw32(cpu_base + CPU_MODE, CPU_MODE_HALT); tw32_f(cpu_base + CPU_PC, info.fw_base); udelay(1000); } if (i >= 5) { netdev_err(tp->dev, "%s fails to set CPU PC, is %08x should be %08x\n", __func__, tr32(cpu_base + CPU_PC), info.fw_base); return -ENODEV; } tw32(cpu_base + CPU_STATE, 0xffffffff); tw32_f(cpu_base + CPU_MODE, 0x00000000); return 0; } /* tp->lock is held. */ static void __tg3_set_mac_addr(struct tg3 *tp, int skip_mac_1) { u32 addr_high, addr_low; int i; addr_high = ((tp->dev->dev_addr[0] << 8) | tp->dev->dev_addr[1]); addr_low = ((tp->dev->dev_addr[2] << 24) | (tp->dev->dev_addr[3] << 16) | (tp->dev->dev_addr[4] << 8) | (tp->dev->dev_addr[5] << 0)); for (i = 0; i < 4; i++) { if (i == 1 && skip_mac_1) continue; tw32(MAC_ADDR_0_HIGH + (i * 8), addr_high); tw32(MAC_ADDR_0_LOW + (i * 8), addr_low); } if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704) { for (i = 0; i < 12; i++) { tw32(MAC_EXTADDR_0_HIGH + (i * 8), addr_high); tw32(MAC_EXTADDR_0_LOW + (i * 8), addr_low); } } addr_high = (tp->dev->dev_addr[0] + tp->dev->dev_addr[1] + tp->dev->dev_addr[2] + tp->dev->dev_addr[3] + tp->dev->dev_addr[4] + tp->dev->dev_addr[5]) & TX_BACKOFF_SEED_MASK; tw32(MAC_TX_BACKOFF_SEED, addr_high); } static void tg3_enable_register_access(struct tg3 *tp) { /* * Make sure register accesses (indirect or otherwise) will function * correctly. */ pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL, tp->misc_host_ctrl); } static int tg3_power_up(struct tg3 *tp) { int err; tg3_enable_register_access(tp); err = pci_set_power_state(tp->pdev, PCI_D0); if (!err) { /* Switch out of Vaux if it is a NIC */ tg3_pwrsrc_switch_to_vmain(tp); } else { netdev_err(tp->dev, "Transition to D0 failed\n"); } return err; } static int tg3_setup_phy(struct tg3 *, int); static int tg3_power_down_prepare(struct tg3 *tp) { u32 misc_host_ctrl; bool device_should_wake, do_low_power; tg3_enable_register_access(tp); /* Restore the CLKREQ setting. */ if (tg3_flag(tp, CLKREQ_BUG)) pcie_capability_set_word(tp->pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_CLKREQ_EN); misc_host_ctrl = tr32(TG3PCI_MISC_HOST_CTRL); tw32(TG3PCI_MISC_HOST_CTRL, misc_host_ctrl | MISC_HOST_CTRL_MASK_PCI_INT); device_should_wake = device_may_wakeup(&tp->pdev->dev) && tg3_flag(tp, WOL_ENABLE); if (tg3_flag(tp, USE_PHYLIB)) { do_low_power = false; if ((tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) && !(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) { struct phy_device *phydev; u32 phyid, advertising; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; tp->phy_flags |= TG3_PHYFLG_IS_LOW_POWER; tp->link_config.speed = phydev->speed; tp->link_config.duplex = phydev->duplex; tp->link_config.autoneg = phydev->autoneg; tp->link_config.advertising = phydev->advertising; advertising = ADVERTISED_TP | ADVERTISED_Pause | ADVERTISED_Autoneg | ADVERTISED_10baseT_Half; if (tg3_flag(tp, ENABLE_ASF) || device_should_wake) { if (tg3_flag(tp, WOL_SPEED_100MB)) advertising |= ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_10baseT_Full; else advertising |= ADVERTISED_10baseT_Full; } phydev->advertising = advertising; phy_start_aneg(phydev); phyid = phydev->drv->phy_id & phydev->drv->phy_id_mask; if (phyid != PHY_ID_BCMAC131) { phyid &= PHY_BCM_OUI_MASK; if (phyid == PHY_BCM_OUI_1 || phyid == PHY_BCM_OUI_2 || phyid == PHY_BCM_OUI_3) do_low_power = true; } } } else { do_low_power = true; if (!(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) tp->phy_flags |= TG3_PHYFLG_IS_LOW_POWER; if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) tg3_setup_phy(tp, 0); } if (tg3_asic_rev(tp) == ASIC_REV_5906) { u32 val; val = tr32(GRC_VCPU_EXT_CTRL); tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_DISABLE_WOL); } else if (!tg3_flag(tp, ENABLE_ASF)) { int i; u32 val; for (i = 0; i < 200; i++) { tg3_read_mem(tp, NIC_SRAM_FW_ASF_STATUS_MBOX, &val); if (val == ~NIC_SRAM_FIRMWARE_MBOX_MAGIC1) break; msleep(1); } } if (tg3_flag(tp, WOL_CAP)) tg3_write_mem(tp, NIC_SRAM_WOL_MBOX, WOL_SIGNATURE | WOL_DRV_STATE_SHUTDOWN | WOL_DRV_WOL | WOL_SET_MAGIC_PKT); if (device_should_wake) { u32 mac_mode; if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) { if (do_low_power && !(tp->phy_flags & TG3_PHYFLG_IS_FET)) { tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, MII_TG3_AUXCTL_PCTL_WOL_EN | MII_TG3_AUXCTL_PCTL_100TX_LPWR | MII_TG3_AUXCTL_PCTL_CL_AB_TXDAC); udelay(40); } if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) mac_mode = MAC_MODE_PORT_MODE_GMII; else mac_mode = MAC_MODE_PORT_MODE_MII; mac_mode |= tp->mac_mode & MAC_MODE_LINK_POLARITY; if (tg3_asic_rev(tp) == ASIC_REV_5700) { u32 speed = tg3_flag(tp, WOL_SPEED_100MB) ? SPEED_100 : SPEED_10; if (tg3_5700_link_polarity(tp, speed)) mac_mode |= MAC_MODE_LINK_POLARITY; else mac_mode &= ~MAC_MODE_LINK_POLARITY; } } else { mac_mode = MAC_MODE_PORT_MODE_TBI; } if (!tg3_flag(tp, 5750_PLUS)) tw32(MAC_LED_CTRL, tp->led_ctrl); mac_mode |= MAC_MODE_MAGIC_PKT_ENABLE; if ((tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS)) && (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE))) mac_mode |= MAC_MODE_KEEP_FRAME_IN_WOL; if (tg3_flag(tp, ENABLE_APE)) mac_mode |= MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN | MAC_MODE_TDE_ENABLE; tw32_f(MAC_MODE, mac_mode); udelay(100); tw32_f(MAC_RX_MODE, RX_MODE_ENABLE); udelay(10); } if (!tg3_flag(tp, WOL_SPEED_100MB) && (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701)) { u32 base_val; base_val = tp->pci_clock_ctrl; base_val |= (CLOCK_CTRL_RXCLK_DISABLE | CLOCK_CTRL_TXCLK_DISABLE); tw32_wait_f(TG3PCI_CLOCK_CTRL, base_val | CLOCK_CTRL_ALTCLK | CLOCK_CTRL_PWRDOWN_PLL133, 40); } else if (tg3_flag(tp, 5780_CLASS) || tg3_flag(tp, CPMU_PRESENT) || tg3_asic_rev(tp) == ASIC_REV_5906) { /* do nothing */ } else if (!(tg3_flag(tp, 5750_PLUS) && tg3_flag(tp, ENABLE_ASF))) { u32 newbits1, newbits2; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { newbits1 = (CLOCK_CTRL_RXCLK_DISABLE | CLOCK_CTRL_TXCLK_DISABLE | CLOCK_CTRL_ALTCLK); newbits2 = newbits1 | CLOCK_CTRL_44MHZ_CORE; } else if (tg3_flag(tp, 5705_PLUS)) { newbits1 = CLOCK_CTRL_625_CORE; newbits2 = newbits1 | CLOCK_CTRL_ALTCLK; } else { newbits1 = CLOCK_CTRL_ALTCLK; newbits2 = newbits1 | CLOCK_CTRL_44MHZ_CORE; } tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits1, 40); tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits2, 40); if (!tg3_flag(tp, 5705_PLUS)) { u32 newbits3; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { newbits3 = (CLOCK_CTRL_RXCLK_DISABLE | CLOCK_CTRL_TXCLK_DISABLE | CLOCK_CTRL_44MHZ_CORE); } else { newbits3 = CLOCK_CTRL_44MHZ_CORE; } tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits3, 40); } } if (!(device_should_wake) && !tg3_flag(tp, ENABLE_ASF)) tg3_power_down_phy(tp, do_low_power); tg3_frob_aux_power(tp, true); /* Workaround for unstable PLL clock */ if ((!tg3_flag(tp, IS_SSB_CORE)) && ((tg3_chip_rev(tp) == CHIPREV_5750_AX) || (tg3_chip_rev(tp) == CHIPREV_5750_BX))) { u32 val = tr32(0x7d00); val &= ~((1 << 16) | (1 << 4) | (1 << 2) | (1 << 1) | 1); tw32(0x7d00, val); if (!tg3_flag(tp, ENABLE_ASF)) { int err; err = tg3_nvram_lock(tp); tg3_halt_cpu(tp, RX_CPU_BASE); if (!err) tg3_nvram_unlock(tp); } } tg3_write_sig_post_reset(tp, RESET_KIND_SHUTDOWN); return 0; } static void tg3_power_down(struct tg3 *tp) { tg3_power_down_prepare(tp); pci_wake_from_d3(tp->pdev, tg3_flag(tp, WOL_ENABLE)); pci_set_power_state(tp->pdev, PCI_D3hot); } static void tg3_aux_stat_to_speed_duplex(struct tg3 *tp, u32 val, u16 *speed, u8 *duplex) { switch (val & MII_TG3_AUX_STAT_SPDMASK) { case MII_TG3_AUX_STAT_10HALF: *speed = SPEED_10; *duplex = DUPLEX_HALF; break; case MII_TG3_AUX_STAT_10FULL: *speed = SPEED_10; *duplex = DUPLEX_FULL; break; case MII_TG3_AUX_STAT_100HALF: *speed = SPEED_100; *duplex = DUPLEX_HALF; break; case MII_TG3_AUX_STAT_100FULL: *speed = SPEED_100; *duplex = DUPLEX_FULL; break; case MII_TG3_AUX_STAT_1000HALF: *speed = SPEED_1000; *duplex = DUPLEX_HALF; break; case MII_TG3_AUX_STAT_1000FULL: *speed = SPEED_1000; *duplex = DUPLEX_FULL; break; default: if (tp->phy_flags & TG3_PHYFLG_IS_FET) { *speed = (val & MII_TG3_AUX_STAT_100) ? SPEED_100 : SPEED_10; *duplex = (val & MII_TG3_AUX_STAT_FULL) ? DUPLEX_FULL : DUPLEX_HALF; break; } *speed = SPEED_UNKNOWN; *duplex = DUPLEX_UNKNOWN; break; } } static int tg3_phy_autoneg_cfg(struct tg3 *tp, u32 advertise, u32 flowctrl) { int err = 0; u32 val, new_adv; new_adv = ADVERTISE_CSMA; new_adv |= ethtool_adv_to_mii_adv_t(advertise) & ADVERTISE_ALL; new_adv |= mii_advertise_flowctrl(flowctrl); err = tg3_writephy(tp, MII_ADVERTISE, new_adv); if (err) goto done; if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) { new_adv = ethtool_adv_to_mii_ctrl1000_t(advertise); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0) new_adv |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER; err = tg3_writephy(tp, MII_CTRL1000, new_adv); if (err) goto done; } if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) goto done; tw32(TG3_CPMU_EEE_MODE, tr32(TG3_CPMU_EEE_MODE) & ~TG3_CPMU_EEEMD_LPI_ENABLE); err = tg3_phy_toggle_auxctl_smdsp(tp, true); if (!err) { u32 err2; val = 0; /* Advertise 100-BaseTX EEE ability */ if (advertise & ADVERTISED_100baseT_Full) val |= MDIO_AN_EEE_ADV_100TX; /* Advertise 1000-BaseT EEE ability */ if (advertise & ADVERTISED_1000baseT_Full) val |= MDIO_AN_EEE_ADV_1000T; err = tg3_phy_cl45_write(tp, MDIO_MMD_AN, MDIO_AN_EEE_ADV, val); if (err) val = 0; switch (tg3_asic_rev(tp)) { case ASIC_REV_5717: case ASIC_REV_57765: case ASIC_REV_57766: case ASIC_REV_5719: /* If we advertised any eee advertisements above... */ if (val) val = MII_TG3_DSP_TAP26_ALNOKO | MII_TG3_DSP_TAP26_RMRXSTO | MII_TG3_DSP_TAP26_OPCSINPT; tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val); /* Fall through */ case ASIC_REV_5720: case ASIC_REV_5762: if (!tg3_phydsp_read(tp, MII_TG3_DSP_CH34TP2, &val)) tg3_phydsp_write(tp, MII_TG3_DSP_CH34TP2, val | MII_TG3_DSP_CH34TP2_HIBW01); } err2 = tg3_phy_toggle_auxctl_smdsp(tp, false); if (!err) err = err2; } done: return err; } static void tg3_phy_copper_begin(struct tg3 *tp) { if (tp->link_config.autoneg == AUTONEG_ENABLE || (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) { u32 adv, fc; if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) { adv = ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full; if (tg3_flag(tp, WOL_SPEED_100MB)) adv |= ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full; fc = FLOW_CTRL_TX | FLOW_CTRL_RX; } else { adv = tp->link_config.advertising; if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY) adv &= ~(ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full); fc = tp->link_config.flowctrl; } tg3_phy_autoneg_cfg(tp, adv, fc); tg3_writephy(tp, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART); } else { int i; u32 bmcr, orig_bmcr; tp->link_config.active_speed = tp->link_config.speed; tp->link_config.active_duplex = tp->link_config.duplex; if (tg3_asic_rev(tp) == ASIC_REV_5714) { /* With autoneg disabled, 5715 only links up when the * advertisement register has the configured speed * enabled. */ tg3_writephy(tp, MII_ADVERTISE, ADVERTISE_ALL); } bmcr = 0; switch (tp->link_config.speed) { default: case SPEED_10: break; case SPEED_100: bmcr |= BMCR_SPEED100; break; case SPEED_1000: bmcr |= BMCR_SPEED1000; break; } if (tp->link_config.duplex == DUPLEX_FULL) bmcr |= BMCR_FULLDPLX; if (!tg3_readphy(tp, MII_BMCR, &orig_bmcr) && (bmcr != orig_bmcr)) { tg3_writephy(tp, MII_BMCR, BMCR_LOOPBACK); for (i = 0; i < 1500; i++) { u32 tmp; udelay(10); if (tg3_readphy(tp, MII_BMSR, &tmp) || tg3_readphy(tp, MII_BMSR, &tmp)) continue; if (!(tmp & BMSR_LSTATUS)) { udelay(40); break; } } tg3_writephy(tp, MII_BMCR, bmcr); udelay(40); } } } static int tg3_init_5401phy_dsp(struct tg3 *tp) { int err; /* Turn off tap power management. */ /* Set Extended packet length bit */ err = tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, 0x4c20); err |= tg3_phydsp_write(tp, 0x0012, 0x1804); err |= tg3_phydsp_write(tp, 0x0013, 0x1204); err |= tg3_phydsp_write(tp, 0x8006, 0x0132); err |= tg3_phydsp_write(tp, 0x8006, 0x0232); err |= tg3_phydsp_write(tp, 0x201f, 0x0a20); udelay(40); return err; } static bool tg3_phy_copper_an_config_ok(struct tg3 *tp, u32 *lcladv) { u32 advmsk, tgtadv, advertising; advertising = tp->link_config.advertising; tgtadv = ethtool_adv_to_mii_adv_t(advertising) & ADVERTISE_ALL; advmsk = ADVERTISE_ALL; if (tp->link_config.active_duplex == DUPLEX_FULL) { tgtadv |= mii_advertise_flowctrl(tp->link_config.flowctrl); advmsk |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM; } if (tg3_readphy(tp, MII_ADVERTISE, lcladv)) return false; if ((*lcladv & advmsk) != tgtadv) return false; if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) { u32 tg3_ctrl; tgtadv = ethtool_adv_to_mii_ctrl1000_t(advertising); if (tg3_readphy(tp, MII_CTRL1000, &tg3_ctrl)) return false; if (tgtadv && (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0)) { tgtadv |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER; tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL | CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER); } else { tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL); } if (tg3_ctrl != tgtadv) return false; } return true; } static bool tg3_phy_copper_fetch_rmtadv(struct tg3 *tp, u32 *rmtadv) { u32 lpeth = 0; if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) { u32 val; if (tg3_readphy(tp, MII_STAT1000, &val)) return false; lpeth = mii_stat1000_to_ethtool_lpa_t(val); } if (tg3_readphy(tp, MII_LPA, rmtadv)) return false; lpeth |= mii_lpa_to_ethtool_lpa_t(*rmtadv); tp->link_config.rmt_adv = lpeth; return true; } static bool tg3_test_and_report_link_chg(struct tg3 *tp, int curr_link_up) { if (curr_link_up != tp->link_up) { if (curr_link_up) { netif_carrier_on(tp->dev); } else { netif_carrier_off(tp->dev); if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; } tg3_link_report(tp); return true; } return false; } static int tg3_setup_copper_phy(struct tg3 *tp, int force_reset) { int current_link_up; u32 bmsr, val; u32 lcl_adv, rmt_adv; u16 current_speed; u8 current_duplex; int i, err; tw32(MAC_EVENT, 0); tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED | MAC_STATUS_MI_COMPLETION | MAC_STATUS_LNKSTATE_CHANGED)); udelay(40); if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) { tw32_f(MAC_MI_MODE, (tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL)); udelay(80); } tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, 0); /* Some third-party PHYs need to be reset on link going * down. */ if ((tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_asic_rev(tp) == ASIC_REV_5705) && tp->link_up) { tg3_readphy(tp, MII_BMSR, &bmsr); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && !(bmsr & BMSR_LSTATUS)) force_reset = 1; } if (force_reset) tg3_phy_reset(tp); if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { tg3_readphy(tp, MII_BMSR, &bmsr); if (tg3_readphy(tp, MII_BMSR, &bmsr) || !tg3_flag(tp, INIT_COMPLETE)) bmsr = 0; if (!(bmsr & BMSR_LSTATUS)) { err = tg3_init_5401phy_dsp(tp); if (err) return err; tg3_readphy(tp, MII_BMSR, &bmsr); for (i = 0; i < 1000; i++) { udelay(10); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) { udelay(40); break; } } if ((tp->phy_id & TG3_PHY_ID_REV_MASK) == TG3_PHY_REV_BCM5401_B0 && !(bmsr & BMSR_LSTATUS) && tp->link_config.active_speed == SPEED_1000) { err = tg3_phy_reset(tp); if (!err) err = tg3_init_5401phy_dsp(tp); if (err) return err; } } } else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0) { /* 5701 {A0,B0} CRC bug workaround */ tg3_writephy(tp, 0x15, 0x0a75); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68); tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68); } /* Clear pending interrupts... */ tg3_readphy(tp, MII_TG3_ISTAT, &val); tg3_readphy(tp, MII_TG3_ISTAT, &val); if (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) tg3_writephy(tp, MII_TG3_IMASK, ~MII_TG3_INT_LINKCHG); else if (!(tp->phy_flags & TG3_PHYFLG_IS_FET)) tg3_writephy(tp, MII_TG3_IMASK, ~0); if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { if (tp->led_ctrl == LED_CTRL_MODE_PHY_1) tg3_writephy(tp, MII_TG3_EXT_CTRL, MII_TG3_EXT_CTRL_LNK3_LED_MODE); else tg3_writephy(tp, MII_TG3_EXT_CTRL, 0); } current_link_up = 0; current_speed = SPEED_UNKNOWN; current_duplex = DUPLEX_UNKNOWN; tp->phy_flags &= ~TG3_PHYFLG_MDIX_STATE; tp->link_config.rmt_adv = 0; if (tp->phy_flags & TG3_PHYFLG_CAPACITIVE_COUPLING) { err = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_MISCTEST, &val); if (!err && !(val & (1 << 10))) { tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_MISCTEST, val | (1 << 10)); goto relink; } } bmsr = 0; for (i = 0; i < 100; i++) { tg3_readphy(tp, MII_BMSR, &bmsr); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) break; udelay(40); } if (bmsr & BMSR_LSTATUS) { u32 aux_stat, bmcr; tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat); for (i = 0; i < 2000; i++) { udelay(10); if (!tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat) && aux_stat) break; } tg3_aux_stat_to_speed_duplex(tp, aux_stat, &current_speed, &current_duplex); bmcr = 0; for (i = 0; i < 200; i++) { tg3_readphy(tp, MII_BMCR, &bmcr); if (tg3_readphy(tp, MII_BMCR, &bmcr)) continue; if (bmcr && bmcr != 0x7fff) break; udelay(10); } lcl_adv = 0; rmt_adv = 0; tp->link_config.active_speed = current_speed; tp->link_config.active_duplex = current_duplex; if (tp->link_config.autoneg == AUTONEG_ENABLE) { if ((bmcr & BMCR_ANENABLE) && tg3_phy_copper_an_config_ok(tp, &lcl_adv) && tg3_phy_copper_fetch_rmtadv(tp, &rmt_adv)) current_link_up = 1; } else { if (!(bmcr & BMCR_ANENABLE) && tp->link_config.speed == current_speed && tp->link_config.duplex == current_duplex && tp->link_config.flowctrl == tp->link_config.active_flowctrl) { current_link_up = 1; } } if (current_link_up == 1 && tp->link_config.active_duplex == DUPLEX_FULL) { u32 reg, bit; if (tp->phy_flags & TG3_PHYFLG_IS_FET) { reg = MII_TG3_FET_GEN_STAT; bit = MII_TG3_FET_GEN_STAT_MDIXSTAT; } else { reg = MII_TG3_EXT_STAT; bit = MII_TG3_EXT_STAT_MDIX; } if (!tg3_readphy(tp, reg, &val) && (val & bit)) tp->phy_flags |= TG3_PHYFLG_MDIX_STATE; tg3_setup_flow_control(tp, lcl_adv, rmt_adv); } } relink: if (current_link_up == 0 || (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) { tg3_phy_copper_begin(tp); if (tg3_flag(tp, ROBOSWITCH)) { current_link_up = 1; /* FIXME: when BCM5325 switch is used use 100 MBit/s */ current_speed = SPEED_1000; current_duplex = DUPLEX_FULL; tp->link_config.active_speed = current_speed; tp->link_config.active_duplex = current_duplex; } tg3_readphy(tp, MII_BMSR, &bmsr); if ((!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) || (tp->mac_mode & MAC_MODE_PORT_INT_LPBACK)) current_link_up = 1; } tp->mac_mode &= ~MAC_MODE_PORT_MODE_MASK; if (current_link_up == 1) { if (tp->link_config.active_speed == SPEED_100 || tp->link_config.active_speed == SPEED_10) tp->mac_mode |= MAC_MODE_PORT_MODE_MII; else tp->mac_mode |= MAC_MODE_PORT_MODE_GMII; } else if (tp->phy_flags & TG3_PHYFLG_IS_FET) tp->mac_mode |= MAC_MODE_PORT_MODE_MII; else tp->mac_mode |= MAC_MODE_PORT_MODE_GMII; /* In order for the 5750 core in BCM4785 chip to work properly * in RGMII mode, the Led Control Register must be set up. */ if (tg3_flag(tp, RGMII_MODE)) { u32 led_ctrl = tr32(MAC_LED_CTRL); led_ctrl &= ~(LED_CTRL_1000MBPS_ON | LED_CTRL_100MBPS_ON); if (tp->link_config.active_speed == SPEED_10) led_ctrl |= LED_CTRL_LNKLED_OVERRIDE; else if (tp->link_config.active_speed == SPEED_100) led_ctrl |= (LED_CTRL_LNKLED_OVERRIDE | LED_CTRL_100MBPS_ON); else if (tp->link_config.active_speed == SPEED_1000) led_ctrl |= (LED_CTRL_LNKLED_OVERRIDE | LED_CTRL_1000MBPS_ON); tw32(MAC_LED_CTRL, led_ctrl); udelay(40); } tp->mac_mode &= ~MAC_MODE_HALF_DUPLEX; if (tp->link_config.active_duplex == DUPLEX_HALF) tp->mac_mode |= MAC_MODE_HALF_DUPLEX; if (tg3_asic_rev(tp) == ASIC_REV_5700) { if (current_link_up == 1 && tg3_5700_link_polarity(tp, tp->link_config.active_speed)) tp->mac_mode |= MAC_MODE_LINK_POLARITY; else tp->mac_mode &= ~MAC_MODE_LINK_POLARITY; } /* ??? Without this setting Netgear GA302T PHY does not * ??? send/receive packets... */ if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411 && tg3_chip_rev_id(tp) == CHIPREV_ID_5700_ALTIMA) { tp->mi_mode |= MAC_MI_MODE_AUTO_POLL; tw32_f(MAC_MI_MODE, tp->mi_mode); udelay(80); } tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tg3_phy_eee_adjust(tp, current_link_up); if (tg3_flag(tp, USE_LINKCHG_REG)) { /* Polled via timer. */ tw32_f(MAC_EVENT, 0); } else { tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED); } udelay(40); if (tg3_asic_rev(tp) == ASIC_REV_5700 && current_link_up == 1 && tp->link_config.active_speed == SPEED_1000 && (tg3_flag(tp, PCIX_MODE) || tg3_flag(tp, PCI_HIGH_SPEED))) { udelay(120); tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED)); udelay(40); tg3_write_mem(tp, NIC_SRAM_FIRMWARE_MBOX, NIC_SRAM_FIRMWARE_MBOX_MAGIC2); } /* Prevent send BD corruption. */ if (tg3_flag(tp, CLKREQ_BUG)) { if (tp->link_config.active_speed == SPEED_100 || tp->link_config.active_speed == SPEED_10) pcie_capability_clear_word(tp->pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_CLKREQ_EN); else pcie_capability_set_word(tp->pdev, PCI_EXP_LNKCTL, PCI_EXP_LNKCTL_CLKREQ_EN); } tg3_test_and_report_link_chg(tp, current_link_up); return 0; } struct tg3_fiber_aneginfo { int state; #define ANEG_STATE_UNKNOWN 0 #define ANEG_STATE_AN_ENABLE 1 #define ANEG_STATE_RESTART_INIT 2 #define ANEG_STATE_RESTART 3 #define ANEG_STATE_DISABLE_LINK_OK 4 #define ANEG_STATE_ABILITY_DETECT_INIT 5 #define ANEG_STATE_ABILITY_DETECT 6 #define ANEG_STATE_ACK_DETECT_INIT 7 #define ANEG_STATE_ACK_DETECT 8 #define ANEG_STATE_COMPLETE_ACK_INIT 9 #define ANEG_STATE_COMPLETE_ACK 10 #define ANEG_STATE_IDLE_DETECT_INIT 11 #define ANEG_STATE_IDLE_DETECT 12 #define ANEG_STATE_LINK_OK 13 #define ANEG_STATE_NEXT_PAGE_WAIT_INIT 14 #define ANEG_STATE_NEXT_PAGE_WAIT 15 u32 flags; #define MR_AN_ENABLE 0x00000001 #define MR_RESTART_AN 0x00000002 #define MR_AN_COMPLETE 0x00000004 #define MR_PAGE_RX 0x00000008 #define MR_NP_LOADED 0x00000010 #define MR_TOGGLE_TX 0x00000020 #define MR_LP_ADV_FULL_DUPLEX 0x00000040 #define MR_LP_ADV_HALF_DUPLEX 0x00000080 #define MR_LP_ADV_SYM_PAUSE 0x00000100 #define MR_LP_ADV_ASYM_PAUSE 0x00000200 #define MR_LP_ADV_REMOTE_FAULT1 0x00000400 #define MR_LP_ADV_REMOTE_FAULT2 0x00000800 #define MR_LP_ADV_NEXT_PAGE 0x00001000 #define MR_TOGGLE_RX 0x00002000 #define MR_NP_RX 0x00004000 #define MR_LINK_OK 0x80000000 unsigned long link_time, cur_time; u32 ability_match_cfg; int ability_match_count; char ability_match, idle_match, ack_match; u32 txconfig, rxconfig; #define ANEG_CFG_NP 0x00000080 #define ANEG_CFG_ACK 0x00000040 #define ANEG_CFG_RF2 0x00000020 #define ANEG_CFG_RF1 0x00000010 #define ANEG_CFG_PS2 0x00000001 #define ANEG_CFG_PS1 0x00008000 #define ANEG_CFG_HD 0x00004000 #define ANEG_CFG_FD 0x00002000 #define ANEG_CFG_INVAL 0x00001f06 }; #define ANEG_OK 0 #define ANEG_DONE 1 #define ANEG_TIMER_ENAB 2 #define ANEG_FAILED -1 #define ANEG_STATE_SETTLE_TIME 10000 static int tg3_fiber_aneg_smachine(struct tg3 *tp, struct tg3_fiber_aneginfo *ap) { u16 flowctrl; unsigned long delta; u32 rx_cfg_reg; int ret; if (ap->state == ANEG_STATE_UNKNOWN) { ap->rxconfig = 0; ap->link_time = 0; ap->cur_time = 0; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->idle_match = 0; ap->ack_match = 0; } ap->cur_time++; if (tr32(MAC_STATUS) & MAC_STATUS_RCVD_CFG) { rx_cfg_reg = tr32(MAC_RX_AUTO_NEG); if (rx_cfg_reg != ap->ability_match_cfg) { ap->ability_match_cfg = rx_cfg_reg; ap->ability_match = 0; ap->ability_match_count = 0; } else { if (++ap->ability_match_count > 1) { ap->ability_match = 1; ap->ability_match_cfg = rx_cfg_reg; } } if (rx_cfg_reg & ANEG_CFG_ACK) ap->ack_match = 1; else ap->ack_match = 0; ap->idle_match = 0; } else { ap->idle_match = 1; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->ack_match = 0; rx_cfg_reg = 0; } ap->rxconfig = rx_cfg_reg; ret = ANEG_OK; switch (ap->state) { case ANEG_STATE_UNKNOWN: if (ap->flags & (MR_AN_ENABLE | MR_RESTART_AN)) ap->state = ANEG_STATE_AN_ENABLE; /* fallthru */ case ANEG_STATE_AN_ENABLE: ap->flags &= ~(MR_AN_COMPLETE | MR_PAGE_RX); if (ap->flags & MR_AN_ENABLE) { ap->link_time = 0; ap->cur_time = 0; ap->ability_match_cfg = 0; ap->ability_match_count = 0; ap->ability_match = 0; ap->idle_match = 0; ap->ack_match = 0; ap->state = ANEG_STATE_RESTART_INIT; } else { ap->state = ANEG_STATE_DISABLE_LINK_OK; } break; case ANEG_STATE_RESTART_INIT: ap->link_time = ap->cur_time; ap->flags &= ~(MR_NP_LOADED); ap->txconfig = 0; tw32(MAC_TX_AUTO_NEG, 0); tp->mac_mode |= MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ret = ANEG_TIMER_ENAB; ap->state = ANEG_STATE_RESTART; /* fallthru */ case ANEG_STATE_RESTART: delta = ap->cur_time - ap->link_time; if (delta > ANEG_STATE_SETTLE_TIME) ap->state = ANEG_STATE_ABILITY_DETECT_INIT; else ret = ANEG_TIMER_ENAB; break; case ANEG_STATE_DISABLE_LINK_OK: ret = ANEG_DONE; break; case ANEG_STATE_ABILITY_DETECT_INIT: ap->flags &= ~(MR_TOGGLE_TX); ap->txconfig = ANEG_CFG_FD; flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl); if (flowctrl & ADVERTISE_1000XPAUSE) ap->txconfig |= ANEG_CFG_PS1; if (flowctrl & ADVERTISE_1000XPSE_ASYM) ap->txconfig |= ANEG_CFG_PS2; tw32(MAC_TX_AUTO_NEG, ap->txconfig); tp->mac_mode |= MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = ANEG_STATE_ABILITY_DETECT; break; case ANEG_STATE_ABILITY_DETECT: if (ap->ability_match != 0 && ap->rxconfig != 0) ap->state = ANEG_STATE_ACK_DETECT_INIT; break; case ANEG_STATE_ACK_DETECT_INIT: ap->txconfig |= ANEG_CFG_ACK; tw32(MAC_TX_AUTO_NEG, ap->txconfig); tp->mac_mode |= MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = ANEG_STATE_ACK_DETECT; /* fallthru */ case ANEG_STATE_ACK_DETECT: if (ap->ack_match != 0) { if ((ap->rxconfig & ~ANEG_CFG_ACK) == (ap->ability_match_cfg & ~ANEG_CFG_ACK)) { ap->state = ANEG_STATE_COMPLETE_ACK_INIT; } else { ap->state = ANEG_STATE_AN_ENABLE; } } else if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = ANEG_STATE_AN_ENABLE; } break; case ANEG_STATE_COMPLETE_ACK_INIT: if (ap->rxconfig & ANEG_CFG_INVAL) { ret = ANEG_FAILED; break; } ap->flags &= ~(MR_LP_ADV_FULL_DUPLEX | MR_LP_ADV_HALF_DUPLEX | MR_LP_ADV_SYM_PAUSE | MR_LP_ADV_ASYM_PAUSE | MR_LP_ADV_REMOTE_FAULT1 | MR_LP_ADV_REMOTE_FAULT2 | MR_LP_ADV_NEXT_PAGE | MR_TOGGLE_RX | MR_NP_RX); if (ap->rxconfig & ANEG_CFG_FD) ap->flags |= MR_LP_ADV_FULL_DUPLEX; if (ap->rxconfig & ANEG_CFG_HD) ap->flags |= MR_LP_ADV_HALF_DUPLEX; if (ap->rxconfig & ANEG_CFG_PS1) ap->flags |= MR_LP_ADV_SYM_PAUSE; if (ap->rxconfig & ANEG_CFG_PS2) ap->flags |= MR_LP_ADV_ASYM_PAUSE; if (ap->rxconfig & ANEG_CFG_RF1) ap->flags |= MR_LP_ADV_REMOTE_FAULT1; if (ap->rxconfig & ANEG_CFG_RF2) ap->flags |= MR_LP_ADV_REMOTE_FAULT2; if (ap->rxconfig & ANEG_CFG_NP) ap->flags |= MR_LP_ADV_NEXT_PAGE; ap->link_time = ap->cur_time; ap->flags ^= (MR_TOGGLE_TX); if (ap->rxconfig & 0x0008) ap->flags |= MR_TOGGLE_RX; if (ap->rxconfig & ANEG_CFG_NP) ap->flags |= MR_NP_RX; ap->flags |= MR_PAGE_RX; ap->state = ANEG_STATE_COMPLETE_ACK; ret = ANEG_TIMER_ENAB; break; case ANEG_STATE_COMPLETE_ACK: if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = ANEG_STATE_AN_ENABLE; break; } delta = ap->cur_time - ap->link_time; if (delta > ANEG_STATE_SETTLE_TIME) { if (!(ap->flags & (MR_LP_ADV_NEXT_PAGE))) { ap->state = ANEG_STATE_IDLE_DETECT_INIT; } else { if ((ap->txconfig & ANEG_CFG_NP) == 0 && !(ap->flags & MR_NP_RX)) { ap->state = ANEG_STATE_IDLE_DETECT_INIT; } else { ret = ANEG_FAILED; } } } break; case ANEG_STATE_IDLE_DETECT_INIT: ap->link_time = ap->cur_time; tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); ap->state = ANEG_STATE_IDLE_DETECT; ret = ANEG_TIMER_ENAB; break; case ANEG_STATE_IDLE_DETECT: if (ap->ability_match != 0 && ap->rxconfig == 0) { ap->state = ANEG_STATE_AN_ENABLE; break; } delta = ap->cur_time - ap->link_time; if (delta > ANEG_STATE_SETTLE_TIME) { /* XXX another gem from the Broadcom driver :( */ ap->state = ANEG_STATE_LINK_OK; } break; case ANEG_STATE_LINK_OK: ap->flags |= (MR_AN_COMPLETE | MR_LINK_OK); ret = ANEG_DONE; break; case ANEG_STATE_NEXT_PAGE_WAIT_INIT: /* ??? unimplemented */ break; case ANEG_STATE_NEXT_PAGE_WAIT: /* ??? unimplemented */ break; default: ret = ANEG_FAILED; break; } return ret; } static int fiber_autoneg(struct tg3 *tp, u32 *txflags, u32 *rxflags) { int res = 0; struct tg3_fiber_aneginfo aninfo; int status = ANEG_FAILED; unsigned int tick; u32 tmp; tw32_f(MAC_TX_AUTO_NEG, 0); tmp = tp->mac_mode & ~MAC_MODE_PORT_MODE_MASK; tw32_f(MAC_MODE, tmp | MAC_MODE_PORT_MODE_GMII); udelay(40); tw32_f(MAC_MODE, tp->mac_mode | MAC_MODE_SEND_CONFIGS); udelay(40); memset(&aninfo, 0, sizeof(aninfo)); aninfo.flags |= MR_AN_ENABLE; aninfo.state = ANEG_STATE_UNKNOWN; aninfo.cur_time = 0; tick = 0; while (++tick < 195000) { status = tg3_fiber_aneg_smachine(tp, &aninfo); if (status == ANEG_DONE || status == ANEG_FAILED) break; udelay(1); } tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); *txflags = aninfo.txconfig; *rxflags = aninfo.flags; if (status == ANEG_DONE && (aninfo.flags & (MR_AN_COMPLETE | MR_LINK_OK | MR_LP_ADV_FULL_DUPLEX))) res = 1; return res; } static void tg3_init_bcm8002(struct tg3 *tp) { u32 mac_status = tr32(MAC_STATUS); int i; /* Reset when initting first time or we have a link. */ if (tg3_flag(tp, INIT_COMPLETE) && !(mac_status & MAC_STATUS_PCS_SYNCED)) return; /* Set PLL lock range. */ tg3_writephy(tp, 0x16, 0x8007); /* SW reset */ tg3_writephy(tp, MII_BMCR, BMCR_RESET); /* Wait for reset to complete. */ /* XXX schedule_timeout() ... */ for (i = 0; i < 500; i++) udelay(10); /* Config mode; select PMA/Ch 1 regs. */ tg3_writephy(tp, 0x10, 0x8411); /* Enable auto-lock and comdet, select txclk for tx. */ tg3_writephy(tp, 0x11, 0x0a10); tg3_writephy(tp, 0x18, 0x00a0); tg3_writephy(tp, 0x16, 0x41ff); /* Assert and deassert POR. */ tg3_writephy(tp, 0x13, 0x0400); udelay(40); tg3_writephy(tp, 0x13, 0x0000); tg3_writephy(tp, 0x11, 0x0a50); udelay(40); tg3_writephy(tp, 0x11, 0x0a10); /* Wait for signal to stabilize */ /* XXX schedule_timeout() ... */ for (i = 0; i < 15000; i++) udelay(10); /* Deselect the channel register so we can read the PHYID * later. */ tg3_writephy(tp, 0x10, 0x8011); } static int tg3_setup_fiber_hw_autoneg(struct tg3 *tp, u32 mac_status) { u16 flowctrl; u32 sg_dig_ctrl, sg_dig_status; u32 serdes_cfg, expected_sg_dig_ctrl; int workaround, port_a; int current_link_up; serdes_cfg = 0; expected_sg_dig_ctrl = 0; workaround = 0; port_a = 1; current_link_up = 0; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5704_A0 && tg3_chip_rev_id(tp) != CHIPREV_ID_5704_A1) { workaround = 1; if (tr32(TG3PCI_DUAL_MAC_CTRL) & DUAL_MAC_CTRL_ID) port_a = 0; /* preserve bits 0-11,13,14 for signal pre-emphasis */ /* preserve bits 20-23 for voltage regulator */ serdes_cfg = tr32(MAC_SERDES_CFG) & 0x00f06fff; } sg_dig_ctrl = tr32(SG_DIG_CTRL); if (tp->link_config.autoneg != AUTONEG_ENABLE) { if (sg_dig_ctrl & SG_DIG_USING_HW_AUTONEG) { if (workaround) { u32 val = serdes_cfg; if (port_a) val |= 0xc010000; else val |= 0x4010000; tw32_f(MAC_SERDES_CFG, val); } tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP); } if (mac_status & MAC_STATUS_PCS_SYNCED) { tg3_setup_flow_control(tp, 0, 0); current_link_up = 1; } goto out; } /* Want auto-negotiation. */ expected_sg_dig_ctrl = SG_DIG_USING_HW_AUTONEG | SG_DIG_COMMON_SETUP; flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl); if (flowctrl & ADVERTISE_1000XPAUSE) expected_sg_dig_ctrl |= SG_DIG_PAUSE_CAP; if (flowctrl & ADVERTISE_1000XPSE_ASYM) expected_sg_dig_ctrl |= SG_DIG_ASYM_PAUSE; if (sg_dig_ctrl != expected_sg_dig_ctrl) { if ((tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT) && tp->serdes_counter && ((mac_status & (MAC_STATUS_PCS_SYNCED | MAC_STATUS_RCVD_CFG)) == MAC_STATUS_PCS_SYNCED)) { tp->serdes_counter--; current_link_up = 1; goto out; } restart_autoneg: if (workaround) tw32_f(MAC_SERDES_CFG, serdes_cfg | 0xc011000); tw32_f(SG_DIG_CTRL, expected_sg_dig_ctrl | SG_DIG_SOFT_RESET); udelay(5); tw32_f(SG_DIG_CTRL, expected_sg_dig_ctrl); tp->serdes_counter = SERDES_AN_TIMEOUT_5704S; tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; } else if (mac_status & (MAC_STATUS_PCS_SYNCED | MAC_STATUS_SIGNAL_DET)) { sg_dig_status = tr32(SG_DIG_STATUS); mac_status = tr32(MAC_STATUS); if ((sg_dig_status & SG_DIG_AUTONEG_COMPLETE) && (mac_status & MAC_STATUS_PCS_SYNCED)) { u32 local_adv = 0, remote_adv = 0; if (sg_dig_ctrl & SG_DIG_PAUSE_CAP) local_adv |= ADVERTISE_1000XPAUSE; if (sg_dig_ctrl & SG_DIG_ASYM_PAUSE) local_adv |= ADVERTISE_1000XPSE_ASYM; if (sg_dig_status & SG_DIG_PARTNER_PAUSE_CAPABLE) remote_adv |= LPA_1000XPAUSE; if (sg_dig_status & SG_DIG_PARTNER_ASYM_PAUSE) remote_adv |= LPA_1000XPAUSE_ASYM; tp->link_config.rmt_adv = mii_adv_to_ethtool_adv_x(remote_adv); tg3_setup_flow_control(tp, local_adv, remote_adv); current_link_up = 1; tp->serdes_counter = 0; tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; } else if (!(sg_dig_status & SG_DIG_AUTONEG_COMPLETE)) { if (tp->serdes_counter) tp->serdes_counter--; else { if (workaround) { u32 val = serdes_cfg; if (port_a) val |= 0xc010000; else val |= 0x4010000; tw32_f(MAC_SERDES_CFG, val); } tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP); udelay(40); /* Link parallel detection - link is up */ /* only if we have PCS_SYNC and not */ /* receiving config code words */ mac_status = tr32(MAC_STATUS); if ((mac_status & MAC_STATUS_PCS_SYNCED) && !(mac_status & MAC_STATUS_RCVD_CFG)) { tg3_setup_flow_control(tp, 0, 0); current_link_up = 1; tp->phy_flags |= TG3_PHYFLG_PARALLEL_DETECT; tp->serdes_counter = SERDES_PARALLEL_DET_TIMEOUT; } else goto restart_autoneg; } } } else { tp->serdes_counter = SERDES_AN_TIMEOUT_5704S; tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; } out: return current_link_up; } static int tg3_setup_fiber_by_hand(struct tg3 *tp, u32 mac_status) { int current_link_up = 0; if (!(mac_status & MAC_STATUS_PCS_SYNCED)) goto out; if (tp->link_config.autoneg == AUTONEG_ENABLE) { u32 txflags, rxflags; int i; if (fiber_autoneg(tp, &txflags, &rxflags)) { u32 local_adv = 0, remote_adv = 0; if (txflags & ANEG_CFG_PS1) local_adv |= ADVERTISE_1000XPAUSE; if (txflags & ANEG_CFG_PS2) local_adv |= ADVERTISE_1000XPSE_ASYM; if (rxflags & MR_LP_ADV_SYM_PAUSE) remote_adv |= LPA_1000XPAUSE; if (rxflags & MR_LP_ADV_ASYM_PAUSE) remote_adv |= LPA_1000XPAUSE_ASYM; tp->link_config.rmt_adv = mii_adv_to_ethtool_adv_x(remote_adv); tg3_setup_flow_control(tp, local_adv, remote_adv); current_link_up = 1; } for (i = 0; i < 30; i++) { udelay(20); tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED)); udelay(40); if ((tr32(MAC_STATUS) & (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED)) == 0) break; } mac_status = tr32(MAC_STATUS); if (current_link_up == 0 && (mac_status & MAC_STATUS_PCS_SYNCED) && !(mac_status & MAC_STATUS_RCVD_CFG)) current_link_up = 1; } else { tg3_setup_flow_control(tp, 0, 0); /* Forcing 1000FD link up. */ current_link_up = 1; tw32_f(MAC_MODE, (tp->mac_mode | MAC_MODE_SEND_CONFIGS)); udelay(40); tw32_f(MAC_MODE, tp->mac_mode); udelay(40); } out: return current_link_up; } static int tg3_setup_fiber_phy(struct tg3 *tp, int force_reset) { u32 orig_pause_cfg; u16 orig_active_speed; u8 orig_active_duplex; u32 mac_status; int current_link_up; int i; orig_pause_cfg = tp->link_config.active_flowctrl; orig_active_speed = tp->link_config.active_speed; orig_active_duplex = tp->link_config.active_duplex; if (!tg3_flag(tp, HW_AUTONEG) && tp->link_up && tg3_flag(tp, INIT_COMPLETE)) { mac_status = tr32(MAC_STATUS); mac_status &= (MAC_STATUS_PCS_SYNCED | MAC_STATUS_SIGNAL_DET | MAC_STATUS_CFG_CHANGED | MAC_STATUS_RCVD_CFG); if (mac_status == (MAC_STATUS_PCS_SYNCED | MAC_STATUS_SIGNAL_DET)) { tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED)); return 0; } } tw32_f(MAC_TX_AUTO_NEG, 0); tp->mac_mode &= ~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX); tp->mac_mode |= MAC_MODE_PORT_MODE_TBI; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); if (tp->phy_id == TG3_PHY_ID_BCM8002) tg3_init_bcm8002(tp); /* Enable link change event even when serdes polling. */ tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED); udelay(40); current_link_up = 0; tp->link_config.rmt_adv = 0; mac_status = tr32(MAC_STATUS); if (tg3_flag(tp, HW_AUTONEG)) current_link_up = tg3_setup_fiber_hw_autoneg(tp, mac_status); else current_link_up = tg3_setup_fiber_by_hand(tp, mac_status); tp->napi[0].hw_status->status = (SD_STATUS_UPDATED | (tp->napi[0].hw_status->status & ~SD_STATUS_LINK_CHG)); for (i = 0; i < 100; i++) { tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED)); udelay(5); if ((tr32(MAC_STATUS) & (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED | MAC_STATUS_LNKSTATE_CHANGED)) == 0) break; } mac_status = tr32(MAC_STATUS); if ((mac_status & MAC_STATUS_PCS_SYNCED) == 0) { current_link_up = 0; if (tp->link_config.autoneg == AUTONEG_ENABLE && tp->serdes_counter == 0) { tw32_f(MAC_MODE, (tp->mac_mode | MAC_MODE_SEND_CONFIGS)); udelay(1); tw32_f(MAC_MODE, tp->mac_mode); } } if (current_link_up == 1) { tp->link_config.active_speed = SPEED_1000; tp->link_config.active_duplex = DUPLEX_FULL; tw32(MAC_LED_CTRL, (tp->led_ctrl | LED_CTRL_LNKLED_OVERRIDE | LED_CTRL_1000MBPS_ON)); } else { tp->link_config.active_speed = SPEED_UNKNOWN; tp->link_config.active_duplex = DUPLEX_UNKNOWN; tw32(MAC_LED_CTRL, (tp->led_ctrl | LED_CTRL_LNKLED_OVERRIDE | LED_CTRL_TRAFFIC_OVERRIDE)); } if (!tg3_test_and_report_link_chg(tp, current_link_up)) { u32 now_pause_cfg = tp->link_config.active_flowctrl; if (orig_pause_cfg != now_pause_cfg || orig_active_speed != tp->link_config.active_speed || orig_active_duplex != tp->link_config.active_duplex) tg3_link_report(tp); } return 0; } static int tg3_setup_fiber_mii_phy(struct tg3 *tp, int force_reset) { int current_link_up, err = 0; u32 bmsr, bmcr; u16 current_speed; u8 current_duplex; u32 local_adv, remote_adv; tp->mac_mode |= MAC_MODE_PORT_MODE_GMII; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tw32(MAC_EVENT, 0); tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED | MAC_STATUS_MI_COMPLETION | MAC_STATUS_LNKSTATE_CHANGED)); udelay(40); if (force_reset) tg3_phy_reset(tp); current_link_up = 0; current_speed = SPEED_UNKNOWN; current_duplex = DUPLEX_UNKNOWN; tp->link_config.rmt_adv = 0; err |= tg3_readphy(tp, MII_BMSR, &bmsr); err |= tg3_readphy(tp, MII_BMSR, &bmsr); if (tg3_asic_rev(tp) == ASIC_REV_5714) { if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) bmsr |= BMSR_LSTATUS; else bmsr &= ~BMSR_LSTATUS; } err |= tg3_readphy(tp, MII_BMCR, &bmcr); if ((tp->link_config.autoneg == AUTONEG_ENABLE) && !force_reset && (tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT)) { /* do nothing, just check for link up at the end */ } else if (tp->link_config.autoneg == AUTONEG_ENABLE) { u32 adv, newadv; err |= tg3_readphy(tp, MII_ADVERTISE, &adv); newadv = adv & ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF | ADVERTISE_1000XPAUSE | ADVERTISE_1000XPSE_ASYM | ADVERTISE_SLCT); newadv |= tg3_advert_flowctrl_1000X(tp->link_config.flowctrl); newadv |= ethtool_adv_to_mii_adv_x(tp->link_config.advertising); if ((newadv != adv) || !(bmcr & BMCR_ANENABLE)) { tg3_writephy(tp, MII_ADVERTISE, newadv); bmcr |= BMCR_ANENABLE | BMCR_ANRESTART; tg3_writephy(tp, MII_BMCR, bmcr); tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED); tp->serdes_counter = SERDES_AN_TIMEOUT_5714S; tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; return err; } } else { u32 new_bmcr; bmcr &= ~BMCR_SPEED1000; new_bmcr = bmcr & ~(BMCR_ANENABLE | BMCR_FULLDPLX); if (tp->link_config.duplex == DUPLEX_FULL) new_bmcr |= BMCR_FULLDPLX; if (new_bmcr != bmcr) { /* BMCR_SPEED1000 is a reserved bit that needs * to be set on write. */ new_bmcr |= BMCR_SPEED1000; /* Force a linkdown */ if (tp->link_up) { u32 adv; err |= tg3_readphy(tp, MII_ADVERTISE, &adv); adv &= ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF | ADVERTISE_SLCT); tg3_writephy(tp, MII_ADVERTISE, adv); tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); udelay(10); tg3_carrier_off(tp); } tg3_writephy(tp, MII_BMCR, new_bmcr); bmcr = new_bmcr; err |= tg3_readphy(tp, MII_BMSR, &bmsr); err |= tg3_readphy(tp, MII_BMSR, &bmsr); if (tg3_asic_rev(tp) == ASIC_REV_5714) { if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) bmsr |= BMSR_LSTATUS; else bmsr &= ~BMSR_LSTATUS; } tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; } } if (bmsr & BMSR_LSTATUS) { current_speed = SPEED_1000; current_link_up = 1; if (bmcr & BMCR_FULLDPLX) current_duplex = DUPLEX_FULL; else current_duplex = DUPLEX_HALF; local_adv = 0; remote_adv = 0; if (bmcr & BMCR_ANENABLE) { u32 common; err |= tg3_readphy(tp, MII_ADVERTISE, &local_adv); err |= tg3_readphy(tp, MII_LPA, &remote_adv); common = local_adv & remote_adv; if (common & (ADVERTISE_1000XHALF | ADVERTISE_1000XFULL)) { if (common & ADVERTISE_1000XFULL) current_duplex = DUPLEX_FULL; else current_duplex = DUPLEX_HALF; tp->link_config.rmt_adv = mii_adv_to_ethtool_adv_x(remote_adv); } else if (!tg3_flag(tp, 5780_CLASS)) { /* Link is up via parallel detect */ } else { current_link_up = 0; } } } if (current_link_up == 1 && current_duplex == DUPLEX_FULL) tg3_setup_flow_control(tp, local_adv, remote_adv); tp->mac_mode &= ~MAC_MODE_HALF_DUPLEX; if (tp->link_config.active_duplex == DUPLEX_HALF) tp->mac_mode |= MAC_MODE_HALF_DUPLEX; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED); tp->link_config.active_speed = current_speed; tp->link_config.active_duplex = current_duplex; tg3_test_and_report_link_chg(tp, current_link_up); return err; } static void tg3_serdes_parallel_detect(struct tg3 *tp) { if (tp->serdes_counter) { /* Give autoneg time to complete. */ tp->serdes_counter--; return; } if (!tp->link_up && (tp->link_config.autoneg == AUTONEG_ENABLE)) { u32 bmcr; tg3_readphy(tp, MII_BMCR, &bmcr); if (bmcr & BMCR_ANENABLE) { u32 phy1, phy2; /* Select shadow register 0x1f */ tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x7c00); tg3_readphy(tp, MII_TG3_MISC_SHDW, &phy1); /* Select expansion interrupt status register */ tg3_writephy(tp, MII_TG3_DSP_ADDRESS, MII_TG3_DSP_EXP1_INT_STAT); tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2); tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2); if ((phy1 & 0x10) && !(phy2 & 0x20)) { /* We have signal detect and not receiving * config code words, link is up by parallel * detection. */ bmcr &= ~BMCR_ANENABLE; bmcr |= BMCR_SPEED1000 | BMCR_FULLDPLX; tg3_writephy(tp, MII_BMCR, bmcr); tp->phy_flags |= TG3_PHYFLG_PARALLEL_DETECT; } } } else if (tp->link_up && (tp->link_config.autoneg == AUTONEG_ENABLE) && (tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT)) { u32 phy2; /* Select expansion interrupt status register */ tg3_writephy(tp, MII_TG3_DSP_ADDRESS, MII_TG3_DSP_EXP1_INT_STAT); tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2); if (phy2 & 0x20) { u32 bmcr; /* Config code words received, turn on autoneg. */ tg3_readphy(tp, MII_BMCR, &bmcr); tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANENABLE); tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; } } } static int tg3_setup_phy(struct tg3 *tp, int force_reset) { u32 val; int err; if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) err = tg3_setup_fiber_phy(tp, force_reset); else if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) err = tg3_setup_fiber_mii_phy(tp, force_reset); else err = tg3_setup_copper_phy(tp, force_reset); if (tg3_chip_rev(tp) == CHIPREV_5784_AX) { u32 scale; val = tr32(TG3_CPMU_CLCK_STAT) & CPMU_CLCK_STAT_MAC_CLCK_MASK; if (val == CPMU_CLCK_STAT_MAC_CLCK_62_5) scale = 65; else if (val == CPMU_CLCK_STAT_MAC_CLCK_6_25) scale = 6; else scale = 12; val = tr32(GRC_MISC_CFG) & ~GRC_MISC_CFG_PRESCALAR_MASK; val |= (scale << GRC_MISC_CFG_PRESCALAR_SHIFT); tw32(GRC_MISC_CFG, val); } val = (2 << TX_LENGTHS_IPG_CRS_SHIFT) | (6 << TX_LENGTHS_IPG_SHIFT); if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) val |= tr32(MAC_TX_LENGTHS) & (TX_LENGTHS_JMB_FRM_LEN_MSK | TX_LENGTHS_CNT_DWN_VAL_MSK); if (tp->link_config.active_speed == SPEED_1000 && tp->link_config.active_duplex == DUPLEX_HALF) tw32(MAC_TX_LENGTHS, val | (0xff << TX_LENGTHS_SLOT_TIME_SHIFT)); else tw32(MAC_TX_LENGTHS, val | (32 << TX_LENGTHS_SLOT_TIME_SHIFT)); if (!tg3_flag(tp, 5705_PLUS)) { if (tp->link_up) { tw32(HOSTCC_STAT_COAL_TICKS, tp->coal.stats_block_coalesce_usecs); } else { tw32(HOSTCC_STAT_COAL_TICKS, 0); } } if (tg3_flag(tp, ASPM_WORKAROUND)) { val = tr32(PCIE_PWR_MGMT_THRESH); if (!tp->link_up) val = (val & ~PCIE_PWR_MGMT_L1_THRESH_MSK) | tp->pwrmgmt_thresh; else val |= PCIE_PWR_MGMT_L1_THRESH_MSK; tw32(PCIE_PWR_MGMT_THRESH, val); } return err; } /* tp->lock must be held */ static u64 tg3_refclk_read(struct tg3 *tp) { u64 stamp = tr32(TG3_EAV_REF_CLCK_LSB); return stamp | (u64)tr32(TG3_EAV_REF_CLCK_MSB) << 32; } /* tp->lock must be held */ static void tg3_refclk_write(struct tg3 *tp, u64 newval) { tw32(TG3_EAV_REF_CLCK_CTL, TG3_EAV_REF_CLCK_CTL_STOP); tw32(TG3_EAV_REF_CLCK_LSB, newval & 0xffffffff); tw32(TG3_EAV_REF_CLCK_MSB, newval >> 32); tw32_f(TG3_EAV_REF_CLCK_CTL, TG3_EAV_REF_CLCK_CTL_RESUME); } static inline void tg3_full_lock(struct tg3 *tp, int irq_sync); static inline void tg3_full_unlock(struct tg3 *tp); static int tg3_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info) { struct tg3 *tp = netdev_priv(dev); info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE; if (tp->ptp_clock) info->phc_index = ptp_clock_index(tp->ptp_clock); else info->phc_index = -1; info->tx_types = (1 << HWTSTAMP_TX_OFF) | (1 << HWTSTAMP_TX_ON); info->rx_filters = (1 << HWTSTAMP_FILTER_NONE) | (1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT) | (1 << HWTSTAMP_FILTER_PTP_V2_L2_EVENT) | (1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT); return 0; } static int tg3_ptp_adjfreq(struct ptp_clock_info *ptp, s32 ppb) { struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); bool neg_adj = false; u32 correction = 0; if (ppb < 0) { neg_adj = true; ppb = -ppb; } /* Frequency adjustment is performed using hardware with a 24 bit * accumulator and a programmable correction value. On each clk, the * correction value gets added to the accumulator and when it * overflows, the time counter is incremented/decremented. * * So conversion from ppb to correction value is * ppb * (1 << 24) / 1000000000 */ correction = div_u64((u64)ppb * (1 << 24), 1000000000ULL) & TG3_EAV_REF_CLK_CORRECT_MASK; tg3_full_lock(tp, 0); if (correction) tw32(TG3_EAV_REF_CLK_CORRECT_CTL, TG3_EAV_REF_CLK_CORRECT_EN | (neg_adj ? TG3_EAV_REF_CLK_CORRECT_NEG : 0) | correction); else tw32(TG3_EAV_REF_CLK_CORRECT_CTL, 0); tg3_full_unlock(tp); return 0; } static int tg3_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) { struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); tg3_full_lock(tp, 0); tp->ptp_adjust += delta; tg3_full_unlock(tp); return 0; } static int tg3_ptp_gettime(struct ptp_clock_info *ptp, struct timespec *ts) { u64 ns; u32 remainder; struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); tg3_full_lock(tp, 0); ns = tg3_refclk_read(tp); ns += tp->ptp_adjust; tg3_full_unlock(tp); ts->tv_sec = div_u64_rem(ns, 1000000000, &remainder); ts->tv_nsec = remainder; return 0; } static int tg3_ptp_settime(struct ptp_clock_info *ptp, const struct timespec *ts) { u64 ns; struct tg3 *tp = container_of(ptp, struct tg3, ptp_info); ns = timespec_to_ns(ts); tg3_full_lock(tp, 0); tg3_refclk_write(tp, ns); tp->ptp_adjust = 0; tg3_full_unlock(tp); return 0; } static int tg3_ptp_enable(struct ptp_clock_info *ptp, struct ptp_clock_request *rq, int on) { return -EOPNOTSUPP; } static const struct ptp_clock_info tg3_ptp_caps = { .owner = THIS_MODULE, .name = "tg3 clock", .max_adj = 250000000, .n_alarm = 0, .n_ext_ts = 0, .n_per_out = 0, .pps = 0, .adjfreq = tg3_ptp_adjfreq, .adjtime = tg3_ptp_adjtime, .gettime = tg3_ptp_gettime, .settime = tg3_ptp_settime, .enable = tg3_ptp_enable, }; static void tg3_hwclock_to_timestamp(struct tg3 *tp, u64 hwclock, struct skb_shared_hwtstamps *timestamp) { memset(timestamp, 0, sizeof(struct skb_shared_hwtstamps)); timestamp->hwtstamp = ns_to_ktime((hwclock & TG3_TSTAMP_MASK) + tp->ptp_adjust); } /* tp->lock must be held */ static void tg3_ptp_init(struct tg3 *tp) { if (!tg3_flag(tp, PTP_CAPABLE)) return; /* Initialize the hardware clock to the system time. */ tg3_refclk_write(tp, ktime_to_ns(ktime_get_real())); tp->ptp_adjust = 0; tp->ptp_info = tg3_ptp_caps; } /* tp->lock must be held */ static void tg3_ptp_resume(struct tg3 *tp) { if (!tg3_flag(tp, PTP_CAPABLE)) return; tg3_refclk_write(tp, ktime_to_ns(ktime_get_real()) + tp->ptp_adjust); tp->ptp_adjust = 0; } static void tg3_ptp_fini(struct tg3 *tp) { if (!tg3_flag(tp, PTP_CAPABLE) || !tp->ptp_clock) return; ptp_clock_unregister(tp->ptp_clock); tp->ptp_clock = NULL; tp->ptp_adjust = 0; } static inline int tg3_irq_sync(struct tg3 *tp) { return tp->irq_sync; } static inline void tg3_rd32_loop(struct tg3 *tp, u32 *dst, u32 off, u32 len) { int i; dst = (u32 *)((u8 *)dst + off); for (i = 0; i < len; i += sizeof(u32)) *dst++ = tr32(off + i); } static void tg3_dump_legacy_regs(struct tg3 *tp, u32 *regs) { tg3_rd32_loop(tp, regs, TG3PCI_VENDOR, 0xb0); tg3_rd32_loop(tp, regs, MAILBOX_INTERRUPT_0, 0x200); tg3_rd32_loop(tp, regs, MAC_MODE, 0x4f0); tg3_rd32_loop(tp, regs, SNDDATAI_MODE, 0xe0); tg3_rd32_loop(tp, regs, SNDDATAC_MODE, 0x04); tg3_rd32_loop(tp, regs, SNDBDS_MODE, 0x80); tg3_rd32_loop(tp, regs, SNDBDI_MODE, 0x48); tg3_rd32_loop(tp, regs, SNDBDC_MODE, 0x04); tg3_rd32_loop(tp, regs, RCVLPC_MODE, 0x20); tg3_rd32_loop(tp, regs, RCVLPC_SELLST_BASE, 0x15c); tg3_rd32_loop(tp, regs, RCVDBDI_MODE, 0x0c); tg3_rd32_loop(tp, regs, RCVDBDI_JUMBO_BD, 0x3c); tg3_rd32_loop(tp, regs, RCVDBDI_BD_PROD_IDX_0, 0x44); tg3_rd32_loop(tp, regs, RCVDCC_MODE, 0x04); tg3_rd32_loop(tp, regs, RCVBDI_MODE, 0x20); tg3_rd32_loop(tp, regs, RCVCC_MODE, 0x14); tg3_rd32_loop(tp, regs, RCVLSC_MODE, 0x08); tg3_rd32_loop(tp, regs, MBFREE_MODE, 0x08); tg3_rd32_loop(tp, regs, HOSTCC_MODE, 0x100); if (tg3_flag(tp, SUPPORT_MSIX)) tg3_rd32_loop(tp, regs, HOSTCC_RXCOL_TICKS_VEC1, 0x180); tg3_rd32_loop(tp, regs, MEMARB_MODE, 0x10); tg3_rd32_loop(tp, regs, BUFMGR_MODE, 0x58); tg3_rd32_loop(tp, regs, RDMAC_MODE, 0x08); tg3_rd32_loop(tp, regs, WDMAC_MODE, 0x08); tg3_rd32_loop(tp, regs, RX_CPU_MODE, 0x04); tg3_rd32_loop(tp, regs, RX_CPU_STATE, 0x04); tg3_rd32_loop(tp, regs, RX_CPU_PGMCTR, 0x04); tg3_rd32_loop(tp, regs, RX_CPU_HWBKPT, 0x04); if (!tg3_flag(tp, 5705_PLUS)) { tg3_rd32_loop(tp, regs, TX_CPU_MODE, 0x04); tg3_rd32_loop(tp, regs, TX_CPU_STATE, 0x04); tg3_rd32_loop(tp, regs, TX_CPU_PGMCTR, 0x04); } tg3_rd32_loop(tp, regs, GRCMBOX_INTERRUPT_0, 0x110); tg3_rd32_loop(tp, regs, FTQ_RESET, 0x120); tg3_rd32_loop(tp, regs, MSGINT_MODE, 0x0c); tg3_rd32_loop(tp, regs, DMAC_MODE, 0x04); tg3_rd32_loop(tp, regs, GRC_MODE, 0x4c); if (tg3_flag(tp, NVRAM)) tg3_rd32_loop(tp, regs, NVRAM_CMD, 0x24); } static void tg3_dump_state(struct tg3 *tp) { int i; u32 *regs; regs = kzalloc(TG3_REG_BLK_SIZE, GFP_ATOMIC); if (!regs) return; if (tg3_flag(tp, PCI_EXPRESS)) { /* Read up to but not including private PCI registers */ for (i = 0; i < TG3_PCIE_TLDLPL_PORT; i += sizeof(u32)) regs[i / sizeof(u32)] = tr32(i); } else tg3_dump_legacy_regs(tp, regs); for (i = 0; i < TG3_REG_BLK_SIZE / sizeof(u32); i += 4) { if (!regs[i + 0] && !regs[i + 1] && !regs[i + 2] && !regs[i + 3]) continue; netdev_err(tp->dev, "0x%08x: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n", i * 4, regs[i + 0], regs[i + 1], regs[i + 2], regs[i + 3]); } kfree(regs); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; /* SW status block */ netdev_err(tp->dev, "%d: Host status block [%08x:%08x:(%04x:%04x:%04x):(%04x:%04x)]\n", i, tnapi->hw_status->status, tnapi->hw_status->status_tag, tnapi->hw_status->rx_jumbo_consumer, tnapi->hw_status->rx_consumer, tnapi->hw_status->rx_mini_consumer, tnapi->hw_status->idx[0].rx_producer, tnapi->hw_status->idx[0].tx_consumer); netdev_err(tp->dev, "%d: NAPI info [%08x:%08x:(%04x:%04x:%04x):%04x:(%04x:%04x:%04x:%04x)]\n", i, tnapi->last_tag, tnapi->last_irq_tag, tnapi->tx_prod, tnapi->tx_cons, tnapi->tx_pending, tnapi->rx_rcb_ptr, tnapi->prodring.rx_std_prod_idx, tnapi->prodring.rx_std_cons_idx, tnapi->prodring.rx_jmb_prod_idx, tnapi->prodring.rx_jmb_cons_idx); } } /* This is called whenever we suspect that the system chipset is re- * ordering the sequence of MMIO to the tx send mailbox. The symptom * is bogus tx completions. We try to recover by setting the * TG3_FLAG_MBOX_WRITE_REORDER flag and resetting the chip later * in the workqueue. */ static void tg3_tx_recover(struct tg3 *tp) { BUG_ON(tg3_flag(tp, MBOX_WRITE_REORDER) || tp->write32_tx_mbox == tg3_write_indirect_mbox); netdev_warn(tp->dev, "The system may be re-ordering memory-mapped I/O " "cycles to the network device, attempting to recover. " "Please report the problem to the driver maintainer " "and include system chipset information.\n"); spin_lock(&tp->lock); tg3_flag_set(tp, TX_RECOVERY_PENDING); spin_unlock(&tp->lock); } static inline u32 tg3_tx_avail(struct tg3_napi *tnapi) { /* Tell compiler to fetch tx indices from memory. */ barrier(); return tnapi->tx_pending - ((tnapi->tx_prod - tnapi->tx_cons) & (TG3_TX_RING_SIZE - 1)); } /* Tigon3 never reports partial packet sends. So we do not * need special logic to handle SKBs that have not had all * of their frags sent yet, like SunGEM does. */ static void tg3_tx(struct tg3_napi *tnapi) { struct tg3 *tp = tnapi->tp; u32 hw_idx = tnapi->hw_status->idx[0].tx_consumer; u32 sw_idx = tnapi->tx_cons; struct netdev_queue *txq; int index = tnapi - tp->napi; unsigned int pkts_compl = 0, bytes_compl = 0; if (tg3_flag(tp, ENABLE_TSS)) index--; txq = netdev_get_tx_queue(tp->dev, index); while (sw_idx != hw_idx) { struct tg3_tx_ring_info *ri = &tnapi->tx_buffers[sw_idx]; struct sk_buff *skb = ri->skb; int i, tx_bug = 0; if (unlikely(skb == NULL)) { tg3_tx_recover(tp); return; } if (tnapi->tx_ring[sw_idx].len_flags & TXD_FLAG_HWTSTAMP) { struct skb_shared_hwtstamps timestamp; u64 hwclock = tr32(TG3_TX_TSTAMP_LSB); hwclock |= (u64)tr32(TG3_TX_TSTAMP_MSB) << 32; tg3_hwclock_to_timestamp(tp, hwclock, &timestamp); skb_tstamp_tx(skb, &timestamp); } pci_unmap_single(tp->pdev, dma_unmap_addr(ri, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); ri->skb = NULL; while (ri->fragmented) { ri->fragmented = false; sw_idx = NEXT_TX(sw_idx); ri = &tnapi->tx_buffers[sw_idx]; } sw_idx = NEXT_TX(sw_idx); for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { ri = &tnapi->tx_buffers[sw_idx]; if (unlikely(ri->skb != NULL || sw_idx == hw_idx)) tx_bug = 1; pci_unmap_page(tp->pdev, dma_unmap_addr(ri, mapping), skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); while (ri->fragmented) { ri->fragmented = false; sw_idx = NEXT_TX(sw_idx); ri = &tnapi->tx_buffers[sw_idx]; } sw_idx = NEXT_TX(sw_idx); } pkts_compl++; bytes_compl += skb->len; dev_kfree_skb(skb); if (unlikely(tx_bug)) { tg3_tx_recover(tp); return; } } netdev_tx_completed_queue(txq, pkts_compl, bytes_compl); tnapi->tx_cons = sw_idx; /* Need to make the tx_cons update visible to tg3_start_xmit() * before checking for netif_queue_stopped(). Without the * memory barrier, there is a small possibility that tg3_start_xmit() * will miss it and cause the queue to be stopped forever. */ smp_mb(); if (unlikely(netif_tx_queue_stopped(txq) && (tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi)))) { __netif_tx_lock(txq, smp_processor_id()); if (netif_tx_queue_stopped(txq) && (tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi))) netif_tx_wake_queue(txq); __netif_tx_unlock(txq); } } static void tg3_frag_free(bool is_frag, void *data) { if (is_frag) put_page(virt_to_head_page(data)); else kfree(data); } static void tg3_rx_data_free(struct tg3 *tp, struct ring_info *ri, u32 map_sz) { unsigned int skb_size = SKB_DATA_ALIGN(map_sz + TG3_RX_OFFSET(tp)) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); if (!ri->data) return; pci_unmap_single(tp->pdev, dma_unmap_addr(ri, mapping), map_sz, PCI_DMA_FROMDEVICE); tg3_frag_free(skb_size <= PAGE_SIZE, ri->data); ri->data = NULL; } /* Returns size of skb allocated or < 0 on error. * * We only need to fill in the address because the other members * of the RX descriptor are invariant, see tg3_init_rings. * * Note the purposeful assymetry of cpu vs. chip accesses. For * posting buffers we only dirty the first cache line of the RX * descriptor (containing the address). Whereas for the RX status * buffers the cpu only reads the last cacheline of the RX descriptor * (to fetch the error flags, vlan tag, checksum, and opaque cookie). */ static int tg3_alloc_rx_data(struct tg3 *tp, struct tg3_rx_prodring_set *tpr, u32 opaque_key, u32 dest_idx_unmasked, unsigned int *frag_size) { struct tg3_rx_buffer_desc *desc; struct ring_info *map; u8 *data; dma_addr_t mapping; int skb_size, data_size, dest_idx; switch (opaque_key) { case RXD_OPAQUE_RING_STD: dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask; desc = &tpr->rx_std[dest_idx]; map = &tpr->rx_std_buffers[dest_idx]; data_size = tp->rx_pkt_map_sz; break; case RXD_OPAQUE_RING_JUMBO: dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask; desc = &tpr->rx_jmb[dest_idx].std; map = &tpr->rx_jmb_buffers[dest_idx]; data_size = TG3_RX_JMB_MAP_SZ; break; default: return -EINVAL; } /* Do not overwrite any of the map or rp information * until we are sure we can commit to a new buffer. * * Callers depend upon this behavior and assume that * we leave everything unchanged if we fail. */ skb_size = SKB_DATA_ALIGN(data_size + TG3_RX_OFFSET(tp)) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); if (skb_size <= PAGE_SIZE) { data = netdev_alloc_frag(skb_size); *frag_size = skb_size; } else { data = kmalloc(skb_size, GFP_ATOMIC); *frag_size = 0; } if (!data) return -ENOMEM; mapping = pci_map_single(tp->pdev, data + TG3_RX_OFFSET(tp), data_size, PCI_DMA_FROMDEVICE); if (unlikely(pci_dma_mapping_error(tp->pdev, mapping))) { tg3_frag_free(skb_size <= PAGE_SIZE, data); return -EIO; } map->data = data; dma_unmap_addr_set(map, mapping, mapping); desc->addr_hi = ((u64)mapping >> 32); desc->addr_lo = ((u64)mapping & 0xffffffff); return data_size; } /* We only need to move over in the address because the other * members of the RX descriptor are invariant. See notes above * tg3_alloc_rx_data for full details. */ static void tg3_recycle_rx(struct tg3_napi *tnapi, struct tg3_rx_prodring_set *dpr, u32 opaque_key, int src_idx, u32 dest_idx_unmasked) { struct tg3 *tp = tnapi->tp; struct tg3_rx_buffer_desc *src_desc, *dest_desc; struct ring_info *src_map, *dest_map; struct tg3_rx_prodring_set *spr = &tp->napi[0].prodring; int dest_idx; switch (opaque_key) { case RXD_OPAQUE_RING_STD: dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask; dest_desc = &dpr->rx_std[dest_idx]; dest_map = &dpr->rx_std_buffers[dest_idx]; src_desc = &spr->rx_std[src_idx]; src_map = &spr->rx_std_buffers[src_idx]; break; case RXD_OPAQUE_RING_JUMBO: dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask; dest_desc = &dpr->rx_jmb[dest_idx].std; dest_map = &dpr->rx_jmb_buffers[dest_idx]; src_desc = &spr->rx_jmb[src_idx].std; src_map = &spr->rx_jmb_buffers[src_idx]; break; default: return; } dest_map->data = src_map->data; dma_unmap_addr_set(dest_map, mapping, dma_unmap_addr(src_map, mapping)); dest_desc->addr_hi = src_desc->addr_hi; dest_desc->addr_lo = src_desc->addr_lo; /* Ensure that the update to the skb happens after the physical * addresses have been transferred to the new BD location. */ smp_wmb(); src_map->data = NULL; } /* The RX ring scheme is composed of multiple rings which post fresh * buffers to the chip, and one special ring the chip uses to report * status back to the host. * * The special ring reports the status of received packets to the * host. The chip does not write into the original descriptor the * RX buffer was obtained from. The chip simply takes the original * descriptor as provided by the host, updates the status and length * field, then writes this into the next status ring entry. * * Each ring the host uses to post buffers to the chip is described * by a TG3_BDINFO entry in the chips SRAM area. When a packet arrives, * it is first placed into the on-chip ram. When the packet's length * is known, it walks down the TG3_BDINFO entries to select the ring. * Each TG3_BDINFO specifies a MAXLEN field and the first TG3_BDINFO * which is within the range of the new packet's length is chosen. * * The "separate ring for rx status" scheme may sound queer, but it makes * sense from a cache coherency perspective. If only the host writes * to the buffer post rings, and only the chip writes to the rx status * rings, then cache lines never move beyond shared-modified state. * If both the host and chip were to write into the same ring, cache line * eviction could occur since both entities want it in an exclusive state. */ static int tg3_rx(struct tg3_napi *tnapi, int budget) { struct tg3 *tp = tnapi->tp; u32 work_mask, rx_std_posted = 0; u32 std_prod_idx, jmb_prod_idx; u32 sw_idx = tnapi->rx_rcb_ptr; u16 hw_idx; int received; struct tg3_rx_prodring_set *tpr = &tnapi->prodring; hw_idx = *(tnapi->rx_rcb_prod_idx); /* * We need to order the read of hw_idx and the read of * the opaque cookie. */ rmb(); work_mask = 0; received = 0; std_prod_idx = tpr->rx_std_prod_idx; jmb_prod_idx = tpr->rx_jmb_prod_idx; while (sw_idx != hw_idx && budget > 0) { struct ring_info *ri; struct tg3_rx_buffer_desc *desc = &tnapi->rx_rcb[sw_idx]; unsigned int len; struct sk_buff *skb; dma_addr_t dma_addr; u32 opaque_key, desc_idx, *post_ptr; u8 *data; u64 tstamp = 0; desc_idx = desc->opaque & RXD_OPAQUE_INDEX_MASK; opaque_key = desc->opaque & RXD_OPAQUE_RING_MASK; if (opaque_key == RXD_OPAQUE_RING_STD) { ri = &tp->napi[0].prodring.rx_std_buffers[desc_idx]; dma_addr = dma_unmap_addr(ri, mapping); data = ri->data; post_ptr = &std_prod_idx; rx_std_posted++; } else if (opaque_key == RXD_OPAQUE_RING_JUMBO) { ri = &tp->napi[0].prodring.rx_jmb_buffers[desc_idx]; dma_addr = dma_unmap_addr(ri, mapping); data = ri->data; post_ptr = &jmb_prod_idx; } else goto next_pkt_nopost; work_mask |= opaque_key; if ((desc->err_vlan & RXD_ERR_MASK) != 0 && (desc->err_vlan != RXD_ERR_ODD_NIBBLE_RCVD_MII)) { drop_it: tg3_recycle_rx(tnapi, tpr, opaque_key, desc_idx, *post_ptr); drop_it_no_recycle: /* Other statistics kept track of by card. */ tp->rx_dropped++; goto next_pkt; } prefetch(data + TG3_RX_OFFSET(tp)); len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT) - ETH_FCS_LEN; if ((desc->type_flags & RXD_FLAG_PTPSTAT_MASK) == RXD_FLAG_PTPSTAT_PTPV1 || (desc->type_flags & RXD_FLAG_PTPSTAT_MASK) == RXD_FLAG_PTPSTAT_PTPV2) { tstamp = tr32(TG3_RX_TSTAMP_LSB); tstamp |= (u64)tr32(TG3_RX_TSTAMP_MSB) << 32; } if (len > TG3_RX_COPY_THRESH(tp)) { int skb_size; unsigned int frag_size; skb_size = tg3_alloc_rx_data(tp, tpr, opaque_key, *post_ptr, &frag_size); if (skb_size < 0) goto drop_it; pci_unmap_single(tp->pdev, dma_addr, skb_size, PCI_DMA_FROMDEVICE); skb = build_skb(data, frag_size); if (!skb) { tg3_frag_free(frag_size != 0, data); goto drop_it_no_recycle; } skb_reserve(skb, TG3_RX_OFFSET(tp)); /* Ensure that the update to the data happens * after the usage of the old DMA mapping. */ smp_wmb(); ri->data = NULL; } else { tg3_recycle_rx(tnapi, tpr, opaque_key, desc_idx, *post_ptr); skb = netdev_alloc_skb(tp->dev, len + TG3_RAW_IP_ALIGN); if (skb == NULL) goto drop_it_no_recycle; skb_reserve(skb, TG3_RAW_IP_ALIGN); pci_dma_sync_single_for_cpu(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); memcpy(skb->data, data + TG3_RX_OFFSET(tp), len); pci_dma_sync_single_for_device(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE); } skb_put(skb, len); if (tstamp) tg3_hwclock_to_timestamp(tp, tstamp, skb_hwtstamps(skb)); if ((tp->dev->features & NETIF_F_RXCSUM) && (desc->type_flags & RXD_FLAG_TCPUDP_CSUM) && (((desc->ip_tcp_csum & RXD_TCPCSUM_MASK) >> RXD_TCPCSUM_SHIFT) == 0xffff)) skb->ip_summed = CHECKSUM_UNNECESSARY; else skb_checksum_none_assert(skb); skb->protocol = eth_type_trans(skb, tp->dev); if (len > (tp->dev->mtu + ETH_HLEN) && skb->protocol != htons(ETH_P_8021Q)) { dev_kfree_skb(skb); goto drop_it_no_recycle; } if (desc->type_flags & RXD_FLAG_VLAN && !(tp->rx_mode & RX_MODE_KEEP_VLAN_TAG)) __vlan_hwaccel_put_tag(skb, desc->err_vlan & RXD_VLAN_MASK); napi_gro_receive(&tnapi->napi, skb); received++; budget--; next_pkt: (*post_ptr)++; if (unlikely(rx_std_posted >= tp->rx_std_max_post)) { tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask; tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG, tpr->rx_std_prod_idx); work_mask &= ~RXD_OPAQUE_RING_STD; rx_std_posted = 0; } next_pkt_nopost: sw_idx++; sw_idx &= tp->rx_ret_ring_mask; /* Refresh hw_idx to see if there is new work */ if (sw_idx == hw_idx) { hw_idx = *(tnapi->rx_rcb_prod_idx); rmb(); } } /* ACK the status ring. */ tnapi->rx_rcb_ptr = sw_idx; tw32_rx_mbox(tnapi->consmbox, sw_idx); /* Refill RX ring(s). */ if (!tg3_flag(tp, ENABLE_RSS)) { /* Sync BD data before updating mailbox */ wmb(); if (work_mask & RXD_OPAQUE_RING_STD) { tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask; tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG, tpr->rx_std_prod_idx); } if (work_mask & RXD_OPAQUE_RING_JUMBO) { tpr->rx_jmb_prod_idx = jmb_prod_idx & tp->rx_jmb_ring_mask; tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG, tpr->rx_jmb_prod_idx); } mmiowb(); } else if (work_mask) { /* rx_std_buffers[] and rx_jmb_buffers[] entries must be * updated before the producer indices can be updated. */ smp_wmb(); tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask; tpr->rx_jmb_prod_idx = jmb_prod_idx & tp->rx_jmb_ring_mask; if (tnapi != &tp->napi[1]) { tp->rx_refill = true; napi_schedule(&tp->napi[1].napi); } } return received; } static void tg3_poll_link(struct tg3 *tp) { /* handle link change and other phy events */ if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) { struct tg3_hw_status *sblk = tp->napi[0].hw_status; if (sblk->status & SD_STATUS_LINK_CHG) { sblk->status = SD_STATUS_UPDATED | (sblk->status & ~SD_STATUS_LINK_CHG); spin_lock(&tp->lock); if (tg3_flag(tp, USE_PHYLIB)) { tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED | MAC_STATUS_CFG_CHANGED | MAC_STATUS_MI_COMPLETION | MAC_STATUS_LNKSTATE_CHANGED)); udelay(40); } else tg3_setup_phy(tp, 0); spin_unlock(&tp->lock); } } } static int tg3_rx_prodring_xfer(struct tg3 *tp, struct tg3_rx_prodring_set *dpr, struct tg3_rx_prodring_set *spr) { u32 si, di, cpycnt, src_prod_idx; int i, err = 0; while (1) { src_prod_idx = spr->rx_std_prod_idx; /* Make sure updates to the rx_std_buffers[] entries and the * standard producer index are seen in the correct order. */ smp_rmb(); if (spr->rx_std_cons_idx == src_prod_idx) break; if (spr->rx_std_cons_idx < src_prod_idx) cpycnt = src_prod_idx - spr->rx_std_cons_idx; else cpycnt = tp->rx_std_ring_mask + 1 - spr->rx_std_cons_idx; cpycnt = min(cpycnt, tp->rx_std_ring_mask + 1 - dpr->rx_std_prod_idx); si = spr->rx_std_cons_idx; di = dpr->rx_std_prod_idx; for (i = di; i < di + cpycnt; i++) { if (dpr->rx_std_buffers[i].data) { cpycnt = i - di; err = -ENOSPC; break; } } if (!cpycnt) break; /* Ensure that updates to the rx_std_buffers ring and the * shadowed hardware producer ring from tg3_recycle_skb() are * ordered correctly WRT the skb check above. */ smp_rmb(); memcpy(&dpr->rx_std_buffers[di], &spr->rx_std_buffers[si], cpycnt * sizeof(struct ring_info)); for (i = 0; i < cpycnt; i++, di++, si++) { struct tg3_rx_buffer_desc *sbd, *dbd; sbd = &spr->rx_std[si]; dbd = &dpr->rx_std[di]; dbd->addr_hi = sbd->addr_hi; dbd->addr_lo = sbd->addr_lo; } spr->rx_std_cons_idx = (spr->rx_std_cons_idx + cpycnt) & tp->rx_std_ring_mask; dpr->rx_std_prod_idx = (dpr->rx_std_prod_idx + cpycnt) & tp->rx_std_ring_mask; } while (1) { src_prod_idx = spr->rx_jmb_prod_idx; /* Make sure updates to the rx_jmb_buffers[] entries and * the jumbo producer index are seen in the correct order. */ smp_rmb(); if (spr->rx_jmb_cons_idx == src_prod_idx) break; if (spr->rx_jmb_cons_idx < src_prod_idx) cpycnt = src_prod_idx - spr->rx_jmb_cons_idx; else cpycnt = tp->rx_jmb_ring_mask + 1 - spr->rx_jmb_cons_idx; cpycnt = min(cpycnt, tp->rx_jmb_ring_mask + 1 - dpr->rx_jmb_prod_idx); si = spr->rx_jmb_cons_idx; di = dpr->rx_jmb_prod_idx; for (i = di; i < di + cpycnt; i++) { if (dpr->rx_jmb_buffers[i].data) { cpycnt = i - di; err = -ENOSPC; break; } } if (!cpycnt) break; /* Ensure that updates to the rx_jmb_buffers ring and the * shadowed hardware producer ring from tg3_recycle_skb() are * ordered correctly WRT the skb check above. */ smp_rmb(); memcpy(&dpr->rx_jmb_buffers[di], &spr->rx_jmb_buffers[si], cpycnt * sizeof(struct ring_info)); for (i = 0; i < cpycnt; i++, di++, si++) { struct tg3_rx_buffer_desc *sbd, *dbd; sbd = &spr->rx_jmb[si].std; dbd = &dpr->rx_jmb[di].std; dbd->addr_hi = sbd->addr_hi; dbd->addr_lo = sbd->addr_lo; } spr->rx_jmb_cons_idx = (spr->rx_jmb_cons_idx + cpycnt) & tp->rx_jmb_ring_mask; dpr->rx_jmb_prod_idx = (dpr->rx_jmb_prod_idx + cpycnt) & tp->rx_jmb_ring_mask; } return err; } static int tg3_poll_work(struct tg3_napi *tnapi, int work_done, int budget) { struct tg3 *tp = tnapi->tp; /* run TX completion thread */ if (tnapi->hw_status->idx[0].tx_consumer != tnapi->tx_cons) { tg3_tx(tnapi); if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING))) return work_done; } if (!tnapi->rx_rcb_prod_idx) return work_done; /* run RX thread, within the bounds set by NAPI. * All RX "locking" is done by ensuring outside * code synchronizes with tg3->napi.poll() */ if (*(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr) work_done += tg3_rx(tnapi, budget - work_done); if (tg3_flag(tp, ENABLE_RSS) && tnapi == &tp->napi[1]) { struct tg3_rx_prodring_set *dpr = &tp->napi[0].prodring; int i, err = 0; u32 std_prod_idx = dpr->rx_std_prod_idx; u32 jmb_prod_idx = dpr->rx_jmb_prod_idx; tp->rx_refill = false; for (i = 1; i <= tp->rxq_cnt; i++) err |= tg3_rx_prodring_xfer(tp, dpr, &tp->napi[i].prodring); wmb(); if (std_prod_idx != dpr->rx_std_prod_idx) tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG, dpr->rx_std_prod_idx); if (jmb_prod_idx != dpr->rx_jmb_prod_idx) tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG, dpr->rx_jmb_prod_idx); mmiowb(); if (err) tw32_f(HOSTCC_MODE, tp->coal_now); } return work_done; } static inline void tg3_reset_task_schedule(struct tg3 *tp) { if (!test_and_set_bit(TG3_FLAG_RESET_TASK_PENDING, tp->tg3_flags)) schedule_work(&tp->reset_task); } static inline void tg3_reset_task_cancel(struct tg3 *tp) { cancel_work_sync(&tp->reset_task); tg3_flag_clear(tp, RESET_TASK_PENDING); tg3_flag_clear(tp, TX_RECOVERY_PENDING); } static int tg3_poll_msix(struct napi_struct *napi, int budget) { struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi); struct tg3 *tp = tnapi->tp; int work_done = 0; struct tg3_hw_status *sblk = tnapi->hw_status; while (1) { work_done = tg3_poll_work(tnapi, work_done, budget); if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING))) goto tx_recovery; if (unlikely(work_done >= budget)) break; /* tp->last_tag is used in tg3_int_reenable() below * to tell the hw how much work has been processed, * so we must read it before checking for more work. */ tnapi->last_tag = sblk->status_tag; tnapi->last_irq_tag = tnapi->last_tag; rmb(); /* check for RX/TX work to do */ if (likely(sblk->idx[0].tx_consumer == tnapi->tx_cons && *(tnapi->rx_rcb_prod_idx) == tnapi->rx_rcb_ptr)) { /* This test here is not race free, but will reduce * the number of interrupts by looping again. */ if (tnapi == &tp->napi[1] && tp->rx_refill) continue; napi_complete(napi); /* Reenable interrupts. */ tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24); /* This test here is synchronized by napi_schedule() * and napi_complete() to close the race condition. */ if (unlikely(tnapi == &tp->napi[1] && tp->rx_refill)) { tw32(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | tnapi->coal_now); } mmiowb(); break; } } return work_done; tx_recovery: /* work_done is guaranteed to be less than budget. */ napi_complete(napi); tg3_reset_task_schedule(tp); return work_done; } static void tg3_process_error(struct tg3 *tp) { u32 val; bool real_error = false; if (tg3_flag(tp, ERROR_PROCESSED)) return; /* Check Flow Attention register */ val = tr32(HOSTCC_FLOW_ATTN); if (val & ~HOSTCC_FLOW_ATTN_MBUF_LWM) { netdev_err(tp->dev, "FLOW Attention error. Resetting chip.\n"); real_error = true; } if (tr32(MSGINT_STATUS) & ~MSGINT_STATUS_MSI_REQ) { netdev_err(tp->dev, "MSI Status error. Resetting chip.\n"); real_error = true; } if (tr32(RDMAC_STATUS) || tr32(WDMAC_STATUS)) { netdev_err(tp->dev, "DMA Status error. Resetting chip.\n"); real_error = true; } if (!real_error) return; tg3_dump_state(tp); tg3_flag_set(tp, ERROR_PROCESSED); tg3_reset_task_schedule(tp); } static int tg3_poll(struct napi_struct *napi, int budget) { struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi); struct tg3 *tp = tnapi->tp; int work_done = 0; struct tg3_hw_status *sblk = tnapi->hw_status; while (1) { if (sblk->status & SD_STATUS_ERROR) tg3_process_error(tp); tg3_poll_link(tp); work_done = tg3_poll_work(tnapi, work_done, budget); if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING))) goto tx_recovery; if (unlikely(work_done >= budget)) break; if (tg3_flag(tp, TAGGED_STATUS)) { /* tp->last_tag is used in tg3_int_reenable() below * to tell the hw how much work has been processed, * so we must read it before checking for more work. */ tnapi->last_tag = sblk->status_tag; tnapi->last_irq_tag = tnapi->last_tag; rmb(); } else sblk->status &= ~SD_STATUS_UPDATED; if (likely(!tg3_has_work(tnapi))) { napi_complete(napi); tg3_int_reenable(tnapi); break; } } return work_done; tx_recovery: /* work_done is guaranteed to be less than budget. */ napi_complete(napi); tg3_reset_task_schedule(tp); return work_done; } static void tg3_napi_disable(struct tg3 *tp) { int i; for (i = tp->irq_cnt - 1; i >= 0; i--) napi_disable(&tp->napi[i].napi); } static void tg3_napi_enable(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_cnt; i++) napi_enable(&tp->napi[i].napi); } static void tg3_napi_init(struct tg3 *tp) { int i; netif_napi_add(tp->dev, &tp->napi[0].napi, tg3_poll, 64); for (i = 1; i < tp->irq_cnt; i++) netif_napi_add(tp->dev, &tp->napi[i].napi, tg3_poll_msix, 64); } static void tg3_napi_fini(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_cnt; i++) netif_napi_del(&tp->napi[i].napi); } static inline void tg3_netif_stop(struct tg3 *tp) { tp->dev->trans_start = jiffies; /* prevent tx timeout */ tg3_napi_disable(tp); netif_carrier_off(tp->dev); netif_tx_disable(tp->dev); } /* tp->lock must be held */ static inline void tg3_netif_start(struct tg3 *tp) { tg3_ptp_resume(tp); /* NOTE: unconditional netif_tx_wake_all_queues is only * appropriate so long as all callers are assured to * have free tx slots (such as after tg3_init_hw) */ netif_tx_wake_all_queues(tp->dev); if (tp->link_up) netif_carrier_on(tp->dev); tg3_napi_enable(tp); tp->napi[0].hw_status->status |= SD_STATUS_UPDATED; tg3_enable_ints(tp); } static void tg3_irq_quiesce(struct tg3 *tp) { int i; BUG_ON(tp->irq_sync); tp->irq_sync = 1; smp_mb(); for (i = 0; i < tp->irq_cnt; i++) synchronize_irq(tp->napi[i].irq_vec); } /* Fully shutdown all tg3 driver activity elsewhere in the system. * If irq_sync is non-zero, then the IRQ handler must be synchronized * with as well. Most of the time, this is not necessary except when * shutting down the device. */ static inline void tg3_full_lock(struct tg3 *tp, int irq_sync) { spin_lock_bh(&tp->lock); if (irq_sync) tg3_irq_quiesce(tp); } static inline void tg3_full_unlock(struct tg3 *tp) { spin_unlock_bh(&tp->lock); } /* One-shot MSI handler - Chip automatically disables interrupt * after sending MSI so driver doesn't have to do it. */ static irqreturn_t tg3_msi_1shot(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; prefetch(tnapi->hw_status); if (tnapi->rx_rcb) prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); if (likely(!tg3_irq_sync(tp))) napi_schedule(&tnapi->napi); return IRQ_HANDLED; } /* MSI ISR - No need to check for interrupt sharing and no need to * flush status block and interrupt mailbox. PCI ordering rules * guarantee that MSI will arrive after the status block. */ static irqreturn_t tg3_msi(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; prefetch(tnapi->hw_status); if (tnapi->rx_rcb) prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); /* * Writing any value to intr-mbox-0 clears PCI INTA# and * chip-internal interrupt pending events. * Writing non-zero to intr-mbox-0 additional tells the * NIC to stop sending us irqs, engaging "in-intr-handler" * event coalescing. */ tw32_mailbox(tnapi->int_mbox, 0x00000001); if (likely(!tg3_irq_sync(tp))) napi_schedule(&tnapi->napi); return IRQ_RETVAL(1); } static irqreturn_t tg3_interrupt(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; unsigned int handled = 1; /* In INTx mode, it is possible for the interrupt to arrive at * the CPU before the status block posted prior to the interrupt. * Reading the PCI State register will confirm whether the * interrupt is ours and will flush the status block. */ if (unlikely(!(sblk->status & SD_STATUS_UPDATED))) { if (tg3_flag(tp, CHIP_RESETTING) || (tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) { handled = 0; goto out; } } /* * Writing any value to intr-mbox-0 clears PCI INTA# and * chip-internal interrupt pending events. * Writing non-zero to intr-mbox-0 additional tells the * NIC to stop sending us irqs, engaging "in-intr-handler" * event coalescing. * * Flush the mailbox to de-assert the IRQ immediately to prevent * spurious interrupts. The flush impacts performance but * excessive spurious interrupts can be worse in some cases. */ tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001); if (tg3_irq_sync(tp)) goto out; sblk->status &= ~SD_STATUS_UPDATED; if (likely(tg3_has_work(tnapi))) { prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); napi_schedule(&tnapi->napi); } else { /* No work, shared interrupt perhaps? re-enable * interrupts, and flush that PCI write */ tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000000); } out: return IRQ_RETVAL(handled); } static irqreturn_t tg3_interrupt_tagged(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; unsigned int handled = 1; /* In INTx mode, it is possible for the interrupt to arrive at * the CPU before the status block posted prior to the interrupt. * Reading the PCI State register will confirm whether the * interrupt is ours and will flush the status block. */ if (unlikely(sblk->status_tag == tnapi->last_irq_tag)) { if (tg3_flag(tp, CHIP_RESETTING) || (tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) { handled = 0; goto out; } } /* * writing any value to intr-mbox-0 clears PCI INTA# and * chip-internal interrupt pending events. * writing non-zero to intr-mbox-0 additional tells the * NIC to stop sending us irqs, engaging "in-intr-handler" * event coalescing. * * Flush the mailbox to de-assert the IRQ immediately to prevent * spurious interrupts. The flush impacts performance but * excessive spurious interrupts can be worse in some cases. */ tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001); /* * In a shared interrupt configuration, sometimes other devices' * interrupts will scream. We record the current status tag here * so that the above check can report that the screaming interrupts * are unhandled. Eventually they will be silenced. */ tnapi->last_irq_tag = sblk->status_tag; if (tg3_irq_sync(tp)) goto out; prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]); napi_schedule(&tnapi->napi); out: return IRQ_RETVAL(handled); } /* ISR for interrupt test */ static irqreturn_t tg3_test_isr(int irq, void *dev_id) { struct tg3_napi *tnapi = dev_id; struct tg3 *tp = tnapi->tp; struct tg3_hw_status *sblk = tnapi->hw_status; if ((sblk->status & SD_STATUS_UPDATED) || !(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) { tg3_disable_ints(tp); return IRQ_RETVAL(1); } return IRQ_RETVAL(0); } #ifdef CONFIG_NET_POLL_CONTROLLER static void tg3_poll_controller(struct net_device *dev) { int i; struct tg3 *tp = netdev_priv(dev); if (tg3_irq_sync(tp)) return; for (i = 0; i < tp->irq_cnt; i++) tg3_interrupt(tp->napi[i].irq_vec, &tp->napi[i]); } #endif static void tg3_tx_timeout(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); if (netif_msg_tx_err(tp)) { netdev_err(dev, "transmit timed out, resetting\n"); tg3_dump_state(tp); } tg3_reset_task_schedule(tp); } /* Test for DMA buffers crossing any 4GB boundaries: 4G, 8G, etc */ static inline int tg3_4g_overflow_test(dma_addr_t mapping, int len) { u32 base = (u32) mapping & 0xffffffff; return (base > 0xffffdcc0) && (base + len + 8 < base); } /* Test for DMA addresses > 40-bit */ static inline int tg3_40bit_overflow_test(struct tg3 *tp, dma_addr_t mapping, int len) { #if defined(CONFIG_HIGHMEM) && (BITS_PER_LONG == 64) if (tg3_flag(tp, 40BIT_DMA_BUG)) return ((u64) mapping + len) > DMA_BIT_MASK(40); return 0; #else return 0; #endif } static inline void tg3_tx_set_bd(struct tg3_tx_buffer_desc *txbd, dma_addr_t mapping, u32 len, u32 flags, u32 mss, u32 vlan) { txbd->addr_hi = ((u64) mapping >> 32); txbd->addr_lo = ((u64) mapping & 0xffffffff); txbd->len_flags = (len << TXD_LEN_SHIFT) | (flags & 0x0000ffff); txbd->vlan_tag = (mss << TXD_MSS_SHIFT) | (vlan << TXD_VLAN_TAG_SHIFT); } static bool tg3_tx_frag_set(struct tg3_napi *tnapi, u32 *entry, u32 *budget, dma_addr_t map, u32 len, u32 flags, u32 mss, u32 vlan) { struct tg3 *tp = tnapi->tp; bool hwbug = false; if (tg3_flag(tp, SHORT_DMA_BUG) && len <= 8) hwbug = true; if (tg3_4g_overflow_test(map, len)) hwbug = true; if (tg3_40bit_overflow_test(tp, map, len)) hwbug = true; if (tp->dma_limit) { u32 prvidx = *entry; u32 tmp_flag = flags & ~TXD_FLAG_END; while (len > tp->dma_limit && *budget) { u32 frag_len = tp->dma_limit; len -= tp->dma_limit; /* Avoid the 8byte DMA problem */ if (len <= 8) { len += tp->dma_limit / 2; frag_len = tp->dma_limit / 2; } tnapi->tx_buffers[*entry].fragmented = true; tg3_tx_set_bd(&tnapi->tx_ring[*entry], map, frag_len, tmp_flag, mss, vlan); *budget -= 1; prvidx = *entry; *entry = NEXT_TX(*entry); map += frag_len; } if (len) { if (*budget) { tg3_tx_set_bd(&tnapi->tx_ring[*entry], map, len, flags, mss, vlan); *budget -= 1; *entry = NEXT_TX(*entry); } else { hwbug = true; tnapi->tx_buffers[prvidx].fragmented = false; } } } else { tg3_tx_set_bd(&tnapi->tx_ring[*entry], map, len, flags, mss, vlan); *entry = NEXT_TX(*entry); } return hwbug; } static void tg3_tx_skb_unmap(struct tg3_napi *tnapi, u32 entry, int last) { int i; struct sk_buff *skb; struct tg3_tx_ring_info *txb = &tnapi->tx_buffers[entry]; skb = txb->skb; txb->skb = NULL; pci_unmap_single(tnapi->tp->pdev, dma_unmap_addr(txb, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); while (txb->fragmented) { txb->fragmented = false; entry = NEXT_TX(entry); txb = &tnapi->tx_buffers[entry]; } for (i = 0; i <= last; i++) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; entry = NEXT_TX(entry); txb = &tnapi->tx_buffers[entry]; pci_unmap_page(tnapi->tp->pdev, dma_unmap_addr(txb, mapping), skb_frag_size(frag), PCI_DMA_TODEVICE); while (txb->fragmented) { txb->fragmented = false; entry = NEXT_TX(entry); txb = &tnapi->tx_buffers[entry]; } } } /* Workaround 4GB and 40-bit hardware DMA bugs. */ static int tigon3_dma_hwbug_workaround(struct tg3_napi *tnapi, struct sk_buff **pskb, u32 *entry, u32 *budget, u32 base_flags, u32 mss, u32 vlan) { struct tg3 *tp = tnapi->tp; struct sk_buff *new_skb, *skb = *pskb; dma_addr_t new_addr = 0; int ret = 0; if (tg3_asic_rev(tp) != ASIC_REV_5701) new_skb = skb_copy(skb, GFP_ATOMIC); else { int more_headroom = 4 - ((unsigned long)skb->data & 3); new_skb = skb_copy_expand(skb, skb_headroom(skb) + more_headroom, skb_tailroom(skb), GFP_ATOMIC); } if (!new_skb) { ret = -1; } else { /* New SKB is guaranteed to be linear. */ new_addr = pci_map_single(tp->pdev, new_skb->data, new_skb->len, PCI_DMA_TODEVICE); /* Make sure the mapping succeeded */ if (pci_dma_mapping_error(tp->pdev, new_addr)) { dev_kfree_skb(new_skb); ret = -1; } else { u32 save_entry = *entry; base_flags |= TXD_FLAG_END; tnapi->tx_buffers[*entry].skb = new_skb; dma_unmap_addr_set(&tnapi->tx_buffers[*entry], mapping, new_addr); if (tg3_tx_frag_set(tnapi, entry, budget, new_addr, new_skb->len, base_flags, mss, vlan)) { tg3_tx_skb_unmap(tnapi, save_entry, -1); dev_kfree_skb(new_skb); ret = -1; } } } dev_kfree_skb(skb); *pskb = new_skb; return ret; } static netdev_tx_t tg3_start_xmit(struct sk_buff *, struct net_device *); /* Use GSO to workaround a rare TSO bug that may be triggered when the * TSO header is greater than 80 bytes. */ static int tg3_tso_bug(struct tg3 *tp, struct sk_buff *skb) { struct sk_buff *segs, *nskb; u32 frag_cnt_est = skb_shinfo(skb)->gso_segs * 3; /* Estimate the number of fragments in the worst case */ if (unlikely(tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est)) { netif_stop_queue(tp->dev); /* netif_tx_stop_queue() must be done before checking * checking tx index in tg3_tx_avail() below, because in * tg3_tx(), we update tx index before checking for * netif_tx_queue_stopped(). */ smp_mb(); if (tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est) return NETDEV_TX_BUSY; netif_wake_queue(tp->dev); } segs = skb_gso_segment(skb, tp->dev->features & ~NETIF_F_TSO); if (IS_ERR(segs)) goto tg3_tso_bug_end; do { nskb = segs; segs = segs->next; nskb->next = NULL; tg3_start_xmit(nskb, tp->dev); } while (segs); tg3_tso_bug_end: dev_kfree_skb(skb); return NETDEV_TX_OK; } /* hard_start_xmit for devices that have the 4G bug and/or 40-bit bug and * support TG3_FLAG_HW_TSO_1 or firmware TSO only. */ static netdev_tx_t tg3_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); u32 len, entry, base_flags, mss, vlan = 0; u32 budget; int i = -1, would_hit_hwbug; dma_addr_t mapping; struct tg3_napi *tnapi; struct netdev_queue *txq; unsigned int last; txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb)); tnapi = &tp->napi[skb_get_queue_mapping(skb)]; if (tg3_flag(tp, ENABLE_TSS)) tnapi++; budget = tg3_tx_avail(tnapi); /* We are running in BH disabled context with netif_tx_lock * and TX reclaim runs via tp->napi.poll inside of a software * interrupt. Furthermore, IRQ processing runs lockless so we have * no IRQ context deadlocks to worry about either. Rejoice! */ if (unlikely(budget <= (skb_shinfo(skb)->nr_frags + 1))) { if (!netif_tx_queue_stopped(txq)) { netif_tx_stop_queue(txq); /* This is a hard error, log it. */ netdev_err(dev, "BUG! Tx Ring full when queue awake!\n"); } return NETDEV_TX_BUSY; } entry = tnapi->tx_prod; base_flags = 0; if (skb->ip_summed == CHECKSUM_PARTIAL) base_flags |= TXD_FLAG_TCPUDP_CSUM; mss = skb_shinfo(skb)->gso_size; if (mss) { struct iphdr *iph; u32 tcp_opt_len, hdr_len; if (skb_header_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC)) goto drop; iph = ip_hdr(skb); tcp_opt_len = tcp_optlen(skb); hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb) - ETH_HLEN; if (!skb_is_gso_v6(skb)) { iph->check = 0; iph->tot_len = htons(mss + hdr_len); } if (unlikely((ETH_HLEN + hdr_len) > 80) && tg3_flag(tp, TSO_BUG)) return tg3_tso_bug(tp, skb); base_flags |= (TXD_FLAG_CPU_PRE_DMA | TXD_FLAG_CPU_POST_DMA); if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) { tcp_hdr(skb)->check = 0; base_flags &= ~TXD_FLAG_TCPUDP_CSUM; } else tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, 0, IPPROTO_TCP, 0); if (tg3_flag(tp, HW_TSO_3)) { mss |= (hdr_len & 0xc) << 12; if (hdr_len & 0x10) base_flags |= 0x00000010; base_flags |= (hdr_len & 0x3e0) << 5; } else if (tg3_flag(tp, HW_TSO_2)) mss |= hdr_len << 9; else if (tg3_flag(tp, HW_TSO_1) || tg3_asic_rev(tp) == ASIC_REV_5705) { if (tcp_opt_len || iph->ihl > 5) { int tsflags; tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2); mss |= (tsflags << 11); } } else { if (tcp_opt_len || iph->ihl > 5) { int tsflags; tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2); base_flags |= tsflags << 12; } } } if (tg3_flag(tp, USE_JUMBO_BDFLAG) && !mss && skb->len > VLAN_ETH_FRAME_LEN) base_flags |= TXD_FLAG_JMB_PKT; if (vlan_tx_tag_present(skb)) { base_flags |= TXD_FLAG_VLAN; vlan = vlan_tx_tag_get(skb); } if ((unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) && tg3_flag(tp, TX_TSTAMP_EN)) { skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; base_flags |= TXD_FLAG_HWTSTAMP; } len = skb_headlen(skb); mapping = pci_map_single(tp->pdev, skb->data, len, PCI_DMA_TODEVICE); if (pci_dma_mapping_error(tp->pdev, mapping)) goto drop; tnapi->tx_buffers[entry].skb = skb; dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping, mapping); would_hit_hwbug = 0; if (tg3_flag(tp, 5701_DMA_BUG)) would_hit_hwbug = 1; if (tg3_tx_frag_set(tnapi, &entry, &budget, mapping, len, base_flags | ((skb_shinfo(skb)->nr_frags == 0) ? TXD_FLAG_END : 0), mss, vlan)) { would_hit_hwbug = 1; } else if (skb_shinfo(skb)->nr_frags > 0) { u32 tmp_mss = mss; if (!tg3_flag(tp, HW_TSO_1) && !tg3_flag(tp, HW_TSO_2) && !tg3_flag(tp, HW_TSO_3)) tmp_mss = 0; /* Now loop through additional data * fragments, and queue them. */ last = skb_shinfo(skb)->nr_frags - 1; for (i = 0; i <= last; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; len = skb_frag_size(frag); mapping = skb_frag_dma_map(&tp->pdev->dev, frag, 0, len, DMA_TO_DEVICE); tnapi->tx_buffers[entry].skb = NULL; dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping, mapping); if (dma_mapping_error(&tp->pdev->dev, mapping)) goto dma_error; if (!budget || tg3_tx_frag_set(tnapi, &entry, &budget, mapping, len, base_flags | ((i == last) ? TXD_FLAG_END : 0), tmp_mss, vlan)) { would_hit_hwbug = 1; break; } } } if (would_hit_hwbug) { tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, i); /* If the workaround fails due to memory/mapping * failure, silently drop this packet. */ entry = tnapi->tx_prod; budget = tg3_tx_avail(tnapi); if (tigon3_dma_hwbug_workaround(tnapi, &skb, &entry, &budget, base_flags, mss, vlan)) goto drop_nofree; } skb_tx_timestamp(skb); netdev_tx_sent_queue(txq, skb->len); /* Sync BD data before updating mailbox */ wmb(); /* Packets are ready, update Tx producer idx local and on card. */ tw32_tx_mbox(tnapi->prodmbox, entry); tnapi->tx_prod = entry; if (unlikely(tg3_tx_avail(tnapi) <= (MAX_SKB_FRAGS + 1))) { netif_tx_stop_queue(txq); /* netif_tx_stop_queue() must be done before checking * checking tx index in tg3_tx_avail() below, because in * tg3_tx(), we update tx index before checking for * netif_tx_queue_stopped(). */ smp_mb(); if (tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi)) netif_tx_wake_queue(txq); } mmiowb(); return NETDEV_TX_OK; dma_error: tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, --i); tnapi->tx_buffers[tnapi->tx_prod].skb = NULL; drop: dev_kfree_skb(skb); drop_nofree: tp->tx_dropped++; return NETDEV_TX_OK; } static void tg3_mac_loopback(struct tg3 *tp, bool enable) { if (enable) { tp->mac_mode &= ~(MAC_MODE_HALF_DUPLEX | MAC_MODE_PORT_MODE_MASK); tp->mac_mode |= MAC_MODE_PORT_INT_LPBACK; if (!tg3_flag(tp, 5705_PLUS)) tp->mac_mode |= MAC_MODE_LINK_POLARITY; if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY) tp->mac_mode |= MAC_MODE_PORT_MODE_MII; else tp->mac_mode |= MAC_MODE_PORT_MODE_GMII; } else { tp->mac_mode &= ~MAC_MODE_PORT_INT_LPBACK; if (tg3_flag(tp, 5705_PLUS) || (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) || tg3_asic_rev(tp) == ASIC_REV_5700) tp->mac_mode &= ~MAC_MODE_LINK_POLARITY; } tw32(MAC_MODE, tp->mac_mode); udelay(40); } static int tg3_phy_lpbk_set(struct tg3 *tp, u32 speed, bool extlpbk) { u32 val, bmcr, mac_mode, ptest = 0; tg3_phy_toggle_apd(tp, false); tg3_phy_toggle_automdix(tp, 0); if (extlpbk && tg3_phy_set_extloopbk(tp)) return -EIO; bmcr = BMCR_FULLDPLX; switch (speed) { case SPEED_10: break; case SPEED_100: bmcr |= BMCR_SPEED100; break; case SPEED_1000: default: if (tp->phy_flags & TG3_PHYFLG_IS_FET) { speed = SPEED_100; bmcr |= BMCR_SPEED100; } else { speed = SPEED_1000; bmcr |= BMCR_SPEED1000; } } if (extlpbk) { if (!(tp->phy_flags & TG3_PHYFLG_IS_FET)) { tg3_readphy(tp, MII_CTRL1000, &val); val |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER; tg3_writephy(tp, MII_CTRL1000, val); } else { ptest = MII_TG3_FET_PTEST_TRIM_SEL | MII_TG3_FET_PTEST_TRIM_2; tg3_writephy(tp, MII_TG3_FET_PTEST, ptest); } } else bmcr |= BMCR_LOOPBACK; tg3_writephy(tp, MII_BMCR, bmcr); /* The write needs to be flushed for the FETs */ if (tp->phy_flags & TG3_PHYFLG_IS_FET) tg3_readphy(tp, MII_BMCR, &bmcr); udelay(40); if ((tp->phy_flags & TG3_PHYFLG_IS_FET) && tg3_asic_rev(tp) == ASIC_REV_5785) { tg3_writephy(tp, MII_TG3_FET_PTEST, ptest | MII_TG3_FET_PTEST_FRC_TX_LINK | MII_TG3_FET_PTEST_FRC_TX_LOCK); /* The write needs to be flushed for the AC131 */ tg3_readphy(tp, MII_TG3_FET_PTEST, &val); } /* Reset to prevent losing 1st rx packet intermittently */ if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) && tg3_flag(tp, 5780_CLASS)) { tw32_f(MAC_RX_MODE, RX_MODE_RESET); udelay(10); tw32_f(MAC_RX_MODE, tp->rx_mode); } mac_mode = tp->mac_mode & ~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX); if (speed == SPEED_1000) mac_mode |= MAC_MODE_PORT_MODE_GMII; else mac_mode |= MAC_MODE_PORT_MODE_MII; if (tg3_asic_rev(tp) == ASIC_REV_5700) { u32 masked_phy_id = tp->phy_id & TG3_PHY_ID_MASK; if (masked_phy_id == TG3_PHY_ID_BCM5401) mac_mode &= ~MAC_MODE_LINK_POLARITY; else if (masked_phy_id == TG3_PHY_ID_BCM5411) mac_mode |= MAC_MODE_LINK_POLARITY; tg3_writephy(tp, MII_TG3_EXT_CTRL, MII_TG3_EXT_CTRL_LNK3_LED_MODE); } tw32(MAC_MODE, mac_mode); udelay(40); return 0; } static void tg3_set_loopback(struct net_device *dev, netdev_features_t features) { struct tg3 *tp = netdev_priv(dev); if (features & NETIF_F_LOOPBACK) { if (tp->mac_mode & MAC_MODE_PORT_INT_LPBACK) return; spin_lock_bh(&tp->lock); tg3_mac_loopback(tp, true); netif_carrier_on(tp->dev); spin_unlock_bh(&tp->lock); netdev_info(dev, "Internal MAC loopback mode enabled.\n"); } else { if (!(tp->mac_mode & MAC_MODE_PORT_INT_LPBACK)) return; spin_lock_bh(&tp->lock); tg3_mac_loopback(tp, false); /* Force link status check */ tg3_setup_phy(tp, 1); spin_unlock_bh(&tp->lock); netdev_info(dev, "Internal MAC loopback mode disabled.\n"); } } static netdev_features_t tg3_fix_features(struct net_device *dev, netdev_features_t features) { struct tg3 *tp = netdev_priv(dev); if (dev->mtu > ETH_DATA_LEN && tg3_flag(tp, 5780_CLASS)) features &= ~NETIF_F_ALL_TSO; return features; } static int tg3_set_features(struct net_device *dev, netdev_features_t features) { netdev_features_t changed = dev->features ^ features; if ((changed & NETIF_F_LOOPBACK) && netif_running(dev)) tg3_set_loopback(dev, features); return 0; } static void tg3_rx_prodring_free(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { int i; if (tpr != &tp->napi[0].prodring) { for (i = tpr->rx_std_cons_idx; i != tpr->rx_std_prod_idx; i = (i + 1) & tp->rx_std_ring_mask) tg3_rx_data_free(tp, &tpr->rx_std_buffers[i], tp->rx_pkt_map_sz); if (tg3_flag(tp, JUMBO_CAPABLE)) { for (i = tpr->rx_jmb_cons_idx; i != tpr->rx_jmb_prod_idx; i = (i + 1) & tp->rx_jmb_ring_mask) { tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i], TG3_RX_JMB_MAP_SZ); } } return; } for (i = 0; i <= tp->rx_std_ring_mask; i++) tg3_rx_data_free(tp, &tpr->rx_std_buffers[i], tp->rx_pkt_map_sz); if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) { for (i = 0; i <= tp->rx_jmb_ring_mask; i++) tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i], TG3_RX_JMB_MAP_SZ); } } /* Initialize rx rings for packet processing. * * The chip has been shut down and the driver detached from * the networking, so no interrupts or new tx packets will * end up in the driver. tp->{tx,}lock are held and thus * we may not sleep. */ static int tg3_rx_prodring_alloc(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { u32 i, rx_pkt_dma_sz; tpr->rx_std_cons_idx = 0; tpr->rx_std_prod_idx = 0; tpr->rx_jmb_cons_idx = 0; tpr->rx_jmb_prod_idx = 0; if (tpr != &tp->napi[0].prodring) { memset(&tpr->rx_std_buffers[0], 0, TG3_RX_STD_BUFF_RING_SIZE(tp)); if (tpr->rx_jmb_buffers) memset(&tpr->rx_jmb_buffers[0], 0, TG3_RX_JMB_BUFF_RING_SIZE(tp)); goto done; } /* Zero out all descriptors. */ memset(tpr->rx_std, 0, TG3_RX_STD_RING_BYTES(tp)); rx_pkt_dma_sz = TG3_RX_STD_DMA_SZ; if (tg3_flag(tp, 5780_CLASS) && tp->dev->mtu > ETH_DATA_LEN) rx_pkt_dma_sz = TG3_RX_JMB_DMA_SZ; tp->rx_pkt_map_sz = TG3_RX_DMA_TO_MAP_SZ(rx_pkt_dma_sz); /* Initialize invariants of the rings, we only set this * stuff once. This works because the card does not * write into the rx buffer posting rings. */ for (i = 0; i <= tp->rx_std_ring_mask; i++) { struct tg3_rx_buffer_desc *rxd; rxd = &tpr->rx_std[i]; rxd->idx_len = rx_pkt_dma_sz << RXD_LEN_SHIFT; rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT); rxd->opaque = (RXD_OPAQUE_RING_STD | (i << RXD_OPAQUE_INDEX_SHIFT)); } /* Now allocate fresh SKBs for each rx ring. */ for (i = 0; i < tp->rx_pending; i++) { unsigned int frag_size; if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_STD, i, &frag_size) < 0) { netdev_warn(tp->dev, "Using a smaller RX standard ring. Only " "%d out of %d buffers were allocated " "successfully\n", i, tp->rx_pending); if (i == 0) goto initfail; tp->rx_pending = i; break; } } if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS)) goto done; memset(tpr->rx_jmb, 0, TG3_RX_JMB_RING_BYTES(tp)); if (!tg3_flag(tp, JUMBO_RING_ENABLE)) goto done; for (i = 0; i <= tp->rx_jmb_ring_mask; i++) { struct tg3_rx_buffer_desc *rxd; rxd = &tpr->rx_jmb[i].std; rxd->idx_len = TG3_RX_JMB_DMA_SZ << RXD_LEN_SHIFT; rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT) | RXD_FLAG_JUMBO; rxd->opaque = (RXD_OPAQUE_RING_JUMBO | (i << RXD_OPAQUE_INDEX_SHIFT)); } for (i = 0; i < tp->rx_jumbo_pending; i++) { unsigned int frag_size; if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_JUMBO, i, &frag_size) < 0) { netdev_warn(tp->dev, "Using a smaller RX jumbo ring. Only %d " "out of %d buffers were allocated " "successfully\n", i, tp->rx_jumbo_pending); if (i == 0) goto initfail; tp->rx_jumbo_pending = i; break; } } done: return 0; initfail: tg3_rx_prodring_free(tp, tpr); return -ENOMEM; } static void tg3_rx_prodring_fini(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { kfree(tpr->rx_std_buffers); tpr->rx_std_buffers = NULL; kfree(tpr->rx_jmb_buffers); tpr->rx_jmb_buffers = NULL; if (tpr->rx_std) { dma_free_coherent(&tp->pdev->dev, TG3_RX_STD_RING_BYTES(tp), tpr->rx_std, tpr->rx_std_mapping); tpr->rx_std = NULL; } if (tpr->rx_jmb) { dma_free_coherent(&tp->pdev->dev, TG3_RX_JMB_RING_BYTES(tp), tpr->rx_jmb, tpr->rx_jmb_mapping); tpr->rx_jmb = NULL; } } static int tg3_rx_prodring_init(struct tg3 *tp, struct tg3_rx_prodring_set *tpr) { tpr->rx_std_buffers = kzalloc(TG3_RX_STD_BUFF_RING_SIZE(tp), GFP_KERNEL); if (!tpr->rx_std_buffers) return -ENOMEM; tpr->rx_std = dma_alloc_coherent(&tp->pdev->dev, TG3_RX_STD_RING_BYTES(tp), &tpr->rx_std_mapping, GFP_KERNEL); if (!tpr->rx_std) goto err_out; if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) { tpr->rx_jmb_buffers = kzalloc(TG3_RX_JMB_BUFF_RING_SIZE(tp), GFP_KERNEL); if (!tpr->rx_jmb_buffers) goto err_out; tpr->rx_jmb = dma_alloc_coherent(&tp->pdev->dev, TG3_RX_JMB_RING_BYTES(tp), &tpr->rx_jmb_mapping, GFP_KERNEL); if (!tpr->rx_jmb) goto err_out; } return 0; err_out: tg3_rx_prodring_fini(tp, tpr); return -ENOMEM; } /* Free up pending packets in all rx/tx rings. * * The chip has been shut down and the driver detached from * the networking, so no interrupts or new tx packets will * end up in the driver. tp->{tx,}lock is not held and we are not * in an interrupt context and thus may sleep. */ static void tg3_free_rings(struct tg3 *tp) { int i, j; for (j = 0; j < tp->irq_cnt; j++) { struct tg3_napi *tnapi = &tp->napi[j]; tg3_rx_prodring_free(tp, &tnapi->prodring); if (!tnapi->tx_buffers) continue; for (i = 0; i < TG3_TX_RING_SIZE; i++) { struct sk_buff *skb = tnapi->tx_buffers[i].skb; if (!skb) continue; tg3_tx_skb_unmap(tnapi, i, skb_shinfo(skb)->nr_frags - 1); dev_kfree_skb_any(skb); } netdev_tx_reset_queue(netdev_get_tx_queue(tp->dev, j)); } } /* Initialize tx/rx rings for packet processing. * * The chip has been shut down and the driver detached from * the networking, so no interrupts or new tx packets will * end up in the driver. tp->{tx,}lock are held and thus * we may not sleep. */ static int tg3_init_rings(struct tg3 *tp) { int i; /* Free up all the SKBs. */ tg3_free_rings(tp); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tnapi->last_tag = 0; tnapi->last_irq_tag = 0; tnapi->hw_status->status = 0; tnapi->hw_status->status_tag = 0; memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); tnapi->tx_prod = 0; tnapi->tx_cons = 0; if (tnapi->tx_ring) memset(tnapi->tx_ring, 0, TG3_TX_RING_BYTES); tnapi->rx_rcb_ptr = 0; if (tnapi->rx_rcb) memset(tnapi->rx_rcb, 0, TG3_RX_RCB_RING_BYTES(tp)); if (tg3_rx_prodring_alloc(tp, &tnapi->prodring)) { tg3_free_rings(tp); return -ENOMEM; } } return 0; } static void tg3_mem_tx_release(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_max; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->tx_ring) { dma_free_coherent(&tp->pdev->dev, TG3_TX_RING_BYTES, tnapi->tx_ring, tnapi->tx_desc_mapping); tnapi->tx_ring = NULL; } kfree(tnapi->tx_buffers); tnapi->tx_buffers = NULL; } } static int tg3_mem_tx_acquire(struct tg3 *tp) { int i; struct tg3_napi *tnapi = &tp->napi[0]; /* If multivector TSS is enabled, vector 0 does not handle * tx interrupts. Don't allocate any resources for it. */ if (tg3_flag(tp, ENABLE_TSS)) tnapi++; for (i = 0; i < tp->txq_cnt; i++, tnapi++) { tnapi->tx_buffers = kzalloc(sizeof(struct tg3_tx_ring_info) * TG3_TX_RING_SIZE, GFP_KERNEL); if (!tnapi->tx_buffers) goto err_out; tnapi->tx_ring = dma_alloc_coherent(&tp->pdev->dev, TG3_TX_RING_BYTES, &tnapi->tx_desc_mapping, GFP_KERNEL); if (!tnapi->tx_ring) goto err_out; } return 0; err_out: tg3_mem_tx_release(tp); return -ENOMEM; } static void tg3_mem_rx_release(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_max; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tg3_rx_prodring_fini(tp, &tnapi->prodring); if (!tnapi->rx_rcb) continue; dma_free_coherent(&tp->pdev->dev, TG3_RX_RCB_RING_BYTES(tp), tnapi->rx_rcb, tnapi->rx_rcb_mapping); tnapi->rx_rcb = NULL; } } static int tg3_mem_rx_acquire(struct tg3 *tp) { unsigned int i, limit; limit = tp->rxq_cnt; /* If RSS is enabled, we need a (dummy) producer ring * set on vector zero. This is the true hw prodring. */ if (tg3_flag(tp, ENABLE_RSS)) limit++; for (i = 0; i < limit; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tg3_rx_prodring_init(tp, &tnapi->prodring)) goto err_out; /* If multivector RSS is enabled, vector 0 * does not handle rx or tx interrupts. * Don't allocate any resources for it. */ if (!i && tg3_flag(tp, ENABLE_RSS)) continue; tnapi->rx_rcb = dma_alloc_coherent(&tp->pdev->dev, TG3_RX_RCB_RING_BYTES(tp), &tnapi->rx_rcb_mapping, GFP_KERNEL); if (!tnapi->rx_rcb) goto err_out; memset(tnapi->rx_rcb, 0, TG3_RX_RCB_RING_BYTES(tp)); } return 0; err_out: tg3_mem_rx_release(tp); return -ENOMEM; } /* * Must not be invoked with interrupt sources disabled and * the hardware shutdown down. */ static void tg3_free_consistent(struct tg3 *tp) { int i; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->hw_status) { dma_free_coherent(&tp->pdev->dev, TG3_HW_STATUS_SIZE, tnapi->hw_status, tnapi->status_mapping); tnapi->hw_status = NULL; } } tg3_mem_rx_release(tp); tg3_mem_tx_release(tp); if (tp->hw_stats) { dma_free_coherent(&tp->pdev->dev, sizeof(struct tg3_hw_stats), tp->hw_stats, tp->stats_mapping); tp->hw_stats = NULL; } } /* * Must not be invoked with interrupt sources disabled and * the hardware shutdown down. Can sleep. */ static int tg3_alloc_consistent(struct tg3 *tp) { int i; tp->hw_stats = dma_alloc_coherent(&tp->pdev->dev, sizeof(struct tg3_hw_stats), &tp->stats_mapping, GFP_KERNEL); if (!tp->hw_stats) goto err_out; memset(tp->hw_stats, 0, sizeof(struct tg3_hw_stats)); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; struct tg3_hw_status *sblk; tnapi->hw_status = dma_alloc_coherent(&tp->pdev->dev, TG3_HW_STATUS_SIZE, &tnapi->status_mapping, GFP_KERNEL); if (!tnapi->hw_status) goto err_out; memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); sblk = tnapi->hw_status; if (tg3_flag(tp, ENABLE_RSS)) { u16 *prodptr = NULL; /* * When RSS is enabled, the status block format changes * slightly. The "rx_jumbo_consumer", "reserved", * and "rx_mini_consumer" members get mapped to the * other three rx return ring producer indexes. */ switch (i) { case 1: prodptr = &sblk->idx[0].rx_producer; break; case 2: prodptr = &sblk->rx_jumbo_consumer; break; case 3: prodptr = &sblk->reserved; break; case 4: prodptr = &sblk->rx_mini_consumer; break; } tnapi->rx_rcb_prod_idx = prodptr; } else { tnapi->rx_rcb_prod_idx = &sblk->idx[0].rx_producer; } } if (tg3_mem_tx_acquire(tp) || tg3_mem_rx_acquire(tp)) goto err_out; return 0; err_out: tg3_free_consistent(tp); return -ENOMEM; } #define MAX_WAIT_CNT 1000 /* To stop a block, clear the enable bit and poll till it * clears. tp->lock is held. */ static int tg3_stop_block(struct tg3 *tp, unsigned long ofs, u32 enable_bit, int silent) { unsigned int i; u32 val; if (tg3_flag(tp, 5705_PLUS)) { switch (ofs) { case RCVLSC_MODE: case DMAC_MODE: case MBFREE_MODE: case BUFMGR_MODE: case MEMARB_MODE: /* We can't enable/disable these bits of the * 5705/5750, just say success. */ return 0; default: break; } } val = tr32(ofs); val &= ~enable_bit; tw32_f(ofs, val); for (i = 0; i < MAX_WAIT_CNT; i++) { udelay(100); val = tr32(ofs); if ((val & enable_bit) == 0) break; } if (i == MAX_WAIT_CNT && !silent) { dev_err(&tp->pdev->dev, "tg3_stop_block timed out, ofs=%lx enable_bit=%x\n", ofs, enable_bit); return -ENODEV; } return 0; } /* tp->lock is held. */ static int tg3_abort_hw(struct tg3 *tp, int silent) { int i, err; tg3_disable_ints(tp); tp->rx_mode &= ~RX_MODE_ENABLE; tw32_f(MAC_RX_MODE, tp->rx_mode); udelay(10); err = tg3_stop_block(tp, RCVBDI_MODE, RCVBDI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVLPC_MODE, RCVLPC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVLSC_MODE, RCVLSC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVDBDI_MODE, RCVDBDI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVDCC_MODE, RCVDCC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RCVCC_MODE, RCVCC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDBDS_MODE, SNDBDS_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDBDI_MODE, SNDBDI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDDATAI_MODE, SNDDATAI_MODE_ENABLE, silent); err |= tg3_stop_block(tp, RDMAC_MODE, RDMAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDDATAC_MODE, SNDDATAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, DMAC_MODE, DMAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, SNDBDC_MODE, SNDBDC_MODE_ENABLE, silent); tp->mac_mode &= ~MAC_MODE_TDE_ENABLE; tw32_f(MAC_MODE, tp->mac_mode); udelay(40); tp->tx_mode &= ~TX_MODE_ENABLE; tw32_f(MAC_TX_MODE, tp->tx_mode); for (i = 0; i < MAX_WAIT_CNT; i++) { udelay(100); if (!(tr32(MAC_TX_MODE) & TX_MODE_ENABLE)) break; } if (i >= MAX_WAIT_CNT) { dev_err(&tp->pdev->dev, "%s timed out, TX_MODE_ENABLE will not clear " "MAC_TX_MODE=%08x\n", __func__, tr32(MAC_TX_MODE)); err |= -ENODEV; } err |= tg3_stop_block(tp, HOSTCC_MODE, HOSTCC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, WDMAC_MODE, WDMAC_MODE_ENABLE, silent); err |= tg3_stop_block(tp, MBFREE_MODE, MBFREE_MODE_ENABLE, silent); tw32(FTQ_RESET, 0xffffffff); tw32(FTQ_RESET, 0x00000000); err |= tg3_stop_block(tp, BUFMGR_MODE, BUFMGR_MODE_ENABLE, silent); err |= tg3_stop_block(tp, MEMARB_MODE, MEMARB_MODE_ENABLE, silent); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->hw_status) memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); } return err; } /* Save PCI command register before chip reset */ static void tg3_save_pci_state(struct tg3 *tp) { pci_read_config_word(tp->pdev, PCI_COMMAND, &tp->pci_cmd); } /* Restore PCI state after chip reset */ static void tg3_restore_pci_state(struct tg3 *tp) { u32 val; /* Re-enable indirect register accesses. */ pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL, tp->misc_host_ctrl); /* Set MAX PCI retry to zero. */ val = (PCISTATE_ROM_ENABLE | PCISTATE_ROM_RETRY_ENABLE); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0 && tg3_flag(tp, PCIX_MODE)) val |= PCISTATE_RETRY_SAME_DMA; /* Allow reads and writes to the APE register and memory space. */ if (tg3_flag(tp, ENABLE_APE)) val |= PCISTATE_ALLOW_APE_CTLSPC_WR | PCISTATE_ALLOW_APE_SHMEM_WR | PCISTATE_ALLOW_APE_PSPACE_WR; pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, val); pci_write_config_word(tp->pdev, PCI_COMMAND, tp->pci_cmd); if (!tg3_flag(tp, PCI_EXPRESS)) { pci_write_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE, tp->pci_cacheline_sz); pci_write_config_byte(tp->pdev, PCI_LATENCY_TIMER, tp->pci_lat_timer); } /* Make sure PCI-X relaxed ordering bit is clear. */ if (tg3_flag(tp, PCIX_MODE)) { u16 pcix_cmd; pci_read_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD, &pcix_cmd); pcix_cmd &= ~PCI_X_CMD_ERO; pci_write_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD, pcix_cmd); } if (tg3_flag(tp, 5780_CLASS)) { /* Chip reset on 5780 will reset MSI enable bit, * so need to restore it. */ if (tg3_flag(tp, USING_MSI)) { u16 ctrl; pci_read_config_word(tp->pdev, tp->msi_cap + PCI_MSI_FLAGS, &ctrl); pci_write_config_word(tp->pdev, tp->msi_cap + PCI_MSI_FLAGS, ctrl | PCI_MSI_FLAGS_ENABLE); val = tr32(MSGINT_MODE); tw32(MSGINT_MODE, val | MSGINT_MODE_ENABLE); } } } /* tp->lock is held. */ static int tg3_chip_reset(struct tg3 *tp) { u32 val; void (*write_op)(struct tg3 *, u32, u32); int i, err; tg3_nvram_lock(tp); tg3_ape_lock(tp, TG3_APE_LOCK_GRC); /* No matching tg3_nvram_unlock() after this because * chip reset below will undo the nvram lock. */ tp->nvram_lock_cnt = 0; /* GRC_MISC_CFG core clock reset will clear the memory * enable bit in PCI register 4 and the MSI enable bit * on some chips, so we save relevant registers here. */ tg3_save_pci_state(tp); if (tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_flag(tp, 5755_PLUS)) tw32(GRC_FASTBOOT_PC, 0); /* * We must avoid the readl() that normally takes place. * It locks machines, causes machine checks, and other * fun things. So, temporarily disable the 5701 * hardware workaround, while we do the reset. */ write_op = tp->write32; if (write_op == tg3_write_flush_reg32) tp->write32 = tg3_write32; /* Prevent the irq handler from reading or writing PCI registers * during chip reset when the memory enable bit in the PCI command * register may be cleared. The chip does not generate interrupt * at this time, but the irq handler may still be called due to irq * sharing or irqpoll. */ tg3_flag_set(tp, CHIP_RESETTING); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tnapi->hw_status) { tnapi->hw_status->status = 0; tnapi->hw_status->status_tag = 0; } tnapi->last_tag = 0; tnapi->last_irq_tag = 0; } smp_mb(); for (i = 0; i < tp->irq_cnt; i++) synchronize_irq(tp->napi[i].irq_vec); if (tg3_asic_rev(tp) == ASIC_REV_57780) { val = tr32(TG3_PCIE_LNKCTL) & ~TG3_PCIE_LNKCTL_L1_PLL_PD_EN; tw32(TG3_PCIE_LNKCTL, val | TG3_PCIE_LNKCTL_L1_PLL_PD_DIS); } /* do the reset */ val = GRC_MISC_CFG_CORECLK_RESET; if (tg3_flag(tp, PCI_EXPRESS)) { /* Force PCIe 1.0a mode */ if (tg3_asic_rev(tp) != ASIC_REV_5785 && !tg3_flag(tp, 57765_PLUS) && tr32(TG3_PCIE_PHY_TSTCTL) == (TG3_PCIE_PHY_TSTCTL_PCIE10 | TG3_PCIE_PHY_TSTCTL_PSCRAM)) tw32(TG3_PCIE_PHY_TSTCTL, TG3_PCIE_PHY_TSTCTL_PSCRAM); if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0) { tw32(GRC_MISC_CFG, (1 << 29)); val |= (1 << 29); } } if (tg3_asic_rev(tp) == ASIC_REV_5906) { tw32(VCPU_STATUS, tr32(VCPU_STATUS) | VCPU_STATUS_DRV_RESET); tw32(GRC_VCPU_EXT_CTRL, tr32(GRC_VCPU_EXT_CTRL) & ~GRC_VCPU_EXT_CTRL_HALT_CPU); } /* Manage gphy power for all CPMU absent PCIe devices. */ if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, CPMU_PRESENT)) val |= GRC_MISC_CFG_KEEP_GPHY_POWER; tw32(GRC_MISC_CFG, val); /* restore 5701 hardware bug workaround write method */ tp->write32 = write_op; /* Unfortunately, we have to delay before the PCI read back. * Some 575X chips even will not respond to a PCI cfg access * when the reset command is given to the chip. * * How do these hardware designers expect things to work * properly if the PCI write is posted for a long period * of time? It is always necessary to have some method by * which a register read back can occur to push the write * out which does the reset. * * For most tg3 variants the trick below was working. * Ho hum... */ udelay(120); /* Flush PCI posted writes. The normal MMIO registers * are inaccessible at this time so this is the only * way to make this reliably (actually, this is no longer * the case, see above). I tried to use indirect * register read/write but this upset some 5701 variants. */ pci_read_config_dword(tp->pdev, PCI_COMMAND, &val); udelay(120); if (tg3_flag(tp, PCI_EXPRESS) && pci_is_pcie(tp->pdev)) { u16 val16; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A0) { int j; u32 cfg_val; /* Wait for link training to complete. */ for (j = 0; j < 5000; j++) udelay(100); pci_read_config_dword(tp->pdev, 0xc4, &cfg_val); pci_write_config_dword(tp->pdev, 0xc4, cfg_val | (1 << 15)); } /* Clear the "no snoop" and "relaxed ordering" bits. */ val16 = PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN; /* * Older PCIe devices only support the 128 byte * MPS setting. Enforce the restriction. */ if (!tg3_flag(tp, CPMU_PRESENT)) val16 |= PCI_EXP_DEVCTL_PAYLOAD; pcie_capability_clear_word(tp->pdev, PCI_EXP_DEVCTL, val16); /* Clear error status */ pcie_capability_write_word(tp->pdev, PCI_EXP_DEVSTA, PCI_EXP_DEVSTA_CED | PCI_EXP_DEVSTA_NFED | PCI_EXP_DEVSTA_FED | PCI_EXP_DEVSTA_URD); } tg3_restore_pci_state(tp); tg3_flag_clear(tp, CHIP_RESETTING); tg3_flag_clear(tp, ERROR_PROCESSED); val = 0; if (tg3_flag(tp, 5780_CLASS)) val = tr32(MEMARB_MODE); tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A3) { tg3_stop_fw(tp); tw32(0x5000, 0x400); } if (tg3_flag(tp, IS_SSB_CORE)) { /* * BCM4785: In order to avoid repercussions from using * potentially defective internal ROM, stop the Rx RISC CPU, * which is not required. */ tg3_stop_fw(tp); tg3_halt_cpu(tp, RX_CPU_BASE); } tw32(GRC_MODE, tp->grc_mode); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A0) { val = tr32(0xc4); tw32(0xc4, val | (1 << 15)); } if ((tp->nic_sram_data_cfg & NIC_SRAM_DATA_CFG_MINI_PCI) != 0 && tg3_asic_rev(tp) == ASIC_REV_5705) { tp->pci_clock_ctrl |= CLOCK_CTRL_CLKRUN_OENABLE; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A0) tp->pci_clock_ctrl |= CLOCK_CTRL_FORCE_CLKRUN; tw32(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl); } if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) { tp->mac_mode = MAC_MODE_PORT_MODE_TBI; val = tp->mac_mode; } else if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) { tp->mac_mode = MAC_MODE_PORT_MODE_GMII; val = tp->mac_mode; } else val = 0; tw32_f(MAC_MODE, val); udelay(40); tg3_ape_unlock(tp, TG3_APE_LOCK_GRC); err = tg3_poll_fw(tp); if (err) return err; tg3_mdio_start(tp); if (tg3_flag(tp, PCI_EXPRESS) && tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0 && tg3_asic_rev(tp) != ASIC_REV_5785 && !tg3_flag(tp, 57765_PLUS)) { val = tr32(0x7c00); tw32(0x7c00, val | (1 << 25)); } if (tg3_asic_rev(tp) == ASIC_REV_5720) { val = tr32(TG3_CPMU_CLCK_ORIDE); tw32(TG3_CPMU_CLCK_ORIDE, val & ~CPMU_CLCK_ORIDE_MAC_ORIDE_EN); } /* Reprobe ASF enable state. */ tg3_flag_clear(tp, ENABLE_ASF); tg3_flag_clear(tp, ASF_NEW_HANDSHAKE); tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val); if (val == NIC_SRAM_DATA_SIG_MAGIC) { u32 nic_cfg; tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg); if (nic_cfg & NIC_SRAM_DATA_CFG_ASF_ENABLE) { tg3_flag_set(tp, ENABLE_ASF); tp->last_event_jiffies = jiffies; if (tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, ASF_NEW_HANDSHAKE); } } return 0; } static void tg3_get_nstats(struct tg3 *, struct rtnl_link_stats64 *); static void tg3_get_estats(struct tg3 *, struct tg3_ethtool_stats *); /* tp->lock is held. */ static int tg3_halt(struct tg3 *tp, int kind, int silent) { int err; tg3_stop_fw(tp); tg3_write_sig_pre_reset(tp, kind); tg3_abort_hw(tp, silent); err = tg3_chip_reset(tp); __tg3_set_mac_addr(tp, 0); tg3_write_sig_legacy(tp, kind); tg3_write_sig_post_reset(tp, kind); if (tp->hw_stats) { /* Save the stats across chip resets... */ tg3_get_nstats(tp, &tp->net_stats_prev); tg3_get_estats(tp, &tp->estats_prev); /* And make sure the next sample is new data */ memset(tp->hw_stats, 0, sizeof(struct tg3_hw_stats)); } if (err) return err; return 0; } static int tg3_set_mac_addr(struct net_device *dev, void *p) { struct tg3 *tp = netdev_priv(dev); struct sockaddr *addr = p; int err = 0, skip_mac_1 = 0; if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; memcpy(dev->dev_addr, addr->sa_data, dev->addr_len); if (!netif_running(dev)) return 0; if (tg3_flag(tp, ENABLE_ASF)) { u32 addr0_high, addr0_low, addr1_high, addr1_low; addr0_high = tr32(MAC_ADDR_0_HIGH); addr0_low = tr32(MAC_ADDR_0_LOW); addr1_high = tr32(MAC_ADDR_1_HIGH); addr1_low = tr32(MAC_ADDR_1_LOW); /* Skip MAC addr 1 if ASF is using it. */ if ((addr0_high != addr1_high || addr0_low != addr1_low) && !(addr1_high == 0 && addr1_low == 0)) skip_mac_1 = 1; } spin_lock_bh(&tp->lock); __tg3_set_mac_addr(tp, skip_mac_1); spin_unlock_bh(&tp->lock); return err; } /* tp->lock is held. */ static void tg3_set_bdinfo(struct tg3 *tp, u32 bdinfo_addr, dma_addr_t mapping, u32 maxlen_flags, u32 nic_addr) { tg3_write_mem(tp, (bdinfo_addr + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH), ((u64) mapping >> 32)); tg3_write_mem(tp, (bdinfo_addr + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW), ((u64) mapping & 0xffffffff)); tg3_write_mem(tp, (bdinfo_addr + TG3_BDINFO_MAXLEN_FLAGS), maxlen_flags); if (!tg3_flag(tp, 5705_PLUS)) tg3_write_mem(tp, (bdinfo_addr + TG3_BDINFO_NIC_ADDR), nic_addr); } static void tg3_coal_tx_init(struct tg3 *tp, struct ethtool_coalesce *ec) { int i = 0; if (!tg3_flag(tp, ENABLE_TSS)) { tw32(HOSTCC_TXCOL_TICKS, ec->tx_coalesce_usecs); tw32(HOSTCC_TXMAX_FRAMES, ec->tx_max_coalesced_frames); tw32(HOSTCC_TXCOAL_MAXF_INT, ec->tx_max_coalesced_frames_irq); } else { tw32(HOSTCC_TXCOL_TICKS, 0); tw32(HOSTCC_TXMAX_FRAMES, 0); tw32(HOSTCC_TXCOAL_MAXF_INT, 0); for (; i < tp->txq_cnt; i++) { u32 reg; reg = HOSTCC_TXCOL_TICKS_VEC1 + i * 0x18; tw32(reg, ec->tx_coalesce_usecs); reg = HOSTCC_TXMAX_FRAMES_VEC1 + i * 0x18; tw32(reg, ec->tx_max_coalesced_frames); reg = HOSTCC_TXCOAL_MAXF_INT_VEC1 + i * 0x18; tw32(reg, ec->tx_max_coalesced_frames_irq); } } for (; i < tp->irq_max - 1; i++) { tw32(HOSTCC_TXCOL_TICKS_VEC1 + i * 0x18, 0); tw32(HOSTCC_TXMAX_FRAMES_VEC1 + i * 0x18, 0); tw32(HOSTCC_TXCOAL_MAXF_INT_VEC1 + i * 0x18, 0); } } static void tg3_coal_rx_init(struct tg3 *tp, struct ethtool_coalesce *ec) { int i = 0; u32 limit = tp->rxq_cnt; if (!tg3_flag(tp, ENABLE_RSS)) { tw32(HOSTCC_RXCOL_TICKS, ec->rx_coalesce_usecs); tw32(HOSTCC_RXMAX_FRAMES, ec->rx_max_coalesced_frames); tw32(HOSTCC_RXCOAL_MAXF_INT, ec->rx_max_coalesced_frames_irq); limit--; } else { tw32(HOSTCC_RXCOL_TICKS, 0); tw32(HOSTCC_RXMAX_FRAMES, 0); tw32(HOSTCC_RXCOAL_MAXF_INT, 0); } for (; i < limit; i++) { u32 reg; reg = HOSTCC_RXCOL_TICKS_VEC1 + i * 0x18; tw32(reg, ec->rx_coalesce_usecs); reg = HOSTCC_RXMAX_FRAMES_VEC1 + i * 0x18; tw32(reg, ec->rx_max_coalesced_frames); reg = HOSTCC_RXCOAL_MAXF_INT_VEC1 + i * 0x18; tw32(reg, ec->rx_max_coalesced_frames_irq); } for (; i < tp->irq_max - 1; i++) { tw32(HOSTCC_RXCOL_TICKS_VEC1 + i * 0x18, 0); tw32(HOSTCC_RXMAX_FRAMES_VEC1 + i * 0x18, 0); tw32(HOSTCC_RXCOAL_MAXF_INT_VEC1 + i * 0x18, 0); } } static void __tg3_set_coalesce(struct tg3 *tp, struct ethtool_coalesce *ec) { tg3_coal_tx_init(tp, ec); tg3_coal_rx_init(tp, ec); if (!tg3_flag(tp, 5705_PLUS)) { u32 val = ec->stats_block_coalesce_usecs; tw32(HOSTCC_RXCOAL_TICK_INT, ec->rx_coalesce_usecs_irq); tw32(HOSTCC_TXCOAL_TICK_INT, ec->tx_coalesce_usecs_irq); if (!tp->link_up) val = 0; tw32(HOSTCC_STAT_COAL_TICKS, val); } } /* tp->lock is held. */ static void tg3_rings_reset(struct tg3 *tp) { int i; u32 stblk, txrcb, rxrcb, limit; struct tg3_napi *tnapi = &tp->napi[0]; /* Disable all transmit rings but the first. */ if (!tg3_flag(tp, 5705_PLUS)) limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 16; else if (tg3_flag(tp, 5717_PLUS)) limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 4; else if (tg3_flag(tp, 57765_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5762) limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 2; else limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE; for (txrcb = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE; txrcb < limit; txrcb += TG3_BDINFO_SIZE) tg3_write_mem(tp, txrcb + TG3_BDINFO_MAXLEN_FLAGS, BDINFO_FLAGS_DISABLED); /* Disable all receive return rings but the first. */ if (tg3_flag(tp, 5717_PLUS)) limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 17; else if (!tg3_flag(tp, 5705_PLUS)) limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 16; else if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5762 || tg3_flag(tp, 57765_CLASS)) limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 4; else limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE; for (rxrcb = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE; rxrcb < limit; rxrcb += TG3_BDINFO_SIZE) tg3_write_mem(tp, rxrcb + TG3_BDINFO_MAXLEN_FLAGS, BDINFO_FLAGS_DISABLED); /* Disable interrupts */ tw32_mailbox_f(tp->napi[0].int_mbox, 1); tp->napi[0].chk_msi_cnt = 0; tp->napi[0].last_rx_cons = 0; tp->napi[0].last_tx_cons = 0; /* Zero mailbox registers. */ if (tg3_flag(tp, SUPPORT_MSIX)) { for (i = 1; i < tp->irq_max; i++) { tp->napi[i].tx_prod = 0; tp->napi[i].tx_cons = 0; if (tg3_flag(tp, ENABLE_TSS)) tw32_mailbox(tp->napi[i].prodmbox, 0); tw32_rx_mbox(tp->napi[i].consmbox, 0); tw32_mailbox_f(tp->napi[i].int_mbox, 1); tp->napi[i].chk_msi_cnt = 0; tp->napi[i].last_rx_cons = 0; tp->napi[i].last_tx_cons = 0; } if (!tg3_flag(tp, ENABLE_TSS)) tw32_mailbox(tp->napi[0].prodmbox, 0); } else { tp->napi[0].tx_prod = 0; tp->napi[0].tx_cons = 0; tw32_mailbox(tp->napi[0].prodmbox, 0); tw32_rx_mbox(tp->napi[0].consmbox, 0); } /* Make sure the NIC-based send BD rings are disabled. */ if (!tg3_flag(tp, 5705_PLUS)) { u32 mbox = MAILBOX_SNDNIC_PROD_IDX_0 + TG3_64BIT_REG_LOW; for (i = 0; i < 16; i++) tw32_tx_mbox(mbox + i * 8, 0); } txrcb = NIC_SRAM_SEND_RCB; rxrcb = NIC_SRAM_RCV_RET_RCB; /* Clear status block in ram. */ memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); /* Set status block DMA address */ tw32(HOSTCC_STATUS_BLK_HOST_ADDR + TG3_64BIT_REG_HIGH, ((u64) tnapi->status_mapping >> 32)); tw32(HOSTCC_STATUS_BLK_HOST_ADDR + TG3_64BIT_REG_LOW, ((u64) tnapi->status_mapping & 0xffffffff)); if (tnapi->tx_ring) { tg3_set_bdinfo(tp, txrcb, tnapi->tx_desc_mapping, (TG3_TX_RING_SIZE << BDINFO_FLAGS_MAXLEN_SHIFT), NIC_SRAM_TX_BUFFER_DESC); txrcb += TG3_BDINFO_SIZE; } if (tnapi->rx_rcb) { tg3_set_bdinfo(tp, rxrcb, tnapi->rx_rcb_mapping, (tp->rx_ret_ring_mask + 1) << BDINFO_FLAGS_MAXLEN_SHIFT, 0); rxrcb += TG3_BDINFO_SIZE; } stblk = HOSTCC_STATBLCK_RING1; for (i = 1, tnapi++; i < tp->irq_cnt; i++, tnapi++) { u64 mapping = (u64)tnapi->status_mapping; tw32(stblk + TG3_64BIT_REG_HIGH, mapping >> 32); tw32(stblk + TG3_64BIT_REG_LOW, mapping & 0xffffffff); /* Clear status block in ram. */ memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE); if (tnapi->tx_ring) { tg3_set_bdinfo(tp, txrcb, tnapi->tx_desc_mapping, (TG3_TX_RING_SIZE << BDINFO_FLAGS_MAXLEN_SHIFT), NIC_SRAM_TX_BUFFER_DESC); txrcb += TG3_BDINFO_SIZE; } tg3_set_bdinfo(tp, rxrcb, tnapi->rx_rcb_mapping, ((tp->rx_ret_ring_mask + 1) << BDINFO_FLAGS_MAXLEN_SHIFT), 0); stblk += 8; rxrcb += TG3_BDINFO_SIZE; } } static void tg3_setup_rxbd_thresholds(struct tg3 *tp) { u32 val, bdcache_maxcnt, host_rep_thresh, nic_rep_thresh; if (!tg3_flag(tp, 5750_PLUS) || tg3_flag(tp, 5780_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_flag(tp, 57765_PLUS)) bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5700; else if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5787) bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5755; else bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5906; nic_rep_thresh = min(bdcache_maxcnt / 2, tp->rx_std_max_post); host_rep_thresh = max_t(u32, tp->rx_pending / 8, 1); val = min(nic_rep_thresh, host_rep_thresh); tw32(RCVBDI_STD_THRESH, val); if (tg3_flag(tp, 57765_PLUS)) tw32(STD_REPLENISH_LWM, bdcache_maxcnt); if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS)) return; bdcache_maxcnt = TG3_SRAM_RX_JMB_BDCACHE_SIZE_5700; host_rep_thresh = max_t(u32, tp->rx_jumbo_pending / 8, 1); val = min(bdcache_maxcnt / 2, host_rep_thresh); tw32(RCVBDI_JUMBO_THRESH, val); if (tg3_flag(tp, 57765_PLUS)) tw32(JMB_REPLENISH_LWM, bdcache_maxcnt); } static inline u32 calc_crc(unsigned char *buf, int len) { u32 reg; u32 tmp; int j, k; reg = 0xffffffff; for (j = 0; j < len; j++) { reg ^= buf[j]; for (k = 0; k < 8; k++) { tmp = reg & 0x01; reg >>= 1; if (tmp) reg ^= 0xedb88320; } } return ~reg; } static void tg3_set_multi(struct tg3 *tp, unsigned int accept_all) { /* accept or reject all multicast frames */ tw32(MAC_HASH_REG_0, accept_all ? 0xffffffff : 0); tw32(MAC_HASH_REG_1, accept_all ? 0xffffffff : 0); tw32(MAC_HASH_REG_2, accept_all ? 0xffffffff : 0); tw32(MAC_HASH_REG_3, accept_all ? 0xffffffff : 0); } static void __tg3_set_rx_mode(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); u32 rx_mode; rx_mode = tp->rx_mode & ~(RX_MODE_PROMISC | RX_MODE_KEEP_VLAN_TAG); #if !defined(CONFIG_VLAN_8021Q) && !defined(CONFIG_VLAN_8021Q_MODULE) /* When ASF is in use, we always keep the RX_MODE_KEEP_VLAN_TAG * flag clear. */ if (!tg3_flag(tp, ENABLE_ASF)) rx_mode |= RX_MODE_KEEP_VLAN_TAG; #endif if (dev->flags & IFF_PROMISC) { /* Promiscuous mode. */ rx_mode |= RX_MODE_PROMISC; } else if (dev->flags & IFF_ALLMULTI) { /* Accept all multicast. */ tg3_set_multi(tp, 1); } else if (netdev_mc_empty(dev)) { /* Reject all multicast. */ tg3_set_multi(tp, 0); } else { /* Accept one or more multicast(s). */ struct netdev_hw_addr *ha; u32 mc_filter[4] = { 0, }; u32 regidx; u32 bit; u32 crc; netdev_for_each_mc_addr(ha, dev) { crc = calc_crc(ha->addr, ETH_ALEN); bit = ~crc & 0x7f; regidx = (bit & 0x60) >> 5; bit &= 0x1f; mc_filter[regidx] |= (1 << bit); } tw32(MAC_HASH_REG_0, mc_filter[0]); tw32(MAC_HASH_REG_1, mc_filter[1]); tw32(MAC_HASH_REG_2, mc_filter[2]); tw32(MAC_HASH_REG_3, mc_filter[3]); } if (rx_mode != tp->rx_mode) { tp->rx_mode = rx_mode; tw32_f(MAC_RX_MODE, rx_mode); udelay(10); } } static void tg3_rss_init_dflt_indir_tbl(struct tg3 *tp, u32 qcnt) { int i; for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++) tp->rss_ind_tbl[i] = ethtool_rxfh_indir_default(i, qcnt); } static void tg3_rss_check_indir_tbl(struct tg3 *tp) { int i; if (!tg3_flag(tp, SUPPORT_MSIX)) return; if (tp->rxq_cnt == 1) { memset(&tp->rss_ind_tbl[0], 0, sizeof(tp->rss_ind_tbl)); return; } /* Validate table against current IRQ count */ for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++) { if (tp->rss_ind_tbl[i] >= tp->rxq_cnt) break; } if (i != TG3_RSS_INDIR_TBL_SIZE) tg3_rss_init_dflt_indir_tbl(tp, tp->rxq_cnt); } static void tg3_rss_write_indir_tbl(struct tg3 *tp) { int i = 0; u32 reg = MAC_RSS_INDIR_TBL_0; while (i < TG3_RSS_INDIR_TBL_SIZE) { u32 val = tp->rss_ind_tbl[i]; i++; for (; i % 8; i++) { val <<= 4; val |= tp->rss_ind_tbl[i]; } tw32(reg, val); reg += 4; } } /* tp->lock is held. */ static int tg3_reset_hw(struct tg3 *tp, int reset_phy) { u32 val, rdmac_mode; int i, err, limit; struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring; tg3_disable_ints(tp); tg3_stop_fw(tp); tg3_write_sig_pre_reset(tp, RESET_KIND_INIT); if (tg3_flag(tp, INIT_COMPLETE)) tg3_abort_hw(tp, 1); /* Enable MAC control of LPI */ if (tp->phy_flags & TG3_PHYFLG_EEE_CAP) { val = TG3_CPMU_EEE_LNKIDL_PCIE_NL0 | TG3_CPMU_EEE_LNKIDL_UART_IDL; if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) val |= TG3_CPMU_EEE_LNKIDL_APE_TX_MT; tw32_f(TG3_CPMU_EEE_LNKIDL_CTRL, val); tw32_f(TG3_CPMU_EEE_CTRL, TG3_CPMU_EEE_CTRL_EXIT_20_1_US); val = TG3_CPMU_EEEMD_ERLY_L1_XIT_DET | TG3_CPMU_EEEMD_LPI_IN_TX | TG3_CPMU_EEEMD_LPI_IN_RX | TG3_CPMU_EEEMD_EEE_ENABLE; if (tg3_asic_rev(tp) != ASIC_REV_5717) val |= TG3_CPMU_EEEMD_SND_IDX_DET_EN; if (tg3_flag(tp, ENABLE_APE)) val |= TG3_CPMU_EEEMD_APE_TX_DET_EN; tw32_f(TG3_CPMU_EEE_MODE, val); tw32_f(TG3_CPMU_EEE_DBTMR1, TG3_CPMU_DBTMR1_PCIEXIT_2047US | TG3_CPMU_DBTMR1_LNKIDLE_2047US); tw32_f(TG3_CPMU_EEE_DBTMR2, TG3_CPMU_DBTMR2_APE_TX_2047US | TG3_CPMU_DBTMR2_TXIDXEQ_2047US); } if (reset_phy) tg3_phy_reset(tp); err = tg3_chip_reset(tp); if (err) return err; tg3_write_sig_legacy(tp, RESET_KIND_INIT); if (tg3_chip_rev(tp) == CHIPREV_5784_AX) { val = tr32(TG3_CPMU_CTRL); val &= ~(CPMU_CTRL_LINK_AWARE_MODE | CPMU_CTRL_LINK_IDLE_MODE); tw32(TG3_CPMU_CTRL, val); val = tr32(TG3_CPMU_LSPD_10MB_CLK); val &= ~CPMU_LSPD_10MB_MACCLK_MASK; val |= CPMU_LSPD_10MB_MACCLK_6_25; tw32(TG3_CPMU_LSPD_10MB_CLK, val); val = tr32(TG3_CPMU_LNK_AWARE_PWRMD); val &= ~CPMU_LNK_AWARE_MACCLK_MASK; val |= CPMU_LNK_AWARE_MACCLK_6_25; tw32(TG3_CPMU_LNK_AWARE_PWRMD, val); val = tr32(TG3_CPMU_HST_ACC); val &= ~CPMU_HST_ACC_MACCLK_MASK; val |= CPMU_HST_ACC_MACCLK_6_25; tw32(TG3_CPMU_HST_ACC, val); } if (tg3_asic_rev(tp) == ASIC_REV_57780) { val = tr32(PCIE_PWR_MGMT_THRESH) & ~PCIE_PWR_MGMT_L1_THRESH_MSK; val |= PCIE_PWR_MGMT_EXT_ASPM_TMR_EN | PCIE_PWR_MGMT_L1_THRESH_4MS; tw32(PCIE_PWR_MGMT_THRESH, val); val = tr32(TG3_PCIE_EIDLE_DELAY) & ~TG3_PCIE_EIDLE_DELAY_MASK; tw32(TG3_PCIE_EIDLE_DELAY, val | TG3_PCIE_EIDLE_DELAY_13_CLKS); tw32(TG3_CORR_ERR_STAT, TG3_CORR_ERR_STAT_CLEAR); val = tr32(TG3_PCIE_LNKCTL) & ~TG3_PCIE_LNKCTL_L1_PLL_PD_EN; tw32(TG3_PCIE_LNKCTL, val | TG3_PCIE_LNKCTL_L1_PLL_PD_DIS); } if (tg3_flag(tp, L1PLLPD_EN)) { u32 grc_mode = tr32(GRC_MODE); /* Access the lower 1K of PL PCIE block registers. */ val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK; tw32(GRC_MODE, val | GRC_MODE_PCIE_PL_SEL); val = tr32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL1); tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL1, val | TG3_PCIE_PL_LO_PHYCTL1_L1PLLPD_EN); tw32(GRC_MODE, grc_mode); } if (tg3_flag(tp, 57765_CLASS)) { if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) { u32 grc_mode = tr32(GRC_MODE); /* Access the lower 1K of PL PCIE block registers. */ val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK; tw32(GRC_MODE, val | GRC_MODE_PCIE_PL_SEL); val = tr32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL5); tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL5, val | TG3_PCIE_PL_LO_PHYCTL5_DIS_L2CLKREQ); tw32(GRC_MODE, grc_mode); } if (tg3_chip_rev(tp) != CHIPREV_57765_AX) { u32 grc_mode; /* Fix transmit hangs */ val = tr32(TG3_CPMU_PADRNG_CTL); val |= TG3_CPMU_PADRNG_CTL_RDIV2; tw32(TG3_CPMU_PADRNG_CTL, val); grc_mode = tr32(GRC_MODE); /* Access the lower 1K of DL PCIE block registers. */ val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK; tw32(GRC_MODE, val | GRC_MODE_PCIE_DL_SEL); val = tr32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_DL_LO_FTSMAX); val &= ~TG3_PCIE_DL_LO_FTSMAX_MSK; tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_DL_LO_FTSMAX, val | TG3_PCIE_DL_LO_FTSMAX_VAL); tw32(GRC_MODE, grc_mode); } val = tr32(TG3_CPMU_LSPD_10MB_CLK); val &= ~CPMU_LSPD_10MB_MACCLK_MASK; val |= CPMU_LSPD_10MB_MACCLK_6_25; tw32(TG3_CPMU_LSPD_10MB_CLK, val); } /* This works around an issue with Athlon chipsets on * B3 tigon3 silicon. This bit has no effect on any * other revision. But do not set this on PCI Express * chips and don't even touch the clocks if the CPMU is present. */ if (!tg3_flag(tp, CPMU_PRESENT)) { if (!tg3_flag(tp, PCI_EXPRESS)) tp->pci_clock_ctrl |= CLOCK_CTRL_DELAY_PCI_GRANT; tw32_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0 && tg3_flag(tp, PCIX_MODE)) { val = tr32(TG3PCI_PCISTATE); val |= PCISTATE_RETRY_SAME_DMA; tw32(TG3PCI_PCISTATE, val); } if (tg3_flag(tp, ENABLE_APE)) { /* Allow reads and writes to the * APE register and memory space. */ val = tr32(TG3PCI_PCISTATE); val |= PCISTATE_ALLOW_APE_CTLSPC_WR | PCISTATE_ALLOW_APE_SHMEM_WR | PCISTATE_ALLOW_APE_PSPACE_WR; tw32(TG3PCI_PCISTATE, val); } if (tg3_chip_rev(tp) == CHIPREV_5704_BX) { /* Enable some hw fixes. */ val = tr32(TG3PCI_MSI_DATA); val |= (1 << 26) | (1 << 28) | (1 << 29); tw32(TG3PCI_MSI_DATA, val); } /* Descriptor ring init may make accesses to the * NIC SRAM area to setup the TX descriptors, so we * can only do this after the hardware has been * successfully reset. */ err = tg3_init_rings(tp); if (err) return err; if (tg3_flag(tp, 57765_PLUS)) { val = tr32(TG3PCI_DMA_RW_CTRL) & ~DMA_RWCTRL_DIS_CACHE_ALIGNMENT; if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) val &= ~DMA_RWCTRL_CRDRDR_RDMA_MRRS_MSK; if (!tg3_flag(tp, 57765_CLASS) && tg3_asic_rev(tp) != ASIC_REV_5717 && tg3_asic_rev(tp) != ASIC_REV_5762) val |= DMA_RWCTRL_TAGGED_STAT_WA; tw32(TG3PCI_DMA_RW_CTRL, val | tp->dma_rwctrl); } else if (tg3_asic_rev(tp) != ASIC_REV_5784 && tg3_asic_rev(tp) != ASIC_REV_5761) { /* This value is determined during the probe time DMA * engine test, tg3_test_dma. */ tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); } tp->grc_mode &= ~(GRC_MODE_HOST_SENDBDS | GRC_MODE_4X_NIC_SEND_RINGS | GRC_MODE_NO_TX_PHDR_CSUM | GRC_MODE_NO_RX_PHDR_CSUM); tp->grc_mode |= GRC_MODE_HOST_SENDBDS; /* Pseudo-header checksum is done by hardware logic and not * the offload processers, so make the chip do the pseudo- * header checksums on receive. For transmit it is more * convenient to do the pseudo-header checksum in software * as Linux does that on transmit for us in all cases. */ tp->grc_mode |= GRC_MODE_NO_TX_PHDR_CSUM; val = GRC_MODE_IRQ_ON_MAC_ATTN | GRC_MODE_HOST_STACKUP; if (tp->rxptpctl) tw32(TG3_RX_PTP_CTL, tp->rxptpctl | TG3_RX_PTP_CTL_HWTS_INTERLOCK); if (tg3_flag(tp, PTP_CAPABLE)) val |= GRC_MODE_TIME_SYNC_ENABLE; tw32(GRC_MODE, tp->grc_mode | val); /* Setup the timer prescalar register. Clock is always 66Mhz. */ val = tr32(GRC_MISC_CFG); val &= ~0xff; val |= (65 << GRC_MISC_CFG_PRESCALAR_SHIFT); tw32(GRC_MISC_CFG, val); /* Initialize MBUF/DESC pool. */ if (tg3_flag(tp, 5750_PLUS)) { /* Do nothing. */ } else if (tg3_asic_rev(tp) != ASIC_REV_5705) { tw32(BUFMGR_MB_POOL_ADDR, NIC_SRAM_MBUF_POOL_BASE); if (tg3_asic_rev(tp) == ASIC_REV_5704) tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE64); else tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE96); tw32(BUFMGR_DMA_DESC_POOL_ADDR, NIC_SRAM_DMA_DESC_POOL_BASE); tw32(BUFMGR_DMA_DESC_POOL_SIZE, NIC_SRAM_DMA_DESC_POOL_SIZE); } else if (tg3_flag(tp, TSO_CAPABLE)) { int fw_len; fw_len = tp->fw_len; fw_len = (fw_len + (0x80 - 1)) & ~(0x80 - 1); tw32(BUFMGR_MB_POOL_ADDR, NIC_SRAM_MBUF_POOL_BASE5705 + fw_len); tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE5705 - fw_len - 0xa00); } if (tp->dev->mtu <= ETH_DATA_LEN) { tw32(BUFMGR_MB_RDMA_LOW_WATER, tp->bufmgr_config.mbuf_read_dma_low_water); tw32(BUFMGR_MB_MACRX_LOW_WATER, tp->bufmgr_config.mbuf_mac_rx_low_water); tw32(BUFMGR_MB_HIGH_WATER, tp->bufmgr_config.mbuf_high_water); } else { tw32(BUFMGR_MB_RDMA_LOW_WATER, tp->bufmgr_config.mbuf_read_dma_low_water_jumbo); tw32(BUFMGR_MB_MACRX_LOW_WATER, tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo); tw32(BUFMGR_MB_HIGH_WATER, tp->bufmgr_config.mbuf_high_water_jumbo); } tw32(BUFMGR_DMA_LOW_WATER, tp->bufmgr_config.dma_low_water); tw32(BUFMGR_DMA_HIGH_WATER, tp->bufmgr_config.dma_high_water); val = BUFMGR_MODE_ENABLE | BUFMGR_MODE_ATTN_ENABLE; if (tg3_asic_rev(tp) == ASIC_REV_5719) val |= BUFMGR_MODE_NO_TX_UNDERRUN; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5720_A0) val |= BUFMGR_MODE_MBLOW_ATTN_ENAB; tw32(BUFMGR_MODE, val); for (i = 0; i < 2000; i++) { if (tr32(BUFMGR_MODE) & BUFMGR_MODE_ENABLE) break; udelay(10); } if (i >= 2000) { netdev_err(tp->dev, "%s cannot enable BUFMGR\n", __func__); return -ENODEV; } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5906_A1) tw32(ISO_PKT_TX, (tr32(ISO_PKT_TX) & ~0x3) | 0x2); tg3_setup_rxbd_thresholds(tp); /* Initialize TG3_BDINFO's at: * RCVDBDI_STD_BD: standard eth size rx ring * RCVDBDI_JUMBO_BD: jumbo frame rx ring * RCVDBDI_MINI_BD: small frame rx ring (??? does not work) * * like so: * TG3_BDINFO_HOST_ADDR: high/low parts of DMA address of ring * TG3_BDINFO_MAXLEN_FLAGS: (rx max buffer size << 16) | * ring attribute flags * TG3_BDINFO_NIC_ADDR: location of descriptors in nic SRAM * * Standard receive ring @ NIC_SRAM_RX_BUFFER_DESC, 512 entries. * Jumbo receive ring @ NIC_SRAM_RX_JUMBO_BUFFER_DESC, 256 entries. * * The size of each ring is fixed in the firmware, but the location is * configurable. */ tw32(RCVDBDI_STD_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH, ((u64) tpr->rx_std_mapping >> 32)); tw32(RCVDBDI_STD_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW, ((u64) tpr->rx_std_mapping & 0xffffffff)); if (!tg3_flag(tp, 5717_PLUS)) tw32(RCVDBDI_STD_BD + TG3_BDINFO_NIC_ADDR, NIC_SRAM_RX_BUFFER_DESC); /* Disable the mini ring */ if (!tg3_flag(tp, 5705_PLUS)) tw32(RCVDBDI_MINI_BD + TG3_BDINFO_MAXLEN_FLAGS, BDINFO_FLAGS_DISABLED); /* Program the jumbo buffer descriptor ring control * blocks on those devices that have them. */ if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS))) { if (tg3_flag(tp, JUMBO_RING_ENABLE)) { tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH, ((u64) tpr->rx_jmb_mapping >> 32)); tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW, ((u64) tpr->rx_jmb_mapping & 0xffffffff)); val = TG3_RX_JMB_RING_SIZE(tp) << BDINFO_FLAGS_MAXLEN_SHIFT; tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_MAXLEN_FLAGS, val | BDINFO_FLAGS_USE_EXT_RECV); if (!tg3_flag(tp, USE_JUMBO_BDFLAG) || tg3_flag(tp, 57765_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5762) tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_NIC_ADDR, NIC_SRAM_RX_JUMBO_BUFFER_DESC); } else { tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_MAXLEN_FLAGS, BDINFO_FLAGS_DISABLED); } if (tg3_flag(tp, 57765_PLUS)) { val = TG3_RX_STD_RING_SIZE(tp); val <<= BDINFO_FLAGS_MAXLEN_SHIFT; val |= (TG3_RX_STD_DMA_SZ << 2); } else val = TG3_RX_STD_DMA_SZ << BDINFO_FLAGS_MAXLEN_SHIFT; } else val = TG3_RX_STD_MAX_SIZE_5700 << BDINFO_FLAGS_MAXLEN_SHIFT; tw32(RCVDBDI_STD_BD + TG3_BDINFO_MAXLEN_FLAGS, val); tpr->rx_std_prod_idx = tp->rx_pending; tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG, tpr->rx_std_prod_idx); tpr->rx_jmb_prod_idx = tg3_flag(tp, JUMBO_RING_ENABLE) ? tp->rx_jumbo_pending : 0; tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG, tpr->rx_jmb_prod_idx); tg3_rings_reset(tp); /* Initialize MAC address and backoff seed. */ __tg3_set_mac_addr(tp, 0); /* MTU + ethernet header + FCS + optional VLAN tag */ tw32(MAC_RX_MTU_SIZE, tp->dev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN); /* The slot time is changed by tg3_setup_phy if we * run at gigabit with half duplex. */ val = (2 << TX_LENGTHS_IPG_CRS_SHIFT) | (6 << TX_LENGTHS_IPG_SHIFT) | (32 << TX_LENGTHS_SLOT_TIME_SHIFT); if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) val |= tr32(MAC_TX_LENGTHS) & (TX_LENGTHS_JMB_FRM_LEN_MSK | TX_LENGTHS_CNT_DWN_VAL_MSK); tw32(MAC_TX_LENGTHS, val); /* Receive rules. */ tw32(MAC_RCV_RULE_CFG, RCV_RULE_CFG_DEFAULT_CLASS); tw32(RCVLPC_CONFIG, 0x0181); /* Calculate RDMAC_MODE setting early, we need it to determine * the RCVLPC_STATE_ENABLE mask. */ rdmac_mode = (RDMAC_MODE_ENABLE | RDMAC_MODE_TGTABORT_ENAB | RDMAC_MODE_MSTABORT_ENAB | RDMAC_MODE_PARITYERR_ENAB | RDMAC_MODE_ADDROFLOW_ENAB | RDMAC_MODE_FIFOOFLOW_ENAB | RDMAC_MODE_FIFOURUN_ENAB | RDMAC_MODE_FIFOOREAD_ENAB | RDMAC_MODE_LNGREAD_ENAB); if (tg3_asic_rev(tp) == ASIC_REV_5717) rdmac_mode |= RDMAC_MODE_MULT_DMA_RD_DIS; if (tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) rdmac_mode |= RDMAC_MODE_BD_SBD_CRPT_ENAB | RDMAC_MODE_MBUF_RBD_CRPT_ENAB | RDMAC_MODE_MBUF_SBD_CRPT_ENAB; if (tg3_asic_rev(tp) == ASIC_REV_5705 && tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) { if (tg3_flag(tp, TSO_CAPABLE) && tg3_asic_rev(tp) == ASIC_REV_5705) { rdmac_mode |= RDMAC_MODE_FIFO_SIZE_128; } else if (!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH) && !tg3_flag(tp, IS_5788)) { rdmac_mode |= RDMAC_MODE_FIFO_LONG_BURST; } } if (tg3_flag(tp, PCI_EXPRESS)) rdmac_mode |= RDMAC_MODE_FIFO_LONG_BURST; if (tg3_asic_rev(tp) == ASIC_REV_57766) { tp->dma_limit = 0; if (tp->dev->mtu <= ETH_DATA_LEN) { rdmac_mode |= RDMAC_MODE_JMB_2K_MMRR; tp->dma_limit = TG3_TX_BD_DMA_MAX_2K; } } if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) rdmac_mode |= RDMAC_MODE_IPV4_LSO_EN; if (tg3_flag(tp, 57765_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) rdmac_mode |= RDMAC_MODE_IPV6_LSO_EN; if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) rdmac_mode |= tr32(RDMAC_MODE) & RDMAC_MODE_H2BNC_VLAN_DET; if (tg3_asic_rev(tp) == ASIC_REV_5761 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_PLUS)) { u32 tgtreg; if (tg3_asic_rev(tp) == ASIC_REV_5762) tgtreg = TG3_RDMA_RSRVCTRL_REG2; else tgtreg = TG3_RDMA_RSRVCTRL_REG; val = tr32(tgtreg); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || tg3_asic_rev(tp) == ASIC_REV_5762) { val &= ~(TG3_RDMA_RSRVCTRL_TXMRGN_MASK | TG3_RDMA_RSRVCTRL_FIFO_LWM_MASK | TG3_RDMA_RSRVCTRL_FIFO_HWM_MASK); val |= TG3_RDMA_RSRVCTRL_TXMRGN_320B | TG3_RDMA_RSRVCTRL_FIFO_LWM_1_5K | TG3_RDMA_RSRVCTRL_FIFO_HWM_1_5K; } tw32(tgtreg, val | TG3_RDMA_RSRVCTRL_FIFO_OFLW_FIX); } if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) { u32 tgtreg; if (tg3_asic_rev(tp) == ASIC_REV_5762) tgtreg = TG3_LSO_RD_DMA_CRPTEN_CTRL2; else tgtreg = TG3_LSO_RD_DMA_CRPTEN_CTRL; val = tr32(tgtreg); tw32(tgtreg, val | TG3_LSO_RD_DMA_CRPTEN_CTRL_BLEN_BD_4K | TG3_LSO_RD_DMA_CRPTEN_CTRL_BLEN_LSO_4K); } /* Receive/send statistics. */ if (tg3_flag(tp, 5750_PLUS)) { val = tr32(RCVLPC_STATS_ENABLE); val &= ~RCVLPC_STATSENAB_DACK_FIX; tw32(RCVLPC_STATS_ENABLE, val); } else if ((rdmac_mode & RDMAC_MODE_FIFO_SIZE_128) && tg3_flag(tp, TSO_CAPABLE)) { val = tr32(RCVLPC_STATS_ENABLE); val &= ~RCVLPC_STATSENAB_LNGBRST_RFIX; tw32(RCVLPC_STATS_ENABLE, val); } else { tw32(RCVLPC_STATS_ENABLE, 0xffffff); } tw32(RCVLPC_STATSCTRL, RCVLPC_STATSCTRL_ENABLE); tw32(SNDDATAI_STATSENAB, 0xffffff); tw32(SNDDATAI_STATSCTRL, (SNDDATAI_SCTRL_ENABLE | SNDDATAI_SCTRL_FASTUPD)); /* Setup host coalescing engine. */ tw32(HOSTCC_MODE, 0); for (i = 0; i < 2000; i++) { if (!(tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE)) break; udelay(10); } __tg3_set_coalesce(tp, &tp->coal); if (!tg3_flag(tp, 5705_PLUS)) { /* Status/statistics block address. See tg3_timer, * the tg3_periodic_fetch_stats call there, and * tg3_get_stats to see how this works for 5705/5750 chips. */ tw32(HOSTCC_STATS_BLK_HOST_ADDR + TG3_64BIT_REG_HIGH, ((u64) tp->stats_mapping >> 32)); tw32(HOSTCC_STATS_BLK_HOST_ADDR + TG3_64BIT_REG_LOW, ((u64) tp->stats_mapping & 0xffffffff)); tw32(HOSTCC_STATS_BLK_NIC_ADDR, NIC_SRAM_STATS_BLK); tw32(HOSTCC_STATUS_BLK_NIC_ADDR, NIC_SRAM_STATUS_BLK); /* Clear statistics and status block memory areas */ for (i = NIC_SRAM_STATS_BLK; i < NIC_SRAM_STATUS_BLK + TG3_HW_STATUS_SIZE; i += sizeof(u32)) { tg3_write_mem(tp, i, 0); udelay(40); } } tw32(HOSTCC_MODE, HOSTCC_MODE_ENABLE | tp->coalesce_mode); tw32(RCVCC_MODE, RCVCC_MODE_ENABLE | RCVCC_MODE_ATTN_ENABLE); tw32(RCVLPC_MODE, RCVLPC_MODE_ENABLE); if (!tg3_flag(tp, 5705_PLUS)) tw32(RCVLSC_MODE, RCVLSC_MODE_ENABLE | RCVLSC_MODE_ATTN_ENABLE); if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) { tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT; /* reset to prevent losing 1st rx packet intermittently */ tw32_f(MAC_RX_MODE, RX_MODE_RESET); udelay(10); } tp->mac_mode |= MAC_MODE_TXSTAT_ENABLE | MAC_MODE_RXSTAT_ENABLE | MAC_MODE_TDE_ENABLE | MAC_MODE_RDE_ENABLE | MAC_MODE_FHDE_ENABLE; if (tg3_flag(tp, ENABLE_APE)) tp->mac_mode |= MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN; if (!tg3_flag(tp, 5705_PLUS) && !(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) && tg3_asic_rev(tp) != ASIC_REV_5700) tp->mac_mode |= MAC_MODE_LINK_POLARITY; tw32_f(MAC_MODE, tp->mac_mode | MAC_MODE_RXSTAT_CLEAR | MAC_MODE_TXSTAT_CLEAR); udelay(40); /* tp->grc_local_ctrl is partially set up during tg3_get_invariants(). * If TG3_FLAG_IS_NIC is zero, we should read the * register to preserve the GPIO settings for LOMs. The GPIOs, * whether used as inputs or outputs, are set by boot code after * reset. */ if (!tg3_flag(tp, IS_NIC)) { u32 gpio_mask; gpio_mask = GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OE1 | GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT0 | GRC_LCLCTRL_GPIO_OUTPUT1 | GRC_LCLCTRL_GPIO_OUTPUT2; if (tg3_asic_rev(tp) == ASIC_REV_5752) gpio_mask |= GRC_LCLCTRL_GPIO_OE3 | GRC_LCLCTRL_GPIO_OUTPUT3; if (tg3_asic_rev(tp) == ASIC_REV_5755) gpio_mask |= GRC_LCLCTRL_GPIO_UART_SEL; tp->grc_local_ctrl &= ~gpio_mask; tp->grc_local_ctrl |= tr32(GRC_LOCAL_CTRL) & gpio_mask; /* GPIO1 must be driven high for eeprom write protect */ if (tg3_flag(tp, EEPROM_WRITE_PROT)) tp->grc_local_ctrl |= (GRC_LCLCTRL_GPIO_OE1 | GRC_LCLCTRL_GPIO_OUTPUT1); } tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl); udelay(100); if (tg3_flag(tp, USING_MSIX)) { val = tr32(MSGINT_MODE); val |= MSGINT_MODE_ENABLE; if (tp->irq_cnt > 1) val |= MSGINT_MODE_MULTIVEC_EN; if (!tg3_flag(tp, 1SHOT_MSI)) val |= MSGINT_MODE_ONE_SHOT_DISABLE; tw32(MSGINT_MODE, val); } if (!tg3_flag(tp, 5705_PLUS)) { tw32_f(DMAC_MODE, DMAC_MODE_ENABLE); udelay(40); } val = (WDMAC_MODE_ENABLE | WDMAC_MODE_TGTABORT_ENAB | WDMAC_MODE_MSTABORT_ENAB | WDMAC_MODE_PARITYERR_ENAB | WDMAC_MODE_ADDROFLOW_ENAB | WDMAC_MODE_FIFOOFLOW_ENAB | WDMAC_MODE_FIFOURUN_ENAB | WDMAC_MODE_FIFOOREAD_ENAB | WDMAC_MODE_LNGREAD_ENAB); if (tg3_asic_rev(tp) == ASIC_REV_5705 && tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) { if (tg3_flag(tp, TSO_CAPABLE) && (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A1 || tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A2)) { /* nothing */ } else if (!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH) && !tg3_flag(tp, IS_5788)) { val |= WDMAC_MODE_RX_ACCEL; } } /* Enable host coalescing bug fix */ if (tg3_flag(tp, 5755_PLUS)) val |= WDMAC_MODE_STATUS_TAG_FIX; if (tg3_asic_rev(tp) == ASIC_REV_5785) val |= WDMAC_MODE_BURST_ALL_DATA; tw32_f(WDMAC_MODE, val); udelay(40); if (tg3_flag(tp, PCIX_MODE)) { u16 pcix_cmd; pci_read_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD, &pcix_cmd); if (tg3_asic_rev(tp) == ASIC_REV_5703) { pcix_cmd &= ~PCI_X_CMD_MAX_READ; pcix_cmd |= PCI_X_CMD_READ_2K; } else if (tg3_asic_rev(tp) == ASIC_REV_5704) { pcix_cmd &= ~(PCI_X_CMD_MAX_SPLIT | PCI_X_CMD_MAX_READ); pcix_cmd |= PCI_X_CMD_READ_2K; } pci_write_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD, pcix_cmd); } tw32_f(RDMAC_MODE, rdmac_mode); udelay(40); if (tg3_asic_rev(tp) == ASIC_REV_5719) { for (i = 0; i < TG3_NUM_RDMA_CHANNELS; i++) { if (tr32(TG3_RDMA_LENGTH + (i << 2)) > TG3_MAX_MTU(tp)) break; } if (i < TG3_NUM_RDMA_CHANNELS) { val = tr32(TG3_LSO_RD_DMA_CRPTEN_CTRL); val |= TG3_LSO_RD_DMA_TX_LENGTH_WA; tw32(TG3_LSO_RD_DMA_CRPTEN_CTRL, val); tg3_flag_set(tp, 5719_RDMA_BUG); } } tw32(RCVDCC_MODE, RCVDCC_MODE_ENABLE | RCVDCC_MODE_ATTN_ENABLE); if (!tg3_flag(tp, 5705_PLUS)) tw32(MBFREE_MODE, MBFREE_MODE_ENABLE); if (tg3_asic_rev(tp) == ASIC_REV_5761) tw32(SNDDATAC_MODE, SNDDATAC_MODE_ENABLE | SNDDATAC_MODE_CDELAY); else tw32(SNDDATAC_MODE, SNDDATAC_MODE_ENABLE); tw32(SNDBDC_MODE, SNDBDC_MODE_ENABLE | SNDBDC_MODE_ATTN_ENABLE); tw32(RCVBDI_MODE, RCVBDI_MODE_ENABLE | RCVBDI_MODE_RCB_ATTN_ENAB); val = RCVDBDI_MODE_ENABLE | RCVDBDI_MODE_INV_RING_SZ; if (tg3_flag(tp, LRG_PROD_RING_CAP)) val |= RCVDBDI_MODE_LRG_RING_SZ; tw32(RCVDBDI_MODE, val); tw32(SNDDATAI_MODE, SNDDATAI_MODE_ENABLE); if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) tw32(SNDDATAI_MODE, SNDDATAI_MODE_ENABLE | 0x8); val = SNDBDI_MODE_ENABLE | SNDBDI_MODE_ATTN_ENABLE; if (tg3_flag(tp, ENABLE_TSS)) val |= SNDBDI_MODE_MULTI_TXQ_EN; tw32(SNDBDI_MODE, val); tw32(SNDBDS_MODE, SNDBDS_MODE_ENABLE | SNDBDS_MODE_ATTN_ENABLE); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) { err = tg3_load_5701_a0_firmware_fix(tp); if (err) return err; } if (tg3_flag(tp, TSO_CAPABLE)) { err = tg3_load_tso_firmware(tp); if (err) return err; } tp->tx_mode = TX_MODE_ENABLE; if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) tp->tx_mode |= TX_MODE_MBUF_LOCKUP_FIX; if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) { val = TX_MODE_JMB_FRM_LEN | TX_MODE_CNT_DN_MODE; tp->tx_mode &= ~val; tp->tx_mode |= tr32(MAC_TX_MODE) & val; } tw32_f(MAC_TX_MODE, tp->tx_mode); udelay(100); if (tg3_flag(tp, ENABLE_RSS)) { tg3_rss_write_indir_tbl(tp); /* Setup the "secret" hash key. */ tw32(MAC_RSS_HASH_KEY_0, 0x5f865437); tw32(MAC_RSS_HASH_KEY_1, 0xe4ac62cc); tw32(MAC_RSS_HASH_KEY_2, 0x50103a45); tw32(MAC_RSS_HASH_KEY_3, 0x36621985); tw32(MAC_RSS_HASH_KEY_4, 0xbf14c0e8); tw32(MAC_RSS_HASH_KEY_5, 0x1bc27a1e); tw32(MAC_RSS_HASH_KEY_6, 0x84f4b556); tw32(MAC_RSS_HASH_KEY_7, 0x094ea6fe); tw32(MAC_RSS_HASH_KEY_8, 0x7dda01e7); tw32(MAC_RSS_HASH_KEY_9, 0xc04d7481); } tp->rx_mode = RX_MODE_ENABLE; if (tg3_flag(tp, 5755_PLUS)) tp->rx_mode |= RX_MODE_IPV6_CSUM_ENABLE; if (tg3_flag(tp, ENABLE_RSS)) tp->rx_mode |= RX_MODE_RSS_ENABLE | RX_MODE_RSS_ITBL_HASH_BITS_7 | RX_MODE_RSS_IPV6_HASH_EN | RX_MODE_RSS_TCP_IPV6_HASH_EN | RX_MODE_RSS_IPV4_HASH_EN | RX_MODE_RSS_TCP_IPV4_HASH_EN; tw32_f(MAC_RX_MODE, tp->rx_mode); udelay(10); tw32(MAC_LED_CTRL, tp->led_ctrl); tw32(MAC_MI_STAT, MAC_MI_STAT_LNKSTAT_ATTN_ENAB); if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) { tw32_f(MAC_RX_MODE, RX_MODE_RESET); udelay(10); } tw32_f(MAC_RX_MODE, tp->rx_mode); udelay(10); if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) { if ((tg3_asic_rev(tp) == ASIC_REV_5704) && !(tp->phy_flags & TG3_PHYFLG_SERDES_PREEMPHASIS)) { /* Set drive transmission level to 1.2V */ /* only if the signal pre-emphasis bit is not set */ val = tr32(MAC_SERDES_CFG); val &= 0xfffff000; val |= 0x880; tw32(MAC_SERDES_CFG, val); } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A1) tw32(MAC_SERDES_CFG, 0x616000); } /* Prevent chip from dropping frames when flow control * is enabled. */ if (tg3_flag(tp, 57765_CLASS)) val = 1; else val = 2; tw32_f(MAC_LOW_WMARK_MAX_RX_FRAME, val); if (tg3_asic_rev(tp) == ASIC_REV_5704 && (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) { /* Use hardware link auto-negotiation */ tg3_flag_set(tp, HW_AUTONEG); } if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) && tg3_asic_rev(tp) == ASIC_REV_5714) { u32 tmp; tmp = tr32(SERDES_RX_CTRL); tw32(SERDES_RX_CTRL, tmp | SERDES_RX_SIG_DETECT); tp->grc_local_ctrl &= ~GRC_LCLCTRL_USE_EXT_SIG_DETECT; tp->grc_local_ctrl |= GRC_LCLCTRL_USE_SIG_DETECT; tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl); } if (!tg3_flag(tp, USE_PHYLIB)) { if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) tp->phy_flags &= ~TG3_PHYFLG_IS_LOW_POWER; err = tg3_setup_phy(tp, 0); if (err) return err; if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) && !(tp->phy_flags & TG3_PHYFLG_IS_FET)) { u32 tmp; /* Clear CRC stats. */ if (!tg3_readphy(tp, MII_TG3_TEST1, &tmp)) { tg3_writephy(tp, MII_TG3_TEST1, tmp | MII_TG3_TEST1_CRC_EN); tg3_readphy(tp, MII_TG3_RXR_COUNTERS, &tmp); } } } __tg3_set_rx_mode(tp->dev); /* Initialize receive rules. */ tw32(MAC_RCV_RULE_0, 0xc2000000 & RCV_RULE_DISABLE_MASK); tw32(MAC_RCV_VALUE_0, 0xffffffff & RCV_RULE_DISABLE_MASK); tw32(MAC_RCV_RULE_1, 0x86000004 & RCV_RULE_DISABLE_MASK); tw32(MAC_RCV_VALUE_1, 0xffffffff & RCV_RULE_DISABLE_MASK); if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS)) limit = 8; else limit = 16; if (tg3_flag(tp, ENABLE_ASF)) limit -= 4; switch (limit) { case 16: tw32(MAC_RCV_RULE_15, 0); tw32(MAC_RCV_VALUE_15, 0); case 15: tw32(MAC_RCV_RULE_14, 0); tw32(MAC_RCV_VALUE_14, 0); case 14: tw32(MAC_RCV_RULE_13, 0); tw32(MAC_RCV_VALUE_13, 0); case 13: tw32(MAC_RCV_RULE_12, 0); tw32(MAC_RCV_VALUE_12, 0); case 12: tw32(MAC_RCV_RULE_11, 0); tw32(MAC_RCV_VALUE_11, 0); case 11: tw32(MAC_RCV_RULE_10, 0); tw32(MAC_RCV_VALUE_10, 0); case 10: tw32(MAC_RCV_RULE_9, 0); tw32(MAC_RCV_VALUE_9, 0); case 9: tw32(MAC_RCV_RULE_8, 0); tw32(MAC_RCV_VALUE_8, 0); case 8: tw32(MAC_RCV_RULE_7, 0); tw32(MAC_RCV_VALUE_7, 0); case 7: tw32(MAC_RCV_RULE_6, 0); tw32(MAC_RCV_VALUE_6, 0); case 6: tw32(MAC_RCV_RULE_5, 0); tw32(MAC_RCV_VALUE_5, 0); case 5: tw32(MAC_RCV_RULE_4, 0); tw32(MAC_RCV_VALUE_4, 0); case 4: /* tw32(MAC_RCV_RULE_3, 0); tw32(MAC_RCV_VALUE_3, 0); */ case 3: /* tw32(MAC_RCV_RULE_2, 0); tw32(MAC_RCV_VALUE_2, 0); */ case 2: case 1: default: break; } if (tg3_flag(tp, ENABLE_APE)) /* Write our heartbeat update interval to APE. */ tg3_ape_write32(tp, TG3_APE_HOST_HEARTBEAT_INT_MS, APE_HOST_HEARTBEAT_INT_DISABLE); tg3_write_sig_post_reset(tp, RESET_KIND_INIT); return 0; } /* Called at device open time to get the chip ready for * packet processing. Invoked with tp->lock held. */ static int tg3_init_hw(struct tg3 *tp, int reset_phy) { tg3_switch_clocks(tp); tw32(TG3PCI_MEM_WIN_BASE_ADDR, 0); return tg3_reset_hw(tp, reset_phy); } static void tg3_sd_scan_scratchpad(struct tg3 *tp, struct tg3_ocir *ocir) { int i; for (i = 0; i < TG3_SD_NUM_RECS; i++, ocir++) { u32 off = i * TG3_OCIR_LEN, len = TG3_OCIR_LEN; tg3_ape_scratchpad_read(tp, (u32 *) ocir, off, len); off += len; if (ocir->signature != TG3_OCIR_SIG_MAGIC || !(ocir->version_flags & TG3_OCIR_FLAG_ACTIVE)) memset(ocir, 0, TG3_OCIR_LEN); } } /* sysfs attributes for hwmon */ static ssize_t tg3_show_temp(struct device *dev, struct device_attribute *devattr, char *buf) { struct pci_dev *pdev = to_pci_dev(dev); struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); u32 temperature; spin_lock_bh(&tp->lock); tg3_ape_scratchpad_read(tp, &temperature, attr->index, sizeof(temperature)); spin_unlock_bh(&tp->lock); return sprintf(buf, "%u\n", temperature); } static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, tg3_show_temp, NULL, TG3_TEMP_SENSOR_OFFSET); static SENSOR_DEVICE_ATTR(temp1_crit, S_IRUGO, tg3_show_temp, NULL, TG3_TEMP_CAUTION_OFFSET); static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO, tg3_show_temp, NULL, TG3_TEMP_MAX_OFFSET); static struct attribute *tg3_attributes[] = { &sensor_dev_attr_temp1_input.dev_attr.attr, &sensor_dev_attr_temp1_crit.dev_attr.attr, &sensor_dev_attr_temp1_max.dev_attr.attr, NULL }; static const struct attribute_group tg3_group = { .attrs = tg3_attributes, }; static void tg3_hwmon_close(struct tg3 *tp) { if (tp->hwmon_dev) { hwmon_device_unregister(tp->hwmon_dev); tp->hwmon_dev = NULL; sysfs_remove_group(&tp->pdev->dev.kobj, &tg3_group); } } static void tg3_hwmon_open(struct tg3 *tp) { int i, err; u32 size = 0; struct pci_dev *pdev = tp->pdev; struct tg3_ocir ocirs[TG3_SD_NUM_RECS]; tg3_sd_scan_scratchpad(tp, ocirs); for (i = 0; i < TG3_SD_NUM_RECS; i++) { if (!ocirs[i].src_data_length) continue; size += ocirs[i].src_hdr_length; size += ocirs[i].src_data_length; } if (!size) return; /* Register hwmon sysfs hooks */ err = sysfs_create_group(&pdev->dev.kobj, &tg3_group); if (err) { dev_err(&pdev->dev, "Cannot create sysfs group, aborting\n"); return; } tp->hwmon_dev = hwmon_device_register(&pdev->dev); if (IS_ERR(tp->hwmon_dev)) { tp->hwmon_dev = NULL; dev_err(&pdev->dev, "Cannot register hwmon device, aborting\n"); sysfs_remove_group(&pdev->dev.kobj, &tg3_group); } } #define TG3_STAT_ADD32(PSTAT, REG) \ do { u32 __val = tr32(REG); \ (PSTAT)->low += __val; \ if ((PSTAT)->low < __val) \ (PSTAT)->high += 1; \ } while (0) static void tg3_periodic_fetch_stats(struct tg3 *tp) { struct tg3_hw_stats *sp = tp->hw_stats; if (!tp->link_up) return; TG3_STAT_ADD32(&sp->tx_octets, MAC_TX_STATS_OCTETS); TG3_STAT_ADD32(&sp->tx_collisions, MAC_TX_STATS_COLLISIONS); TG3_STAT_ADD32(&sp->tx_xon_sent, MAC_TX_STATS_XON_SENT); TG3_STAT_ADD32(&sp->tx_xoff_sent, MAC_TX_STATS_XOFF_SENT); TG3_STAT_ADD32(&sp->tx_mac_errors, MAC_TX_STATS_MAC_ERRORS); TG3_STAT_ADD32(&sp->tx_single_collisions, MAC_TX_STATS_SINGLE_COLLISIONS); TG3_STAT_ADD32(&sp->tx_mult_collisions, MAC_TX_STATS_MULT_COLLISIONS); TG3_STAT_ADD32(&sp->tx_deferred, MAC_TX_STATS_DEFERRED); TG3_STAT_ADD32(&sp->tx_excessive_collisions, MAC_TX_STATS_EXCESSIVE_COL); TG3_STAT_ADD32(&sp->tx_late_collisions, MAC_TX_STATS_LATE_COL); TG3_STAT_ADD32(&sp->tx_ucast_packets, MAC_TX_STATS_UCAST); TG3_STAT_ADD32(&sp->tx_mcast_packets, MAC_TX_STATS_MCAST); TG3_STAT_ADD32(&sp->tx_bcast_packets, MAC_TX_STATS_BCAST); if (unlikely(tg3_flag(tp, 5719_RDMA_BUG) && (sp->tx_ucast_packets.low + sp->tx_mcast_packets.low + sp->tx_bcast_packets.low) > TG3_NUM_RDMA_CHANNELS)) { u32 val; val = tr32(TG3_LSO_RD_DMA_CRPTEN_CTRL); val &= ~TG3_LSO_RD_DMA_TX_LENGTH_WA; tw32(TG3_LSO_RD_DMA_CRPTEN_CTRL, val); tg3_flag_clear(tp, 5719_RDMA_BUG); } TG3_STAT_ADD32(&sp->rx_octets, MAC_RX_STATS_OCTETS); TG3_STAT_ADD32(&sp->rx_fragments, MAC_RX_STATS_FRAGMENTS); TG3_STAT_ADD32(&sp->rx_ucast_packets, MAC_RX_STATS_UCAST); TG3_STAT_ADD32(&sp->rx_mcast_packets, MAC_RX_STATS_MCAST); TG3_STAT_ADD32(&sp->rx_bcast_packets, MAC_RX_STATS_BCAST); TG3_STAT_ADD32(&sp->rx_fcs_errors, MAC_RX_STATS_FCS_ERRORS); TG3_STAT_ADD32(&sp->rx_align_errors, MAC_RX_STATS_ALIGN_ERRORS); TG3_STAT_ADD32(&sp->rx_xon_pause_rcvd, MAC_RX_STATS_XON_PAUSE_RECVD); TG3_STAT_ADD32(&sp->rx_xoff_pause_rcvd, MAC_RX_STATS_XOFF_PAUSE_RECVD); TG3_STAT_ADD32(&sp->rx_mac_ctrl_rcvd, MAC_RX_STATS_MAC_CTRL_RECVD); TG3_STAT_ADD32(&sp->rx_xoff_entered, MAC_RX_STATS_XOFF_ENTERED); TG3_STAT_ADD32(&sp->rx_frame_too_long_errors, MAC_RX_STATS_FRAME_TOO_LONG); TG3_STAT_ADD32(&sp->rx_jabbers, MAC_RX_STATS_JABBERS); TG3_STAT_ADD32(&sp->rx_undersize_packets, MAC_RX_STATS_UNDERSIZE); TG3_STAT_ADD32(&sp->rxbds_empty, RCVLPC_NO_RCV_BD_CNT); if (tg3_asic_rev(tp) != ASIC_REV_5717 && tg3_chip_rev_id(tp) != CHIPREV_ID_5719_A0 && tg3_chip_rev_id(tp) != CHIPREV_ID_5720_A0) { TG3_STAT_ADD32(&sp->rx_discards, RCVLPC_IN_DISCARDS_CNT); } else { u32 val = tr32(HOSTCC_FLOW_ATTN); val = (val & HOSTCC_FLOW_ATTN_MBUF_LWM) ? 1 : 0; if (val) { tw32(HOSTCC_FLOW_ATTN, HOSTCC_FLOW_ATTN_MBUF_LWM); sp->rx_discards.low += val; if (sp->rx_discards.low < val) sp->rx_discards.high += 1; } sp->mbuf_lwm_thresh_hit = sp->rx_discards; } TG3_STAT_ADD32(&sp->rx_errors, RCVLPC_IN_ERRORS_CNT); } static void tg3_chk_missed_msi(struct tg3 *tp) { u32 i; for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; if (tg3_has_work(tnapi)) { if (tnapi->last_rx_cons == tnapi->rx_rcb_ptr && tnapi->last_tx_cons == tnapi->tx_cons) { if (tnapi->chk_msi_cnt < 1) { tnapi->chk_msi_cnt++; return; } tg3_msi(0, tnapi); } } tnapi->chk_msi_cnt = 0; tnapi->last_rx_cons = tnapi->rx_rcb_ptr; tnapi->last_tx_cons = tnapi->tx_cons; } } static void tg3_timer(unsigned long __opaque) { struct tg3 *tp = (struct tg3 *) __opaque; if (tp->irq_sync || tg3_flag(tp, RESET_TASK_PENDING)) goto restart_timer; spin_lock(&tp->lock); if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_flag(tp, 57765_CLASS)) tg3_chk_missed_msi(tp); if (tg3_flag(tp, FLUSH_POSTED_WRITES)) { /* BCM4785: Flush posted writes from GbE to host memory. */ tr32(HOSTCC_MODE); } if (!tg3_flag(tp, TAGGED_STATUS)) { /* All of this garbage is because when using non-tagged * IRQ status the mailbox/status_block protocol the chip * uses with the cpu is race prone. */ if (tp->napi[0].hw_status->status & SD_STATUS_UPDATED) { tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl | GRC_LCLCTRL_SETINT); } else { tw32(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | HOSTCC_MODE_NOW); } if (!(tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) { spin_unlock(&tp->lock); tg3_reset_task_schedule(tp); goto restart_timer; } } /* This part only runs once per second. */ if (!--tp->timer_counter) { if (tg3_flag(tp, 5705_PLUS)) tg3_periodic_fetch_stats(tp); if (tp->setlpicnt && !--tp->setlpicnt) tg3_phy_eee_enable(tp); if (tg3_flag(tp, USE_LINKCHG_REG)) { u32 mac_stat; int phy_event; mac_stat = tr32(MAC_STATUS); phy_event = 0; if (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) { if (mac_stat & MAC_STATUS_MI_INTERRUPT) phy_event = 1; } else if (mac_stat & MAC_STATUS_LNKSTATE_CHANGED) phy_event = 1; if (phy_event) tg3_setup_phy(tp, 0); } else if (tg3_flag(tp, POLL_SERDES)) { u32 mac_stat = tr32(MAC_STATUS); int need_setup = 0; if (tp->link_up && (mac_stat & MAC_STATUS_LNKSTATE_CHANGED)) { need_setup = 1; } if (!tp->link_up && (mac_stat & (MAC_STATUS_PCS_SYNCED | MAC_STATUS_SIGNAL_DET))) { need_setup = 1; } if (need_setup) { if (!tp->serdes_counter) { tw32_f(MAC_MODE, (tp->mac_mode & ~MAC_MODE_PORT_MODE_MASK)); udelay(40); tw32_f(MAC_MODE, tp->mac_mode); udelay(40); } tg3_setup_phy(tp, 0); } } else if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) && tg3_flag(tp, 5780_CLASS)) { tg3_serdes_parallel_detect(tp); } tp->timer_counter = tp->timer_multiplier; } /* Heartbeat is only sent once every 2 seconds. * * The heartbeat is to tell the ASF firmware that the host * driver is still alive. In the event that the OS crashes, * ASF needs to reset the hardware to free up the FIFO space * that may be filled with rx packets destined for the host. * If the FIFO is full, ASF will no longer function properly. * * Unintended resets have been reported on real time kernels * where the timer doesn't run on time. Netpoll will also have * same problem. * * The new FWCMD_NICDRV_ALIVE3 command tells the ASF firmware * to check the ring condition when the heartbeat is expiring * before doing the reset. This will prevent most unintended * resets. */ if (!--tp->asf_counter) { if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) { tg3_wait_for_event_ack(tp); tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_ALIVE3); tg3_write_mem(tp, NIC_SRAM_FW_CMD_LEN_MBOX, 4); tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX, TG3_FW_UPDATE_TIMEOUT_SEC); tg3_generate_fw_event(tp); } tp->asf_counter = tp->asf_multiplier; } spin_unlock(&tp->lock); restart_timer: tp->timer.expires = jiffies + tp->timer_offset; add_timer(&tp->timer); } static void tg3_timer_init(struct tg3 *tp) { if (tg3_flag(tp, TAGGED_STATUS) && tg3_asic_rev(tp) != ASIC_REV_5717 && !tg3_flag(tp, 57765_CLASS)) tp->timer_offset = HZ; else tp->timer_offset = HZ / 10; BUG_ON(tp->timer_offset > HZ); tp->timer_multiplier = (HZ / tp->timer_offset); tp->asf_multiplier = (HZ / tp->timer_offset) * TG3_FW_UPDATE_FREQ_SEC; init_timer(&tp->timer); tp->timer.data = (unsigned long) tp; tp->timer.function = tg3_timer; } static void tg3_timer_start(struct tg3 *tp) { tp->asf_counter = tp->asf_multiplier; tp->timer_counter = tp->timer_multiplier; tp->timer.expires = jiffies + tp->timer_offset; add_timer(&tp->timer); } static void tg3_timer_stop(struct tg3 *tp) { del_timer_sync(&tp->timer); } /* Restart hardware after configuration changes, self-test, etc. * Invoked with tp->lock held. */ static int tg3_restart_hw(struct tg3 *tp, int reset_phy) __releases(tp->lock) __acquires(tp->lock) { int err; err = tg3_init_hw(tp, reset_phy); if (err) { netdev_err(tp->dev, "Failed to re-initialize device, aborting\n"); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_full_unlock(tp); tg3_timer_stop(tp); tp->irq_sync = 0; tg3_napi_enable(tp); dev_close(tp->dev); tg3_full_lock(tp, 0); } return err; } static void tg3_reset_task(struct work_struct *work) { struct tg3 *tp = container_of(work, struct tg3, reset_task); int err; tg3_full_lock(tp, 0); if (!netif_running(tp->dev)) { tg3_flag_clear(tp, RESET_TASK_PENDING); tg3_full_unlock(tp); return; } tg3_full_unlock(tp); tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_full_lock(tp, 1); if (tg3_flag(tp, TX_RECOVERY_PENDING)) { tp->write32_tx_mbox = tg3_write32_tx_mbox; tp->write32_rx_mbox = tg3_write_flush_reg32; tg3_flag_set(tp, MBOX_WRITE_REORDER); tg3_flag_clear(tp, TX_RECOVERY_PENDING); } tg3_halt(tp, RESET_KIND_SHUTDOWN, 0); err = tg3_init_hw(tp, 1); if (err) goto out; tg3_netif_start(tp); out: tg3_full_unlock(tp); if (!err) tg3_phy_start(tp); tg3_flag_clear(tp, RESET_TASK_PENDING); } static int tg3_request_irq(struct tg3 *tp, int irq_num) { irq_handler_t fn; unsigned long flags; char *name; struct tg3_napi *tnapi = &tp->napi[irq_num]; if (tp->irq_cnt == 1) name = tp->dev->name; else { name = &tnapi->irq_lbl[0]; snprintf(name, IFNAMSIZ, "%s-%d", tp->dev->name, irq_num); name[IFNAMSIZ-1] = 0; } if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) { fn = tg3_msi; if (tg3_flag(tp, 1SHOT_MSI)) fn = tg3_msi_1shot; flags = 0; } else { fn = tg3_interrupt; if (tg3_flag(tp, TAGGED_STATUS)) fn = tg3_interrupt_tagged; flags = IRQF_SHARED; } return request_irq(tnapi->irq_vec, fn, flags, name, tnapi); } static int tg3_test_interrupt(struct tg3 *tp) { struct tg3_napi *tnapi = &tp->napi[0]; struct net_device *dev = tp->dev; int err, i, intr_ok = 0; u32 val; if (!netif_running(dev)) return -ENODEV; tg3_disable_ints(tp); free_irq(tnapi->irq_vec, tnapi); /* * Turn off MSI one shot mode. Otherwise this test has no * observable way to know whether the interrupt was delivered. */ if (tg3_flag(tp, 57765_PLUS)) { val = tr32(MSGINT_MODE) | MSGINT_MODE_ONE_SHOT_DISABLE; tw32(MSGINT_MODE, val); } err = request_irq(tnapi->irq_vec, tg3_test_isr, IRQF_SHARED, dev->name, tnapi); if (err) return err; tnapi->hw_status->status &= ~SD_STATUS_UPDATED; tg3_enable_ints(tp); tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | tnapi->coal_now); for (i = 0; i < 5; i++) { u32 int_mbox, misc_host_ctrl; int_mbox = tr32_mailbox(tnapi->int_mbox); misc_host_ctrl = tr32(TG3PCI_MISC_HOST_CTRL); if ((int_mbox != 0) || (misc_host_ctrl & MISC_HOST_CTRL_MASK_PCI_INT)) { intr_ok = 1; break; } if (tg3_flag(tp, 57765_PLUS) && tnapi->hw_status->status_tag != tnapi->last_tag) tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24); msleep(10); } tg3_disable_ints(tp); free_irq(tnapi->irq_vec, tnapi); err = tg3_request_irq(tp, 0); if (err) return err; if (intr_ok) { /* Reenable MSI one shot mode. */ if (tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, 1SHOT_MSI)) { val = tr32(MSGINT_MODE) & ~MSGINT_MODE_ONE_SHOT_DISABLE; tw32(MSGINT_MODE, val); } return 0; } return -EIO; } /* Returns 0 if MSI test succeeds or MSI test fails and INTx mode is * successfully restored */ static int tg3_test_msi(struct tg3 *tp) { int err; u16 pci_cmd; if (!tg3_flag(tp, USING_MSI)) return 0; /* Turn off SERR reporting in case MSI terminates with Master * Abort. */ pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd); pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd & ~PCI_COMMAND_SERR); err = tg3_test_interrupt(tp); pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd); if (!err) return 0; /* other failures */ if (err != -EIO) return err; /* MSI test failed, go back to INTx mode */ netdev_warn(tp->dev, "No interrupt was generated using MSI. Switching " "to INTx mode. Please report this failure to the PCI " "maintainer and include system chipset information\n"); free_irq(tp->napi[0].irq_vec, &tp->napi[0]); pci_disable_msi(tp->pdev); tg3_flag_clear(tp, USING_MSI); tp->napi[0].irq_vec = tp->pdev->irq; err = tg3_request_irq(tp, 0); if (err) return err; /* Need to reset the chip because the MSI cycle may have terminated * with Master Abort. */ tg3_full_lock(tp, 1); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); err = tg3_init_hw(tp, 1); tg3_full_unlock(tp); if (err) free_irq(tp->napi[0].irq_vec, &tp->napi[0]); return err; } static int tg3_request_firmware(struct tg3 *tp) { const __be32 *fw_data; if (request_firmware(&tp->fw, tp->fw_needed, &tp->pdev->dev)) { netdev_err(tp->dev, "Failed to load firmware \"%s\"\n", tp->fw_needed); return -ENOENT; } fw_data = (void *)tp->fw->data; /* Firmware blob starts with version numbers, followed by * start address and _full_ length including BSS sections * (which must be longer than the actual data, of course */ tp->fw_len = be32_to_cpu(fw_data[2]); /* includes bss */ if (tp->fw_len < (tp->fw->size - 12)) { netdev_err(tp->dev, "bogus length %d in \"%s\"\n", tp->fw_len, tp->fw_needed); release_firmware(tp->fw); tp->fw = NULL; return -EINVAL; } /* We no longer need firmware; we have it. */ tp->fw_needed = NULL; return 0; } static u32 tg3_irq_count(struct tg3 *tp) { u32 irq_cnt = max(tp->rxq_cnt, tp->txq_cnt); if (irq_cnt > 1) { /* We want as many rx rings enabled as there are cpus. * In multiqueue MSI-X mode, the first MSI-X vector * only deals with link interrupts, etc, so we add * one to the number of vectors we are requesting. */ irq_cnt = min_t(unsigned, irq_cnt + 1, tp->irq_max); } return irq_cnt; } static bool tg3_enable_msix(struct tg3 *tp) { int i, rc; struct msix_entry msix_ent[TG3_IRQ_MAX_VECS]; tp->txq_cnt = tp->txq_req; tp->rxq_cnt = tp->rxq_req; if (!tp->rxq_cnt) tp->rxq_cnt = netif_get_num_default_rss_queues(); if (tp->rxq_cnt > tp->rxq_max) tp->rxq_cnt = tp->rxq_max; /* Disable multiple TX rings by default. Simple round-robin hardware * scheduling of the TX rings can cause starvation of rings with * small packets when other rings have TSO or jumbo packets. */ if (!tp->txq_req) tp->txq_cnt = 1; tp->irq_cnt = tg3_irq_count(tp); for (i = 0; i < tp->irq_max; i++) { msix_ent[i].entry = i; msix_ent[i].vector = 0; } rc = pci_enable_msix(tp->pdev, msix_ent, tp->irq_cnt); if (rc < 0) { return false; } else if (rc != 0) { if (pci_enable_msix(tp->pdev, msix_ent, rc)) return false; netdev_notice(tp->dev, "Requested %d MSI-X vectors, received %d\n", tp->irq_cnt, rc); tp->irq_cnt = rc; tp->rxq_cnt = max(rc - 1, 1); if (tp->txq_cnt) tp->txq_cnt = min(tp->rxq_cnt, tp->txq_max); } for (i = 0; i < tp->irq_max; i++) tp->napi[i].irq_vec = msix_ent[i].vector; if (netif_set_real_num_rx_queues(tp->dev, tp->rxq_cnt)) { pci_disable_msix(tp->pdev); return false; } if (tp->irq_cnt == 1) return true; tg3_flag_set(tp, ENABLE_RSS); if (tp->txq_cnt > 1) tg3_flag_set(tp, ENABLE_TSS); netif_set_real_num_tx_queues(tp->dev, tp->txq_cnt); return true; } static void tg3_ints_init(struct tg3 *tp) { if ((tg3_flag(tp, SUPPORT_MSI) || tg3_flag(tp, SUPPORT_MSIX)) && !tg3_flag(tp, TAGGED_STATUS)) { /* All MSI supporting chips should support tagged * status. Assert that this is the case. */ netdev_warn(tp->dev, "MSI without TAGGED_STATUS? Not using MSI\n"); goto defcfg; } if (tg3_flag(tp, SUPPORT_MSIX) && tg3_enable_msix(tp)) tg3_flag_set(tp, USING_MSIX); else if (tg3_flag(tp, SUPPORT_MSI) && pci_enable_msi(tp->pdev) == 0) tg3_flag_set(tp, USING_MSI); if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) { u32 msi_mode = tr32(MSGINT_MODE); if (tg3_flag(tp, USING_MSIX) && tp->irq_cnt > 1) msi_mode |= MSGINT_MODE_MULTIVEC_EN; if (!tg3_flag(tp, 1SHOT_MSI)) msi_mode |= MSGINT_MODE_ONE_SHOT_DISABLE; tw32(MSGINT_MODE, msi_mode | MSGINT_MODE_ENABLE); } defcfg: if (!tg3_flag(tp, USING_MSIX)) { tp->irq_cnt = 1; tp->napi[0].irq_vec = tp->pdev->irq; } if (tp->irq_cnt == 1) { tp->txq_cnt = 1; tp->rxq_cnt = 1; netif_set_real_num_tx_queues(tp->dev, 1); netif_set_real_num_rx_queues(tp->dev, 1); } } static void tg3_ints_fini(struct tg3 *tp) { if (tg3_flag(tp, USING_MSIX)) pci_disable_msix(tp->pdev); else if (tg3_flag(tp, USING_MSI)) pci_disable_msi(tp->pdev); tg3_flag_clear(tp, USING_MSI); tg3_flag_clear(tp, USING_MSIX); tg3_flag_clear(tp, ENABLE_RSS); tg3_flag_clear(tp, ENABLE_TSS); } static int tg3_start(struct tg3 *tp, bool reset_phy, bool test_irq, bool init) { struct net_device *dev = tp->dev; int i, err; /* * Setup interrupts first so we know how * many NAPI resources to allocate */ tg3_ints_init(tp); tg3_rss_check_indir_tbl(tp); /* The placement of this call is tied * to the setup and use of Host TX descriptors. */ err = tg3_alloc_consistent(tp); if (err) goto err_out1; tg3_napi_init(tp); tg3_napi_enable(tp); for (i = 0; i < tp->irq_cnt; i++) { struct tg3_napi *tnapi = &tp->napi[i]; err = tg3_request_irq(tp, i); if (err) { for (i--; i >= 0; i--) { tnapi = &tp->napi[i]; free_irq(tnapi->irq_vec, tnapi); } goto err_out2; } } tg3_full_lock(tp, 0); err = tg3_init_hw(tp, reset_phy); if (err) { tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_free_rings(tp); } tg3_full_unlock(tp); if (err) goto err_out3; if (test_irq && tg3_flag(tp, USING_MSI)) { err = tg3_test_msi(tp); if (err) { tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_free_rings(tp); tg3_full_unlock(tp); goto err_out2; } if (!tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, USING_MSI)) { u32 val = tr32(PCIE_TRANSACTION_CFG); tw32(PCIE_TRANSACTION_CFG, val | PCIE_TRANS_CFG_1SHOT_MSI); } } tg3_phy_start(tp); tg3_hwmon_open(tp); tg3_full_lock(tp, 0); tg3_timer_start(tp); tg3_flag_set(tp, INIT_COMPLETE); tg3_enable_ints(tp); if (init) tg3_ptp_init(tp); else tg3_ptp_resume(tp); tg3_full_unlock(tp); netif_tx_start_all_queues(dev); /* * Reset loopback feature if it was turned on while the device was down * make sure that it's installed properly now. */ if (dev->features & NETIF_F_LOOPBACK) tg3_set_loopback(dev, dev->features); return 0; err_out3: for (i = tp->irq_cnt - 1; i >= 0; i--) { struct tg3_napi *tnapi = &tp->napi[i]; free_irq(tnapi->irq_vec, tnapi); } err_out2: tg3_napi_disable(tp); tg3_napi_fini(tp); tg3_free_consistent(tp); err_out1: tg3_ints_fini(tp); return err; } static void tg3_stop(struct tg3 *tp) { int i; tg3_reset_task_cancel(tp); tg3_netif_stop(tp); tg3_timer_stop(tp); tg3_hwmon_close(tp); tg3_phy_stop(tp); tg3_full_lock(tp, 1); tg3_disable_ints(tp); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_free_rings(tp); tg3_flag_clear(tp, INIT_COMPLETE); tg3_full_unlock(tp); for (i = tp->irq_cnt - 1; i >= 0; i--) { struct tg3_napi *tnapi = &tp->napi[i]; free_irq(tnapi->irq_vec, tnapi); } tg3_ints_fini(tp); tg3_napi_fini(tp); tg3_free_consistent(tp); } static int tg3_open(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); int err; if (tp->fw_needed) { err = tg3_request_firmware(tp); if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) { if (err) return err; } else if (err) { netdev_warn(tp->dev, "TSO capability disabled\n"); tg3_flag_clear(tp, TSO_CAPABLE); } else if (!tg3_flag(tp, TSO_CAPABLE)) { netdev_notice(tp->dev, "TSO capability restored\n"); tg3_flag_set(tp, TSO_CAPABLE); } } tg3_carrier_off(tp); err = tg3_power_up(tp); if (err) return err; tg3_full_lock(tp, 0); tg3_disable_ints(tp); tg3_flag_clear(tp, INIT_COMPLETE); tg3_full_unlock(tp); err = tg3_start(tp, true, true, true); if (err) { tg3_frob_aux_power(tp, false); pci_set_power_state(tp->pdev, PCI_D3hot); } if (tg3_flag(tp, PTP_CAPABLE)) { tp->ptp_clock = ptp_clock_register(&tp->ptp_info, &tp->pdev->dev); if (IS_ERR(tp->ptp_clock)) tp->ptp_clock = NULL; } return err; } static int tg3_close(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); tg3_ptp_fini(tp); tg3_stop(tp); /* Clear stats across close / open calls */ memset(&tp->net_stats_prev, 0, sizeof(tp->net_stats_prev)); memset(&tp->estats_prev, 0, sizeof(tp->estats_prev)); tg3_power_down(tp); tg3_carrier_off(tp); return 0; } static inline u64 get_stat64(tg3_stat64_t *val) { return ((u64)val->high << 32) | ((u64)val->low); } static u64 tg3_calc_crc_errors(struct tg3 *tp) { struct tg3_hw_stats *hw_stats = tp->hw_stats; if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) && (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701)) { u32 val; if (!tg3_readphy(tp, MII_TG3_TEST1, &val)) { tg3_writephy(tp, MII_TG3_TEST1, val | MII_TG3_TEST1_CRC_EN); tg3_readphy(tp, MII_TG3_RXR_COUNTERS, &val); } else val = 0; tp->phy_crc_errors += val; return tp->phy_crc_errors; } return get_stat64(&hw_stats->rx_fcs_errors); } #define ESTAT_ADD(member) \ estats->member = old_estats->member + \ get_stat64(&hw_stats->member) static void tg3_get_estats(struct tg3 *tp, struct tg3_ethtool_stats *estats) { struct tg3_ethtool_stats *old_estats = &tp->estats_prev; struct tg3_hw_stats *hw_stats = tp->hw_stats; ESTAT_ADD(rx_octets); ESTAT_ADD(rx_fragments); ESTAT_ADD(rx_ucast_packets); ESTAT_ADD(rx_mcast_packets); ESTAT_ADD(rx_bcast_packets); ESTAT_ADD(rx_fcs_errors); ESTAT_ADD(rx_align_errors); ESTAT_ADD(rx_xon_pause_rcvd); ESTAT_ADD(rx_xoff_pause_rcvd); ESTAT_ADD(rx_mac_ctrl_rcvd); ESTAT_ADD(rx_xoff_entered); ESTAT_ADD(rx_frame_too_long_errors); ESTAT_ADD(rx_jabbers); ESTAT_ADD(rx_undersize_packets); ESTAT_ADD(rx_in_length_errors); ESTAT_ADD(rx_out_length_errors); ESTAT_ADD(rx_64_or_less_octet_packets); ESTAT_ADD(rx_65_to_127_octet_packets); ESTAT_ADD(rx_128_to_255_octet_packets); ESTAT_ADD(rx_256_to_511_octet_packets); ESTAT_ADD(rx_512_to_1023_octet_packets); ESTAT_ADD(rx_1024_to_1522_octet_packets); ESTAT_ADD(rx_1523_to_2047_octet_packets); ESTAT_ADD(rx_2048_to_4095_octet_packets); ESTAT_ADD(rx_4096_to_8191_octet_packets); ESTAT_ADD(rx_8192_to_9022_octet_packets); ESTAT_ADD(tx_octets); ESTAT_ADD(tx_collisions); ESTAT_ADD(tx_xon_sent); ESTAT_ADD(tx_xoff_sent); ESTAT_ADD(tx_flow_control); ESTAT_ADD(tx_mac_errors); ESTAT_ADD(tx_single_collisions); ESTAT_ADD(tx_mult_collisions); ESTAT_ADD(tx_deferred); ESTAT_ADD(tx_excessive_collisions); ESTAT_ADD(tx_late_collisions); ESTAT_ADD(tx_collide_2times); ESTAT_ADD(tx_collide_3times); ESTAT_ADD(tx_collide_4times); ESTAT_ADD(tx_collide_5times); ESTAT_ADD(tx_collide_6times); ESTAT_ADD(tx_collide_7times); ESTAT_ADD(tx_collide_8times); ESTAT_ADD(tx_collide_9times); ESTAT_ADD(tx_collide_10times); ESTAT_ADD(tx_collide_11times); ESTAT_ADD(tx_collide_12times); ESTAT_ADD(tx_collide_13times); ESTAT_ADD(tx_collide_14times); ESTAT_ADD(tx_collide_15times); ESTAT_ADD(tx_ucast_packets); ESTAT_ADD(tx_mcast_packets); ESTAT_ADD(tx_bcast_packets); ESTAT_ADD(tx_carrier_sense_errors); ESTAT_ADD(tx_discards); ESTAT_ADD(tx_errors); ESTAT_ADD(dma_writeq_full); ESTAT_ADD(dma_write_prioq_full); ESTAT_ADD(rxbds_empty); ESTAT_ADD(rx_discards); ESTAT_ADD(rx_errors); ESTAT_ADD(rx_threshold_hit); ESTAT_ADD(dma_readq_full); ESTAT_ADD(dma_read_prioq_full); ESTAT_ADD(tx_comp_queue_full); ESTAT_ADD(ring_set_send_prod_index); ESTAT_ADD(ring_status_update); ESTAT_ADD(nic_irqs); ESTAT_ADD(nic_avoided_irqs); ESTAT_ADD(nic_tx_threshold_hit); ESTAT_ADD(mbuf_lwm_thresh_hit); } static void tg3_get_nstats(struct tg3 *tp, struct rtnl_link_stats64 *stats) { struct rtnl_link_stats64 *old_stats = &tp->net_stats_prev; struct tg3_hw_stats *hw_stats = tp->hw_stats; stats->rx_packets = old_stats->rx_packets + get_stat64(&hw_stats->rx_ucast_packets) + get_stat64(&hw_stats->rx_mcast_packets) + get_stat64(&hw_stats->rx_bcast_packets); stats->tx_packets = old_stats->tx_packets + get_stat64(&hw_stats->tx_ucast_packets) + get_stat64(&hw_stats->tx_mcast_packets) + get_stat64(&hw_stats->tx_bcast_packets); stats->rx_bytes = old_stats->rx_bytes + get_stat64(&hw_stats->rx_octets); stats->tx_bytes = old_stats->tx_bytes + get_stat64(&hw_stats->tx_octets); stats->rx_errors = old_stats->rx_errors + get_stat64(&hw_stats->rx_errors); stats->tx_errors = old_stats->tx_errors + get_stat64(&hw_stats->tx_errors) + get_stat64(&hw_stats->tx_mac_errors) + get_stat64(&hw_stats->tx_carrier_sense_errors) + get_stat64(&hw_stats->tx_discards); stats->multicast = old_stats->multicast + get_stat64(&hw_stats->rx_mcast_packets); stats->collisions = old_stats->collisions + get_stat64(&hw_stats->tx_collisions); stats->rx_length_errors = old_stats->rx_length_errors + get_stat64(&hw_stats->rx_frame_too_long_errors) + get_stat64(&hw_stats->rx_undersize_packets); stats->rx_over_errors = old_stats->rx_over_errors + get_stat64(&hw_stats->rxbds_empty); stats->rx_frame_errors = old_stats->rx_frame_errors + get_stat64(&hw_stats->rx_align_errors); stats->tx_aborted_errors = old_stats->tx_aborted_errors + get_stat64(&hw_stats->tx_discards); stats->tx_carrier_errors = old_stats->tx_carrier_errors + get_stat64(&hw_stats->tx_carrier_sense_errors); stats->rx_crc_errors = old_stats->rx_crc_errors + tg3_calc_crc_errors(tp); stats->rx_missed_errors = old_stats->rx_missed_errors + get_stat64(&hw_stats->rx_discards); stats->rx_dropped = tp->rx_dropped; stats->tx_dropped = tp->tx_dropped; } static int tg3_get_regs_len(struct net_device *dev) { return TG3_REG_BLK_SIZE; } static void tg3_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *_p) { struct tg3 *tp = netdev_priv(dev); regs->version = 0; memset(_p, 0, TG3_REG_BLK_SIZE); if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) return; tg3_full_lock(tp, 0); tg3_dump_legacy_regs(tp, (u32 *)_p); tg3_full_unlock(tp); } static int tg3_get_eeprom_len(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); return tp->nvram_size; } static int tg3_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { struct tg3 *tp = netdev_priv(dev); int ret; u8 *pd; u32 i, offset, len, b_offset, b_count; __be32 val; if (tg3_flag(tp, NO_NVRAM)) return -EINVAL; if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) return -EAGAIN; offset = eeprom->offset; len = eeprom->len; eeprom->len = 0; eeprom->magic = TG3_EEPROM_MAGIC; if (offset & 3) { /* adjustments to start on required 4 byte boundary */ b_offset = offset & 3; b_count = 4 - b_offset; if (b_count > len) { /* i.e. offset=1 len=2 */ b_count = len; } ret = tg3_nvram_read_be32(tp, offset-b_offset, &val); if (ret) return ret; memcpy(data, ((char *)&val) + b_offset, b_count); len -= b_count; offset += b_count; eeprom->len += b_count; } /* read bytes up to the last 4 byte boundary */ pd = &data[eeprom->len]; for (i = 0; i < (len - (len & 3)); i += 4) { ret = tg3_nvram_read_be32(tp, offset + i, &val); if (ret) { eeprom->len += i; return ret; } memcpy(pd + i, &val, 4); } eeprom->len += i; if (len & 3) { /* read last bytes not ending on 4 byte boundary */ pd = &data[eeprom->len]; b_count = len & 3; b_offset = offset + len - b_count; ret = tg3_nvram_read_be32(tp, b_offset, &val); if (ret) return ret; memcpy(pd, &val, b_count); eeprom->len += b_count; } return 0; } static int tg3_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data) { struct tg3 *tp = netdev_priv(dev); int ret; u32 offset, len, b_offset, odd_len; u8 *buf; __be32 start, end; if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) return -EAGAIN; if (tg3_flag(tp, NO_NVRAM) || eeprom->magic != TG3_EEPROM_MAGIC) return -EINVAL; offset = eeprom->offset; len = eeprom->len; if ((b_offset = (offset & 3))) { /* adjustments to start on required 4 byte boundary */ ret = tg3_nvram_read_be32(tp, offset-b_offset, &start); if (ret) return ret; len += b_offset; offset &= ~3; if (len < 4) len = 4; } odd_len = 0; if (len & 3) { /* adjustments to end on required 4 byte boundary */ odd_len = 1; len = (len + 3) & ~3; ret = tg3_nvram_read_be32(tp, offset+len-4, &end); if (ret) return ret; } buf = data; if (b_offset || odd_len) { buf = kmalloc(len, GFP_KERNEL); if (!buf) return -ENOMEM; if (b_offset) memcpy(buf, &start, 4); if (odd_len) memcpy(buf+len-4, &end, 4); memcpy(buf + b_offset, data, eeprom->len); } ret = tg3_nvram_write_block(tp, offset, len, buf); if (buf != data) kfree(buf); return ret; } static int tg3_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, USE_PHYLIB)) { struct phy_device *phydev; if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)) return -EAGAIN; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; return phy_ethtool_gset(phydev, cmd); } cmd->supported = (SUPPORTED_Autoneg); if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) cmd->supported |= (SUPPORTED_1000baseT_Half | SUPPORTED_1000baseT_Full); if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) { cmd->supported |= (SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_TP); cmd->port = PORT_TP; } else { cmd->supported |= SUPPORTED_FIBRE; cmd->port = PORT_FIBRE; } cmd->advertising = tp->link_config.advertising; if (tg3_flag(tp, PAUSE_AUTONEG)) { if (tp->link_config.flowctrl & FLOW_CTRL_RX) { if (tp->link_config.flowctrl & FLOW_CTRL_TX) { cmd->advertising |= ADVERTISED_Pause; } else { cmd->advertising |= ADVERTISED_Pause | ADVERTISED_Asym_Pause; } } else if (tp->link_config.flowctrl & FLOW_CTRL_TX) { cmd->advertising |= ADVERTISED_Asym_Pause; } } if (netif_running(dev) && tp->link_up) { ethtool_cmd_speed_set(cmd, tp->link_config.active_speed); cmd->duplex = tp->link_config.active_duplex; cmd->lp_advertising = tp->link_config.rmt_adv; if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) { if (tp->phy_flags & TG3_PHYFLG_MDIX_STATE) cmd->eth_tp_mdix = ETH_TP_MDI_X; else cmd->eth_tp_mdix = ETH_TP_MDI; } } else { ethtool_cmd_speed_set(cmd, SPEED_UNKNOWN); cmd->duplex = DUPLEX_UNKNOWN; cmd->eth_tp_mdix = ETH_TP_MDI_INVALID; } cmd->phy_address = tp->phy_addr; cmd->transceiver = XCVR_INTERNAL; cmd->autoneg = tp->link_config.autoneg; cmd->maxtxpkt = 0; cmd->maxrxpkt = 0; return 0; } static int tg3_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct tg3 *tp = netdev_priv(dev); u32 speed = ethtool_cmd_speed(cmd); if (tg3_flag(tp, USE_PHYLIB)) { struct phy_device *phydev; if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)) return -EAGAIN; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; return phy_ethtool_sset(phydev, cmd); } if (cmd->autoneg != AUTONEG_ENABLE && cmd->autoneg != AUTONEG_DISABLE) return -EINVAL; if (cmd->autoneg == AUTONEG_DISABLE && cmd->duplex != DUPLEX_FULL && cmd->duplex != DUPLEX_HALF) return -EINVAL; if (cmd->autoneg == AUTONEG_ENABLE) { u32 mask = ADVERTISED_Autoneg | ADVERTISED_Pause | ADVERTISED_Asym_Pause; if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) mask |= ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full; if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) mask |= ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_TP; else mask |= ADVERTISED_FIBRE; if (cmd->advertising & ~mask) return -EINVAL; mask &= (ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full | ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full); cmd->advertising &= mask; } else { if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES) { if (speed != SPEED_1000) return -EINVAL; if (cmd->duplex != DUPLEX_FULL) return -EINVAL; } else { if (speed != SPEED_100 && speed != SPEED_10) return -EINVAL; } } tg3_full_lock(tp, 0); tp->link_config.autoneg = cmd->autoneg; if (cmd->autoneg == AUTONEG_ENABLE) { tp->link_config.advertising = (cmd->advertising | ADVERTISED_Autoneg); tp->link_config.speed = SPEED_UNKNOWN; tp->link_config.duplex = DUPLEX_UNKNOWN; } else { tp->link_config.advertising = 0; tp->link_config.speed = speed; tp->link_config.duplex = cmd->duplex; } if (netif_running(dev)) tg3_setup_phy(tp, 1); tg3_full_unlock(tp); return 0; } static void tg3_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct tg3 *tp = netdev_priv(dev); strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version)); strlcpy(info->fw_version, tp->fw_ver, sizeof(info->fw_version)); strlcpy(info->bus_info, pci_name(tp->pdev), sizeof(info->bus_info)); } static void tg3_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, WOL_CAP) && device_can_wakeup(&tp->pdev->dev)) wol->supported = WAKE_MAGIC; else wol->supported = 0; wol->wolopts = 0; if (tg3_flag(tp, WOL_ENABLE) && device_can_wakeup(&tp->pdev->dev)) wol->wolopts = WAKE_MAGIC; memset(&wol->sopass, 0, sizeof(wol->sopass)); } static int tg3_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct tg3 *tp = netdev_priv(dev); struct device *dp = &tp->pdev->dev; if (wol->wolopts & ~WAKE_MAGIC) return -EINVAL; if ((wol->wolopts & WAKE_MAGIC) && !(tg3_flag(tp, WOL_CAP) && device_can_wakeup(dp))) return -EINVAL; device_set_wakeup_enable(dp, wol->wolopts & WAKE_MAGIC); spin_lock_bh(&tp->lock); if (device_may_wakeup(dp)) tg3_flag_set(tp, WOL_ENABLE); else tg3_flag_clear(tp, WOL_ENABLE); spin_unlock_bh(&tp->lock); return 0; } static u32 tg3_get_msglevel(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); return tp->msg_enable; } static void tg3_set_msglevel(struct net_device *dev, u32 value) { struct tg3 *tp = netdev_priv(dev); tp->msg_enable = value; } static int tg3_nway_reset(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); int r; if (!netif_running(dev)) return -EAGAIN; if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) return -EINVAL; if (tg3_flag(tp, USE_PHYLIB)) { if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)) return -EAGAIN; r = phy_start_aneg(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]); } else { u32 bmcr; spin_lock_bh(&tp->lock); r = -EINVAL; tg3_readphy(tp, MII_BMCR, &bmcr); if (!tg3_readphy(tp, MII_BMCR, &bmcr) && ((bmcr & BMCR_ANENABLE) || (tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT))) { tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); r = 0; } spin_unlock_bh(&tp->lock); } return r; } static void tg3_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct tg3 *tp = netdev_priv(dev); ering->rx_max_pending = tp->rx_std_ring_mask; if (tg3_flag(tp, JUMBO_RING_ENABLE)) ering->rx_jumbo_max_pending = tp->rx_jmb_ring_mask; else ering->rx_jumbo_max_pending = 0; ering->tx_max_pending = TG3_TX_RING_SIZE - 1; ering->rx_pending = tp->rx_pending; if (tg3_flag(tp, JUMBO_RING_ENABLE)) ering->rx_jumbo_pending = tp->rx_jumbo_pending; else ering->rx_jumbo_pending = 0; ering->tx_pending = tp->napi[0].tx_pending; } static int tg3_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct tg3 *tp = netdev_priv(dev); int i, irq_sync = 0, err = 0; if ((ering->rx_pending > tp->rx_std_ring_mask) || (ering->rx_jumbo_pending > tp->rx_jmb_ring_mask) || (ering->tx_pending > TG3_TX_RING_SIZE - 1) || (ering->tx_pending <= MAX_SKB_FRAGS) || (tg3_flag(tp, TSO_BUG) && (ering->tx_pending <= (MAX_SKB_FRAGS * 3)))) return -EINVAL; if (netif_running(dev)) { tg3_phy_stop(tp); tg3_netif_stop(tp); irq_sync = 1; } tg3_full_lock(tp, irq_sync); tp->rx_pending = ering->rx_pending; if (tg3_flag(tp, MAX_RXPEND_64) && tp->rx_pending > 63) tp->rx_pending = 63; tp->rx_jumbo_pending = ering->rx_jumbo_pending; for (i = 0; i < tp->irq_max; i++) tp->napi[i].tx_pending = ering->tx_pending; if (netif_running(dev)) { tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); err = tg3_restart_hw(tp, 1); if (!err) tg3_netif_start(tp); } tg3_full_unlock(tp); if (irq_sync && !err) tg3_phy_start(tp); return err; } static void tg3_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct tg3 *tp = netdev_priv(dev); epause->autoneg = !!tg3_flag(tp, PAUSE_AUTONEG); if (tp->link_config.flowctrl & FLOW_CTRL_RX) epause->rx_pause = 1; else epause->rx_pause = 0; if (tp->link_config.flowctrl & FLOW_CTRL_TX) epause->tx_pause = 1; else epause->tx_pause = 0; } static int tg3_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct tg3 *tp = netdev_priv(dev); int err = 0; if (tg3_flag(tp, USE_PHYLIB)) { u32 newadv; struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; if (!(phydev->supported & SUPPORTED_Pause) || (!(phydev->supported & SUPPORTED_Asym_Pause) && (epause->rx_pause != epause->tx_pause))) return -EINVAL; tp->link_config.flowctrl = 0; if (epause->rx_pause) { tp->link_config.flowctrl |= FLOW_CTRL_RX; if (epause->tx_pause) { tp->link_config.flowctrl |= FLOW_CTRL_TX; newadv = ADVERTISED_Pause; } else newadv = ADVERTISED_Pause | ADVERTISED_Asym_Pause; } else if (epause->tx_pause) { tp->link_config.flowctrl |= FLOW_CTRL_TX; newadv = ADVERTISED_Asym_Pause; } else newadv = 0; if (epause->autoneg) tg3_flag_set(tp, PAUSE_AUTONEG); else tg3_flag_clear(tp, PAUSE_AUTONEG); if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) { u32 oldadv = phydev->advertising & (ADVERTISED_Pause | ADVERTISED_Asym_Pause); if (oldadv != newadv) { phydev->advertising &= ~(ADVERTISED_Pause | ADVERTISED_Asym_Pause); phydev->advertising |= newadv; if (phydev->autoneg) { /* * Always renegotiate the link to * inform our link partner of our * flow control settings, even if the * flow control is forced. Let * tg3_adjust_link() do the final * flow control setup. */ return phy_start_aneg(phydev); } } if (!epause->autoneg) tg3_setup_flow_control(tp, 0, 0); } else { tp->link_config.advertising &= ~(ADVERTISED_Pause | ADVERTISED_Asym_Pause); tp->link_config.advertising |= newadv; } } else { int irq_sync = 0; if (netif_running(dev)) { tg3_netif_stop(tp); irq_sync = 1; } tg3_full_lock(tp, irq_sync); if (epause->autoneg) tg3_flag_set(tp, PAUSE_AUTONEG); else tg3_flag_clear(tp, PAUSE_AUTONEG); if (epause->rx_pause) tp->link_config.flowctrl |= FLOW_CTRL_RX; else tp->link_config.flowctrl &= ~FLOW_CTRL_RX; if (epause->tx_pause) tp->link_config.flowctrl |= FLOW_CTRL_TX; else tp->link_config.flowctrl &= ~FLOW_CTRL_TX; if (netif_running(dev)) { tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); err = tg3_restart_hw(tp, 1); if (!err) tg3_netif_start(tp); } tg3_full_unlock(tp); } return err; } static int tg3_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_TEST: return TG3_NUM_TEST; case ETH_SS_STATS: return TG3_NUM_STATS; default: return -EOPNOTSUPP; } } static int tg3_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rules __always_unused) { struct tg3 *tp = netdev_priv(dev); if (!tg3_flag(tp, SUPPORT_MSIX)) return -EOPNOTSUPP; switch (info->cmd) { case ETHTOOL_GRXRINGS: if (netif_running(tp->dev)) info->data = tp->rxq_cnt; else { info->data = num_online_cpus(); if (info->data > TG3_RSS_MAX_NUM_QS) info->data = TG3_RSS_MAX_NUM_QS; } /* The first interrupt vector only * handles link interrupts. */ info->data -= 1; return 0; default: return -EOPNOTSUPP; } } static u32 tg3_get_rxfh_indir_size(struct net_device *dev) { u32 size = 0; struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, SUPPORT_MSIX)) size = TG3_RSS_INDIR_TBL_SIZE; return size; } static int tg3_get_rxfh_indir(struct net_device *dev, u32 *indir) { struct tg3 *tp = netdev_priv(dev); int i; for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++) indir[i] = tp->rss_ind_tbl[i]; return 0; } static int tg3_set_rxfh_indir(struct net_device *dev, const u32 *indir) { struct tg3 *tp = netdev_priv(dev); size_t i; for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++) tp->rss_ind_tbl[i] = indir[i]; if (!netif_running(dev) || !tg3_flag(tp, ENABLE_RSS)) return 0; /* It is legal to write the indirection * table while the device is running. */ tg3_full_lock(tp, 0); tg3_rss_write_indir_tbl(tp); tg3_full_unlock(tp); return 0; } static void tg3_get_channels(struct net_device *dev, struct ethtool_channels *channel) { struct tg3 *tp = netdev_priv(dev); u32 deflt_qs = netif_get_num_default_rss_queues(); channel->max_rx = tp->rxq_max; channel->max_tx = tp->txq_max; if (netif_running(dev)) { channel->rx_count = tp->rxq_cnt; channel->tx_count = tp->txq_cnt; } else { if (tp->rxq_req) channel->rx_count = tp->rxq_req; else channel->rx_count = min(deflt_qs, tp->rxq_max); if (tp->txq_req) channel->tx_count = tp->txq_req; else channel->tx_count = min(deflt_qs, tp->txq_max); } } static int tg3_set_channels(struct net_device *dev, struct ethtool_channels *channel) { struct tg3 *tp = netdev_priv(dev); if (!tg3_flag(tp, SUPPORT_MSIX)) return -EOPNOTSUPP; if (channel->rx_count > tp->rxq_max || channel->tx_count > tp->txq_max) return -EINVAL; tp->rxq_req = channel->rx_count; tp->txq_req = channel->tx_count; if (!netif_running(dev)) return 0; tg3_stop(tp); tg3_carrier_off(tp); tg3_start(tp, true, false, false); return 0; } static void tg3_get_strings(struct net_device *dev, u32 stringset, u8 *buf) { switch (stringset) { case ETH_SS_STATS: memcpy(buf, &ethtool_stats_keys, sizeof(ethtool_stats_keys)); break; case ETH_SS_TEST: memcpy(buf, &ethtool_test_keys, sizeof(ethtool_test_keys)); break; default: WARN_ON(1); /* we need a WARN() */ break; } } static int tg3_set_phys_id(struct net_device *dev, enum ethtool_phys_id_state state) { struct tg3 *tp = netdev_priv(dev); if (!netif_running(tp->dev)) return -EAGAIN; switch (state) { case ETHTOOL_ID_ACTIVE: return 1; /* cycle on/off once per second */ case ETHTOOL_ID_ON: tw32(MAC_LED_CTRL, LED_CTRL_LNKLED_OVERRIDE | LED_CTRL_1000MBPS_ON | LED_CTRL_100MBPS_ON | LED_CTRL_10MBPS_ON | LED_CTRL_TRAFFIC_OVERRIDE | LED_CTRL_TRAFFIC_BLINK | LED_CTRL_TRAFFIC_LED); break; case ETHTOOL_ID_OFF: tw32(MAC_LED_CTRL, LED_CTRL_LNKLED_OVERRIDE | LED_CTRL_TRAFFIC_OVERRIDE); break; case ETHTOOL_ID_INACTIVE: tw32(MAC_LED_CTRL, tp->led_ctrl); break; } return 0; } static void tg3_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *estats, u64 *tmp_stats) { struct tg3 *tp = netdev_priv(dev); if (tp->hw_stats) tg3_get_estats(tp, (struct tg3_ethtool_stats *)tmp_stats); else memset(tmp_stats, 0, sizeof(struct tg3_ethtool_stats)); } static __be32 *tg3_vpd_readblock(struct tg3 *tp, u32 *vpdlen) { int i; __be32 *buf; u32 offset = 0, len = 0; u32 magic, val; if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &magic)) return NULL; if (magic == TG3_EEPROM_MAGIC) { for (offset = TG3_NVM_DIR_START; offset < TG3_NVM_DIR_END; offset += TG3_NVM_DIRENT_SIZE) { if (tg3_nvram_read(tp, offset, &val)) return NULL; if ((val >> TG3_NVM_DIRTYPE_SHIFT) == TG3_NVM_DIRTYPE_EXTVPD) break; } if (offset != TG3_NVM_DIR_END) { len = (val & TG3_NVM_DIRTYPE_LENMSK) * 4; if (tg3_nvram_read(tp, offset + 4, &offset)) return NULL; offset = tg3_nvram_logical_addr(tp, offset); } } if (!offset || !len) { offset = TG3_NVM_VPD_OFF; len = TG3_NVM_VPD_LEN; } buf = kmalloc(len, GFP_KERNEL); if (buf == NULL) return NULL; if (magic == TG3_EEPROM_MAGIC) { for (i = 0; i < len; i += 4) { /* The data is in little-endian format in NVRAM. * Use the big-endian read routines to preserve * the byte order as it exists in NVRAM. */ if (tg3_nvram_read_be32(tp, offset + i, &buf[i/4])) goto error; } } else { u8 *ptr; ssize_t cnt; unsigned int pos = 0; ptr = (u8 *)&buf[0]; for (i = 0; pos < len && i < 3; i++, pos += cnt, ptr += cnt) { cnt = pci_read_vpd(tp->pdev, pos, len - pos, ptr); if (cnt == -ETIMEDOUT || cnt == -EINTR) cnt = 0; else if (cnt < 0) goto error; } if (pos != len) goto error; } *vpdlen = len; return buf; error: kfree(buf); return NULL; } #define NVRAM_TEST_SIZE 0x100 #define NVRAM_SELFBOOT_FORMAT1_0_SIZE 0x14 #define NVRAM_SELFBOOT_FORMAT1_2_SIZE 0x18 #define NVRAM_SELFBOOT_FORMAT1_3_SIZE 0x1c #define NVRAM_SELFBOOT_FORMAT1_4_SIZE 0x20 #define NVRAM_SELFBOOT_FORMAT1_5_SIZE 0x24 #define NVRAM_SELFBOOT_FORMAT1_6_SIZE 0x50 #define NVRAM_SELFBOOT_HW_SIZE 0x20 #define NVRAM_SELFBOOT_DATA_SIZE 0x1c static int tg3_test_nvram(struct tg3 *tp) { u32 csum, magic, len; __be32 *buf; int i, j, k, err = 0, size; if (tg3_flag(tp, NO_NVRAM)) return 0; if (tg3_nvram_read(tp, 0, &magic) != 0) return -EIO; if (magic == TG3_EEPROM_MAGIC) size = NVRAM_TEST_SIZE; else if ((magic & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW) { if ((magic & TG3_EEPROM_SB_FORMAT_MASK) == TG3_EEPROM_SB_FORMAT_1) { switch (magic & TG3_EEPROM_SB_REVISION_MASK) { case TG3_EEPROM_SB_REVISION_0: size = NVRAM_SELFBOOT_FORMAT1_0_SIZE; break; case TG3_EEPROM_SB_REVISION_2: size = NVRAM_SELFBOOT_FORMAT1_2_SIZE; break; case TG3_EEPROM_SB_REVISION_3: size = NVRAM_SELFBOOT_FORMAT1_3_SIZE; break; case TG3_EEPROM_SB_REVISION_4: size = NVRAM_SELFBOOT_FORMAT1_4_SIZE; break; case TG3_EEPROM_SB_REVISION_5: size = NVRAM_SELFBOOT_FORMAT1_5_SIZE; break; case TG3_EEPROM_SB_REVISION_6: size = NVRAM_SELFBOOT_FORMAT1_6_SIZE; break; default: return -EIO; } } else return 0; } else if ((magic & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW) size = NVRAM_SELFBOOT_HW_SIZE; else return -EIO; buf = kmalloc(size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; err = -EIO; for (i = 0, j = 0; i < size; i += 4, j++) { err = tg3_nvram_read_be32(tp, i, &buf[j]); if (err) break; } if (i < size) goto out; /* Selfboot format */ magic = be32_to_cpu(buf[0]); if ((magic & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW) { u8 *buf8 = (u8 *) buf, csum8 = 0; if ((magic & TG3_EEPROM_SB_REVISION_MASK) == TG3_EEPROM_SB_REVISION_2) { /* For rev 2, the csum doesn't include the MBA. */ for (i = 0; i < TG3_EEPROM_SB_F1R2_MBA_OFF; i++) csum8 += buf8[i]; for (i = TG3_EEPROM_SB_F1R2_MBA_OFF + 4; i < size; i++) csum8 += buf8[i]; } else { for (i = 0; i < size; i++) csum8 += buf8[i]; } if (csum8 == 0) { err = 0; goto out; } err = -EIO; goto out; } if ((magic & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW) { u8 data[NVRAM_SELFBOOT_DATA_SIZE]; u8 parity[NVRAM_SELFBOOT_DATA_SIZE]; u8 *buf8 = (u8 *) buf; /* Separate the parity bits and the data bytes. */ for (i = 0, j = 0, k = 0; i < NVRAM_SELFBOOT_HW_SIZE; i++) { if ((i == 0) || (i == 8)) { int l; u8 msk; for (l = 0, msk = 0x80; l < 7; l++, msk >>= 1) parity[k++] = buf8[i] & msk; i++; } else if (i == 16) { int l; u8 msk; for (l = 0, msk = 0x20; l < 6; l++, msk >>= 1) parity[k++] = buf8[i] & msk; i++; for (l = 0, msk = 0x80; l < 8; l++, msk >>= 1) parity[k++] = buf8[i] & msk; i++; } data[j++] = buf8[i]; } err = -EIO; for (i = 0; i < NVRAM_SELFBOOT_DATA_SIZE; i++) { u8 hw8 = hweight8(data[i]); if ((hw8 & 0x1) && parity[i]) goto out; else if (!(hw8 & 0x1) && !parity[i]) goto out; } err = 0; goto out; } err = -EIO; /* Bootstrap checksum at offset 0x10 */ csum = calc_crc((unsigned char *) buf, 0x10); if (csum != le32_to_cpu(buf[0x10/4])) goto out; /* Manufacturing block starts at offset 0x74, checksum at 0xfc */ csum = calc_crc((unsigned char *) &buf[0x74/4], 0x88); if (csum != le32_to_cpu(buf[0xfc/4])) goto out; kfree(buf); buf = tg3_vpd_readblock(tp, &len); if (!buf) return -ENOMEM; i = pci_vpd_find_tag((u8 *)buf, 0, len, PCI_VPD_LRDT_RO_DATA); if (i > 0) { j = pci_vpd_lrdt_size(&((u8 *)buf)[i]); if (j < 0) goto out; if (i + PCI_VPD_LRDT_TAG_SIZE + j > len) goto out; i += PCI_VPD_LRDT_TAG_SIZE; j = pci_vpd_find_info_keyword((u8 *)buf, i, j, PCI_VPD_RO_KEYWORD_CHKSUM); if (j > 0) { u8 csum8 = 0; j += PCI_VPD_INFO_FLD_HDR_SIZE; for (i = 0; i <= j; i++) csum8 += ((u8 *)buf)[i]; if (csum8) goto out; } } err = 0; out: kfree(buf); return err; } #define TG3_SERDES_TIMEOUT_SEC 2 #define TG3_COPPER_TIMEOUT_SEC 6 static int tg3_test_link(struct tg3 *tp) { int i, max; if (!netif_running(tp->dev)) return -ENODEV; if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES) max = TG3_SERDES_TIMEOUT_SEC; else max = TG3_COPPER_TIMEOUT_SEC; for (i = 0; i < max; i++) { if (tp->link_up) return 0; if (msleep_interruptible(1000)) break; } return -EIO; } /* Only test the commonly used registers */ static int tg3_test_registers(struct tg3 *tp) { int i, is_5705, is_5750; u32 offset, read_mask, write_mask, val, save_val, read_val; static struct { u16 offset; u16 flags; #define TG3_FL_5705 0x1 #define TG3_FL_NOT_5705 0x2 #define TG3_FL_NOT_5788 0x4 #define TG3_FL_NOT_5750 0x8 u32 read_mask; u32 write_mask; } reg_tbl[] = { /* MAC Control Registers */ { MAC_MODE, TG3_FL_NOT_5705, 0x00000000, 0x00ef6f8c }, { MAC_MODE, TG3_FL_5705, 0x00000000, 0x01ef6b8c }, { MAC_STATUS, TG3_FL_NOT_5705, 0x03800107, 0x00000000 }, { MAC_STATUS, TG3_FL_5705, 0x03800100, 0x00000000 }, { MAC_ADDR_0_HIGH, 0x0000, 0x00000000, 0x0000ffff }, { MAC_ADDR_0_LOW, 0x0000, 0x00000000, 0xffffffff }, { MAC_RX_MTU_SIZE, 0x0000, 0x00000000, 0x0000ffff }, { MAC_TX_MODE, 0x0000, 0x00000000, 0x00000070 }, { MAC_TX_LENGTHS, 0x0000, 0x00000000, 0x00003fff }, { MAC_RX_MODE, TG3_FL_NOT_5705, 0x00000000, 0x000007fc }, { MAC_RX_MODE, TG3_FL_5705, 0x00000000, 0x000007dc }, { MAC_HASH_REG_0, 0x0000, 0x00000000, 0xffffffff }, { MAC_HASH_REG_1, 0x0000, 0x00000000, 0xffffffff }, { MAC_HASH_REG_2, 0x0000, 0x00000000, 0xffffffff }, { MAC_HASH_REG_3, 0x0000, 0x00000000, 0xffffffff }, /* Receive Data and Receive BD Initiator Control Registers. */ { RCVDBDI_JUMBO_BD+0, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVDBDI_JUMBO_BD+4, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVDBDI_JUMBO_BD+8, TG3_FL_NOT_5705, 0x00000000, 0x00000003 }, { RCVDBDI_JUMBO_BD+0xc, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVDBDI_STD_BD+0, 0x0000, 0x00000000, 0xffffffff }, { RCVDBDI_STD_BD+4, 0x0000, 0x00000000, 0xffffffff }, { RCVDBDI_STD_BD+8, 0x0000, 0x00000000, 0xffff0002 }, { RCVDBDI_STD_BD+0xc, 0x0000, 0x00000000, 0xffffffff }, /* Receive BD Initiator Control Registers. */ { RCVBDI_STD_THRESH, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { RCVBDI_STD_THRESH, TG3_FL_5705, 0x00000000, 0x000003ff }, { RCVBDI_JUMBO_THRESH, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, /* Host Coalescing Control Registers. */ { HOSTCC_MODE, TG3_FL_NOT_5705, 0x00000000, 0x00000004 }, { HOSTCC_MODE, TG3_FL_5705, 0x00000000, 0x000000f6 }, { HOSTCC_RXCOL_TICKS, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_RXCOL_TICKS, TG3_FL_5705, 0x00000000, 0x000003ff }, { HOSTCC_TXCOL_TICKS, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_TXCOL_TICKS, TG3_FL_5705, 0x00000000, 0x000003ff }, { HOSTCC_RXMAX_FRAMES, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_RXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { HOSTCC_TXMAX_FRAMES, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_TXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { HOSTCC_RXCOAL_TICK_INT, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_TXCOAL_TICK_INT, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_RXCOAL_MAXF_INT, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_RXCOAL_MAXF_INT, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { HOSTCC_TXCOAL_MAXF_INT, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_TXCOAL_MAXF_INT, TG3_FL_5705 | TG3_FL_NOT_5788, 0x00000000, 0x000000ff }, { HOSTCC_STAT_COAL_TICKS, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_STATS_BLK_HOST_ADDR, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_STATS_BLK_HOST_ADDR+4, TG3_FL_NOT_5705, 0x00000000, 0xffffffff }, { HOSTCC_STATUS_BLK_HOST_ADDR, 0x0000, 0x00000000, 0xffffffff }, { HOSTCC_STATUS_BLK_HOST_ADDR+4, 0x0000, 0x00000000, 0xffffffff }, { HOSTCC_STATS_BLK_NIC_ADDR, 0x0000, 0xffffffff, 0x00000000 }, { HOSTCC_STATUS_BLK_NIC_ADDR, 0x0000, 0xffffffff, 0x00000000 }, /* Buffer Manager Control Registers. */ { BUFMGR_MB_POOL_ADDR, TG3_FL_NOT_5750, 0x00000000, 0x007fff80 }, { BUFMGR_MB_POOL_SIZE, TG3_FL_NOT_5750, 0x00000000, 0x007fffff }, { BUFMGR_MB_RDMA_LOW_WATER, 0x0000, 0x00000000, 0x0000003f }, { BUFMGR_MB_MACRX_LOW_WATER, 0x0000, 0x00000000, 0x000001ff }, { BUFMGR_MB_HIGH_WATER, 0x0000, 0x00000000, 0x000001ff }, { BUFMGR_DMA_DESC_POOL_ADDR, TG3_FL_NOT_5705, 0xffffffff, 0x00000000 }, { BUFMGR_DMA_DESC_POOL_SIZE, TG3_FL_NOT_5705, 0xffffffff, 0x00000000 }, /* Mailbox Registers */ { GRCMBOX_RCVSTD_PROD_IDX+4, 0x0000, 0x00000000, 0x000001ff }, { GRCMBOX_RCVJUMBO_PROD_IDX+4, TG3_FL_NOT_5705, 0x00000000, 0x000001ff }, { GRCMBOX_RCVRET_CON_IDX_0+4, 0x0000, 0x00000000, 0x000007ff }, { GRCMBOX_SNDHOST_PROD_IDX_0+4, 0x0000, 0x00000000, 0x000001ff }, { 0xffff, 0x0000, 0x00000000, 0x00000000 }, }; is_5705 = is_5750 = 0; if (tg3_flag(tp, 5705_PLUS)) { is_5705 = 1; if (tg3_flag(tp, 5750_PLUS)) is_5750 = 1; } for (i = 0; reg_tbl[i].offset != 0xffff; i++) { if (is_5705 && (reg_tbl[i].flags & TG3_FL_NOT_5705)) continue; if (!is_5705 && (reg_tbl[i].flags & TG3_FL_5705)) continue; if (tg3_flag(tp, IS_5788) && (reg_tbl[i].flags & TG3_FL_NOT_5788)) continue; if (is_5750 && (reg_tbl[i].flags & TG3_FL_NOT_5750)) continue; offset = (u32) reg_tbl[i].offset; read_mask = reg_tbl[i].read_mask; write_mask = reg_tbl[i].write_mask; /* Save the original register content */ save_val = tr32(offset); /* Determine the read-only value. */ read_val = save_val & read_mask; /* Write zero to the register, then make sure the read-only bits * are not changed and the read/write bits are all zeros. */ tw32(offset, 0); val = tr32(offset); /* Test the read-only and read/write bits. */ if (((val & read_mask) != read_val) || (val & write_mask)) goto out; /* Write ones to all the bits defined by RdMask and WrMask, then * make sure the read-only bits are not changed and the * read/write bits are all ones. */ tw32(offset, read_mask | write_mask); val = tr32(offset); /* Test the read-only bits. */ if ((val & read_mask) != read_val) goto out; /* Test the read/write bits. */ if ((val & write_mask) != write_mask) goto out; tw32(offset, save_val); } return 0; out: if (netif_msg_hw(tp)) netdev_err(tp->dev, "Register test failed at offset %x\n", offset); tw32(offset, save_val); return -EIO; } static int tg3_do_mem_test(struct tg3 *tp, u32 offset, u32 len) { static const u32 test_pattern[] = { 0x00000000, 0xffffffff, 0xaa55a55a }; int i; u32 j; for (i = 0; i < ARRAY_SIZE(test_pattern); i++) { for (j = 0; j < len; j += 4) { u32 val; tg3_write_mem(tp, offset + j, test_pattern[i]); tg3_read_mem(tp, offset + j, &val); if (val != test_pattern[i]) return -EIO; } } return 0; } static int tg3_test_memory(struct tg3 *tp) { static struct mem_entry { u32 offset; u32 len; } mem_tbl_570x[] = { { 0x00000000, 0x00b50}, { 0x00002000, 0x1c000}, { 0xffffffff, 0x00000} }, mem_tbl_5705[] = { { 0x00000100, 0x0000c}, { 0x00000200, 0x00008}, { 0x00004000, 0x00800}, { 0x00006000, 0x01000}, { 0x00008000, 0x02000}, { 0x00010000, 0x0e000}, { 0xffffffff, 0x00000} }, mem_tbl_5755[] = { { 0x00000200, 0x00008}, { 0x00004000, 0x00800}, { 0x00006000, 0x00800}, { 0x00008000, 0x02000}, { 0x00010000, 0x0c000}, { 0xffffffff, 0x00000} }, mem_tbl_5906[] = { { 0x00000200, 0x00008}, { 0x00004000, 0x00400}, { 0x00006000, 0x00400}, { 0x00008000, 0x01000}, { 0x00010000, 0x01000}, { 0xffffffff, 0x00000} }, mem_tbl_5717[] = { { 0x00000200, 0x00008}, { 0x00010000, 0x0a000}, { 0x00020000, 0x13c00}, { 0xffffffff, 0x00000} }, mem_tbl_57765[] = { { 0x00000200, 0x00008}, { 0x00004000, 0x00800}, { 0x00006000, 0x09800}, { 0x00010000, 0x0a000}, { 0xffffffff, 0x00000} }; struct mem_entry *mem_tbl; int err = 0; int i; if (tg3_flag(tp, 5717_PLUS)) mem_tbl = mem_tbl_5717; else if (tg3_flag(tp, 57765_CLASS) || tg3_asic_rev(tp) == ASIC_REV_5762) mem_tbl = mem_tbl_57765; else if (tg3_flag(tp, 5755_PLUS)) mem_tbl = mem_tbl_5755; else if (tg3_asic_rev(tp) == ASIC_REV_5906) mem_tbl = mem_tbl_5906; else if (tg3_flag(tp, 5705_PLUS)) mem_tbl = mem_tbl_5705; else mem_tbl = mem_tbl_570x; for (i = 0; mem_tbl[i].offset != 0xffffffff; i++) { err = tg3_do_mem_test(tp, mem_tbl[i].offset, mem_tbl[i].len); if (err) break; } return err; } #define TG3_TSO_MSS 500 #define TG3_TSO_IP_HDR_LEN 20 #define TG3_TSO_TCP_HDR_LEN 20 #define TG3_TSO_TCP_OPT_LEN 12 static const u8 tg3_tso_header[] = { 0x08, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x01, 0x0a, 0x00, 0x00, 0x02, 0x0d, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x80, 0x10, 0x10, 0x00, 0x14, 0x09, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, }; static int tg3_run_loopback(struct tg3 *tp, u32 pktsz, bool tso_loopback) { u32 rx_start_idx, rx_idx, tx_idx, opaque_key; u32 base_flags = 0, mss = 0, desc_idx, coal_now, data_off, val; u32 budget; struct sk_buff *skb; u8 *tx_data, *rx_data; dma_addr_t map; int num_pkts, tx_len, rx_len, i, err; struct tg3_rx_buffer_desc *desc; struct tg3_napi *tnapi, *rnapi; struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring; tnapi = &tp->napi[0]; rnapi = &tp->napi[0]; if (tp->irq_cnt > 1) { if (tg3_flag(tp, ENABLE_RSS)) rnapi = &tp->napi[1]; if (tg3_flag(tp, ENABLE_TSS)) tnapi = &tp->napi[1]; } coal_now = tnapi->coal_now | rnapi->coal_now; err = -EIO; tx_len = pktsz; skb = netdev_alloc_skb(tp->dev, tx_len); if (!skb) return -ENOMEM; tx_data = skb_put(skb, tx_len); memcpy(tx_data, tp->dev->dev_addr, 6); memset(tx_data + 6, 0x0, 8); tw32(MAC_RX_MTU_SIZE, tx_len + ETH_FCS_LEN); if (tso_loopback) { struct iphdr *iph = (struct iphdr *)&tx_data[ETH_HLEN]; u32 hdr_len = TG3_TSO_IP_HDR_LEN + TG3_TSO_TCP_HDR_LEN + TG3_TSO_TCP_OPT_LEN; memcpy(tx_data + ETH_ALEN * 2, tg3_tso_header, sizeof(tg3_tso_header)); mss = TG3_TSO_MSS; val = tx_len - ETH_ALEN * 2 - sizeof(tg3_tso_header); num_pkts = DIV_ROUND_UP(val, TG3_TSO_MSS); /* Set the total length field in the IP header */ iph->tot_len = htons((u16)(mss + hdr_len)); base_flags = (TXD_FLAG_CPU_PRE_DMA | TXD_FLAG_CPU_POST_DMA); if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) { struct tcphdr *th; val = ETH_HLEN + TG3_TSO_IP_HDR_LEN; th = (struct tcphdr *)&tx_data[val]; th->check = 0; } else base_flags |= TXD_FLAG_TCPUDP_CSUM; if (tg3_flag(tp, HW_TSO_3)) { mss |= (hdr_len & 0xc) << 12; if (hdr_len & 0x10) base_flags |= 0x00000010; base_flags |= (hdr_len & 0x3e0) << 5; } else if (tg3_flag(tp, HW_TSO_2)) mss |= hdr_len << 9; else if (tg3_flag(tp, HW_TSO_1) || tg3_asic_rev(tp) == ASIC_REV_5705) { mss |= (TG3_TSO_TCP_OPT_LEN << 9); } else { base_flags |= (TG3_TSO_TCP_OPT_LEN << 10); } data_off = ETH_ALEN * 2 + sizeof(tg3_tso_header); } else { num_pkts = 1; data_off = ETH_HLEN; if (tg3_flag(tp, USE_JUMBO_BDFLAG) && tx_len > VLAN_ETH_FRAME_LEN) base_flags |= TXD_FLAG_JMB_PKT; } for (i = data_off; i < tx_len; i++) tx_data[i] = (u8) (i & 0xff); map = pci_map_single(tp->pdev, skb->data, tx_len, PCI_DMA_TODEVICE); if (pci_dma_mapping_error(tp->pdev, map)) { dev_kfree_skb(skb); return -EIO; } val = tnapi->tx_prod; tnapi->tx_buffers[val].skb = skb; dma_unmap_addr_set(&tnapi->tx_buffers[val], mapping, map); tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | rnapi->coal_now); udelay(10); rx_start_idx = rnapi->hw_status->idx[0].rx_producer; budget = tg3_tx_avail(tnapi); if (tg3_tx_frag_set(tnapi, &val, &budget, map, tx_len, base_flags | TXD_FLAG_END, mss, 0)) { tnapi->tx_buffers[val].skb = NULL; dev_kfree_skb(skb); return -EIO; } tnapi->tx_prod++; /* Sync BD data before updating mailbox */ wmb(); tw32_tx_mbox(tnapi->prodmbox, tnapi->tx_prod); tr32_mailbox(tnapi->prodmbox); udelay(10); /* 350 usec to allow enough time on some 10/100 Mbps devices. */ for (i = 0; i < 35; i++) { tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE | coal_now); udelay(10); tx_idx = tnapi->hw_status->idx[0].tx_consumer; rx_idx = rnapi->hw_status->idx[0].rx_producer; if ((tx_idx == tnapi->tx_prod) && (rx_idx == (rx_start_idx + num_pkts))) break; } tg3_tx_skb_unmap(tnapi, tnapi->tx_prod - 1, -1); dev_kfree_skb(skb); if (tx_idx != tnapi->tx_prod) goto out; if (rx_idx != rx_start_idx + num_pkts) goto out; val = data_off; while (rx_idx != rx_start_idx) { desc = &rnapi->rx_rcb[rx_start_idx++]; desc_idx = desc->opaque & RXD_OPAQUE_INDEX_MASK; opaque_key = desc->opaque & RXD_OPAQUE_RING_MASK; if ((desc->err_vlan & RXD_ERR_MASK) != 0 && (desc->err_vlan != RXD_ERR_ODD_NIBBLE_RCVD_MII)) goto out; rx_len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT) - ETH_FCS_LEN; if (!tso_loopback) { if (rx_len != tx_len) goto out; if (pktsz <= TG3_RX_STD_DMA_SZ - ETH_FCS_LEN) { if (opaque_key != RXD_OPAQUE_RING_STD) goto out; } else { if (opaque_key != RXD_OPAQUE_RING_JUMBO) goto out; } } else if ((desc->type_flags & RXD_FLAG_TCPUDP_CSUM) && (desc->ip_tcp_csum & RXD_TCPCSUM_MASK) >> RXD_TCPCSUM_SHIFT != 0xffff) { goto out; } if (opaque_key == RXD_OPAQUE_RING_STD) { rx_data = tpr->rx_std_buffers[desc_idx].data; map = dma_unmap_addr(&tpr->rx_std_buffers[desc_idx], mapping); } else if (opaque_key == RXD_OPAQUE_RING_JUMBO) { rx_data = tpr->rx_jmb_buffers[desc_idx].data; map = dma_unmap_addr(&tpr->rx_jmb_buffers[desc_idx], mapping); } else goto out; pci_dma_sync_single_for_cpu(tp->pdev, map, rx_len, PCI_DMA_FROMDEVICE); rx_data += TG3_RX_OFFSET(tp); for (i = data_off; i < rx_len; i++, val++) { if (*(rx_data + i) != (u8) (val & 0xff)) goto out; } } err = 0; /* tg3_free_rings will unmap and free the rx_data */ out: return err; } #define TG3_STD_LOOPBACK_FAILED 1 #define TG3_JMB_LOOPBACK_FAILED 2 #define TG3_TSO_LOOPBACK_FAILED 4 #define TG3_LOOPBACK_FAILED \ (TG3_STD_LOOPBACK_FAILED | \ TG3_JMB_LOOPBACK_FAILED | \ TG3_TSO_LOOPBACK_FAILED) static int tg3_test_loopback(struct tg3 *tp, u64 *data, bool do_extlpbk) { int err = -EIO; u32 eee_cap; u32 jmb_pkt_sz = 9000; if (tp->dma_limit) jmb_pkt_sz = tp->dma_limit - ETH_HLEN; eee_cap = tp->phy_flags & TG3_PHYFLG_EEE_CAP; tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP; if (!netif_running(tp->dev)) { data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; if (do_extlpbk) data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; goto done; } err = tg3_reset_hw(tp, 1); if (err) { data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; if (do_extlpbk) data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; goto done; } if (tg3_flag(tp, ENABLE_RSS)) { int i; /* Reroute all rx packets to the 1st queue */ for (i = MAC_RSS_INDIR_TBL_0; i < MAC_RSS_INDIR_TBL_0 + TG3_RSS_INDIR_TBL_SIZE; i += 4) tw32(i, 0x0); } /* HW errata - mac loopback fails in some cases on 5780. * Normal traffic and PHY loopback are not affected by * errata. Also, the MAC loopback test is deprecated for * all newer ASIC revisions. */ if (tg3_asic_rev(tp) != ASIC_REV_5780 && !tg3_flag(tp, CPMU_PRESENT)) { tg3_mac_loopback(tp, true); if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) data[TG3_MAC_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; if (tg3_flag(tp, JUMBO_RING_ENABLE) && tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) data[TG3_MAC_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; tg3_mac_loopback(tp, false); } if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) && !tg3_flag(tp, USE_PHYLIB)) { int i; tg3_phy_lpbk_set(tp, 0, false); /* Wait for link */ for (i = 0; i < 100; i++) { if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) break; mdelay(1); } if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) data[TG3_PHY_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; if (tg3_flag(tp, TSO_CAPABLE) && tg3_run_loopback(tp, ETH_FRAME_LEN, true)) data[TG3_PHY_LOOPB_TEST] |= TG3_TSO_LOOPBACK_FAILED; if (tg3_flag(tp, JUMBO_RING_ENABLE) && tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) data[TG3_PHY_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; if (do_extlpbk) { tg3_phy_lpbk_set(tp, 0, true); /* All link indications report up, but the hardware * isn't really ready for about 20 msec. Double it * to be sure. */ mdelay(40); if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) data[TG3_EXT_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; if (tg3_flag(tp, TSO_CAPABLE) && tg3_run_loopback(tp, ETH_FRAME_LEN, true)) data[TG3_EXT_LOOPB_TEST] |= TG3_TSO_LOOPBACK_FAILED; if (tg3_flag(tp, JUMBO_RING_ENABLE) && tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) data[TG3_EXT_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; } /* Re-enable gphy autopowerdown. */ if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD) tg3_phy_toggle_apd(tp, true); } err = (data[TG3_MAC_LOOPB_TEST] | data[TG3_PHY_LOOPB_TEST] | data[TG3_EXT_LOOPB_TEST]) ? -EIO : 0; done: tp->phy_flags |= eee_cap; return err; } static void tg3_self_test(struct net_device *dev, struct ethtool_test *etest, u64 *data) { struct tg3 *tp = netdev_priv(dev); bool doextlpbk = etest->flags & ETH_TEST_FL_EXTERNAL_LB; if ((tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) && tg3_power_up(tp)) { etest->flags |= ETH_TEST_FL_FAILED; memset(data, 1, sizeof(u64) * TG3_NUM_TEST); return; } memset(data, 0, sizeof(u64) * TG3_NUM_TEST); if (tg3_test_nvram(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_NVRAM_TEST] = 1; } if (!doextlpbk && tg3_test_link(tp)) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_LINK_TEST] = 1; } if (etest->flags & ETH_TEST_FL_OFFLINE) { int err, err2 = 0, irq_sync = 0; if (netif_running(dev)) { tg3_phy_stop(tp); tg3_netif_stop(tp); irq_sync = 1; } tg3_full_lock(tp, irq_sync); tg3_halt(tp, RESET_KIND_SUSPEND, 1); err = tg3_nvram_lock(tp); tg3_halt_cpu(tp, RX_CPU_BASE); if (!tg3_flag(tp, 5705_PLUS)) tg3_halt_cpu(tp, TX_CPU_BASE); if (!err) tg3_nvram_unlock(tp); if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) tg3_phy_reset(tp); if (tg3_test_registers(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_REGISTER_TEST] = 1; } if (tg3_test_memory(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_MEMORY_TEST] = 1; } if (doextlpbk) etest->flags |= ETH_TEST_FL_EXTERNAL_LB_DONE; if (tg3_test_loopback(tp, data, doextlpbk)) etest->flags |= ETH_TEST_FL_FAILED; tg3_full_unlock(tp); if (tg3_test_interrupt(tp) != 0) { etest->flags |= ETH_TEST_FL_FAILED; data[TG3_INTERRUPT_TEST] = 1; } tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); if (netif_running(dev)) { tg3_flag_set(tp, INIT_COMPLETE); err2 = tg3_restart_hw(tp, 1); if (!err2) tg3_netif_start(tp); } tg3_full_unlock(tp); if (irq_sync && !err2) tg3_phy_start(tp); } if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) tg3_power_down(tp); } static int tg3_hwtstamp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct tg3 *tp = netdev_priv(dev); struct hwtstamp_config stmpconf; if (!tg3_flag(tp, PTP_CAPABLE)) return -EINVAL; if (copy_from_user(&stmpconf, ifr->ifr_data, sizeof(stmpconf))) return -EFAULT; if (stmpconf.flags) return -EINVAL; switch (stmpconf.tx_type) { case HWTSTAMP_TX_ON: tg3_flag_set(tp, TX_TSTAMP_EN); break; case HWTSTAMP_TX_OFF: tg3_flag_clear(tp, TX_TSTAMP_EN); break; default: return -ERANGE; } switch (stmpconf.rx_filter) { case HWTSTAMP_FILTER_NONE: tp->rxptpctl = 0; break; case HWTSTAMP_FILTER_PTP_V1_L4_EVENT: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V1_EN | TG3_RX_PTP_CTL_ALL_V1_EVENTS; break; case HWTSTAMP_FILTER_PTP_V1_L4_SYNC: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V1_EN | TG3_RX_PTP_CTL_SYNC_EVNT; break; case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V1_EN | TG3_RX_PTP_CTL_DELAY_REQ; break; case HWTSTAMP_FILTER_PTP_V2_EVENT: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_EN | TG3_RX_PTP_CTL_ALL_V2_EVENTS; break; case HWTSTAMP_FILTER_PTP_V2_L2_EVENT: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN | TG3_RX_PTP_CTL_ALL_V2_EVENTS; break; case HWTSTAMP_FILTER_PTP_V2_L4_EVENT: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN | TG3_RX_PTP_CTL_ALL_V2_EVENTS; break; case HWTSTAMP_FILTER_PTP_V2_SYNC: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_EN | TG3_RX_PTP_CTL_SYNC_EVNT; break; case HWTSTAMP_FILTER_PTP_V2_L2_SYNC: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN | TG3_RX_PTP_CTL_SYNC_EVNT; break; case HWTSTAMP_FILTER_PTP_V2_L4_SYNC: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN | TG3_RX_PTP_CTL_SYNC_EVNT; break; case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_EN | TG3_RX_PTP_CTL_DELAY_REQ; break; case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN | TG3_RX_PTP_CTL_DELAY_REQ; break; case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ: tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN | TG3_RX_PTP_CTL_DELAY_REQ; break; default: return -ERANGE; } if (netif_running(dev) && tp->rxptpctl) tw32(TG3_RX_PTP_CTL, tp->rxptpctl | TG3_RX_PTP_CTL_HWTS_INTERLOCK); return copy_to_user(ifr->ifr_data, &stmpconf, sizeof(stmpconf)) ? -EFAULT : 0; } static int tg3_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct mii_ioctl_data *data = if_mii(ifr); struct tg3 *tp = netdev_priv(dev); int err; if (tg3_flag(tp, USE_PHYLIB)) { struct phy_device *phydev; if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)) return -EAGAIN; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; return phy_mii_ioctl(phydev, ifr, cmd); } switch (cmd) { case SIOCGMIIPHY: data->phy_id = tp->phy_addr; /* fallthru */ case SIOCGMIIREG: { u32 mii_regval; if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) break; /* We have no PHY */ if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&tp->lock); err = __tg3_readphy(tp, data->phy_id & 0x1f, data->reg_num & 0x1f, &mii_regval); spin_unlock_bh(&tp->lock); data->val_out = mii_regval; return err; } case SIOCSMIIREG: if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) break; /* We have no PHY */ if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&tp->lock); err = __tg3_writephy(tp, data->phy_id & 0x1f, data->reg_num & 0x1f, data->val_in); spin_unlock_bh(&tp->lock); return err; case SIOCSHWTSTAMP: return tg3_hwtstamp_ioctl(dev, ifr, cmd); default: /* do nothing */ break; } return -EOPNOTSUPP; } static int tg3_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tg3 *tp = netdev_priv(dev); memcpy(ec, &tp->coal, sizeof(*ec)); return 0; } static int tg3_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tg3 *tp = netdev_priv(dev); u32 max_rxcoal_tick_int = 0, max_txcoal_tick_int = 0; u32 max_stat_coal_ticks = 0, min_stat_coal_ticks = 0; if (!tg3_flag(tp, 5705_PLUS)) { max_rxcoal_tick_int = MAX_RXCOAL_TICK_INT; max_txcoal_tick_int = MAX_TXCOAL_TICK_INT; max_stat_coal_ticks = MAX_STAT_COAL_TICKS; min_stat_coal_ticks = MIN_STAT_COAL_TICKS; } if ((ec->rx_coalesce_usecs > MAX_RXCOL_TICKS) || (ec->tx_coalesce_usecs > MAX_TXCOL_TICKS) || (ec->rx_max_coalesced_frames > MAX_RXMAX_FRAMES) || (ec->tx_max_coalesced_frames > MAX_TXMAX_FRAMES) || (ec->rx_coalesce_usecs_irq > max_rxcoal_tick_int) || (ec->tx_coalesce_usecs_irq > max_txcoal_tick_int) || (ec->rx_max_coalesced_frames_irq > MAX_RXCOAL_MAXF_INT) || (ec->tx_max_coalesced_frames_irq > MAX_TXCOAL_MAXF_INT) || (ec->stats_block_coalesce_usecs > max_stat_coal_ticks) || (ec->stats_block_coalesce_usecs < min_stat_coal_ticks)) return -EINVAL; /* No rx interrupts will be generated if both are zero */ if ((ec->rx_coalesce_usecs == 0) && (ec->rx_max_coalesced_frames == 0)) return -EINVAL; /* No tx interrupts will be generated if both are zero */ if ((ec->tx_coalesce_usecs == 0) && (ec->tx_max_coalesced_frames == 0)) return -EINVAL; /* Only copy relevant parameters, ignore all others. */ tp->coal.rx_coalesce_usecs = ec->rx_coalesce_usecs; tp->coal.tx_coalesce_usecs = ec->tx_coalesce_usecs; tp->coal.rx_max_coalesced_frames = ec->rx_max_coalesced_frames; tp->coal.tx_max_coalesced_frames = ec->tx_max_coalesced_frames; tp->coal.rx_coalesce_usecs_irq = ec->rx_coalesce_usecs_irq; tp->coal.tx_coalesce_usecs_irq = ec->tx_coalesce_usecs_irq; tp->coal.rx_max_coalesced_frames_irq = ec->rx_max_coalesced_frames_irq; tp->coal.tx_max_coalesced_frames_irq = ec->tx_max_coalesced_frames_irq; tp->coal.stats_block_coalesce_usecs = ec->stats_block_coalesce_usecs; if (netif_running(dev)) { tg3_full_lock(tp, 0); __tg3_set_coalesce(tp, &tp->coal); tg3_full_unlock(tp); } return 0; } static const struct ethtool_ops tg3_ethtool_ops = { .get_settings = tg3_get_settings, .set_settings = tg3_set_settings, .get_drvinfo = tg3_get_drvinfo, .get_regs_len = tg3_get_regs_len, .get_regs = tg3_get_regs, .get_wol = tg3_get_wol, .set_wol = tg3_set_wol, .get_msglevel = tg3_get_msglevel, .set_msglevel = tg3_set_msglevel, .nway_reset = tg3_nway_reset, .get_link = ethtool_op_get_link, .get_eeprom_len = tg3_get_eeprom_len, .get_eeprom = tg3_get_eeprom, .set_eeprom = tg3_set_eeprom, .get_ringparam = tg3_get_ringparam, .set_ringparam = tg3_set_ringparam, .get_pauseparam = tg3_get_pauseparam, .set_pauseparam = tg3_set_pauseparam, .self_test = tg3_self_test, .get_strings = tg3_get_strings, .set_phys_id = tg3_set_phys_id, .get_ethtool_stats = tg3_get_ethtool_stats, .get_coalesce = tg3_get_coalesce, .set_coalesce = tg3_set_coalesce, .get_sset_count = tg3_get_sset_count, .get_rxnfc = tg3_get_rxnfc, .get_rxfh_indir_size = tg3_get_rxfh_indir_size, .get_rxfh_indir = tg3_get_rxfh_indir, .set_rxfh_indir = tg3_set_rxfh_indir, .get_channels = tg3_get_channels, .set_channels = tg3_set_channels, .get_ts_info = tg3_get_ts_info, }; static struct rtnl_link_stats64 *tg3_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { struct tg3 *tp = netdev_priv(dev); spin_lock_bh(&tp->lock); if (!tp->hw_stats) { spin_unlock_bh(&tp->lock); return &tp->net_stats_prev; } tg3_get_nstats(tp, stats); spin_unlock_bh(&tp->lock); return stats; } static void tg3_set_rx_mode(struct net_device *dev) { struct tg3 *tp = netdev_priv(dev); if (!netif_running(dev)) return; tg3_full_lock(tp, 0); __tg3_set_rx_mode(dev); tg3_full_unlock(tp); } static inline void tg3_set_mtu(struct net_device *dev, struct tg3 *tp, int new_mtu) { dev->mtu = new_mtu; if (new_mtu > ETH_DATA_LEN) { if (tg3_flag(tp, 5780_CLASS)) { netdev_update_features(dev); tg3_flag_clear(tp, TSO_CAPABLE); } else { tg3_flag_set(tp, JUMBO_RING_ENABLE); } } else { if (tg3_flag(tp, 5780_CLASS)) { tg3_flag_set(tp, TSO_CAPABLE); netdev_update_features(dev); } tg3_flag_clear(tp, JUMBO_RING_ENABLE); } } static int tg3_change_mtu(struct net_device *dev, int new_mtu) { struct tg3 *tp = netdev_priv(dev); int err, reset_phy = 0; if (new_mtu < TG3_MIN_MTU || new_mtu > TG3_MAX_MTU(tp)) return -EINVAL; if (!netif_running(dev)) { /* We'll just catch it later when the * device is up'd. */ tg3_set_mtu(dev, tp, new_mtu); return 0; } tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_full_lock(tp, 1); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_set_mtu(dev, tp, new_mtu); /* Reset PHY, otherwise the read DMA engine will be in a mode that * breaks all requests to 256 bytes. */ if (tg3_asic_rev(tp) == ASIC_REV_57766) reset_phy = 1; err = tg3_restart_hw(tp, reset_phy); if (!err) tg3_netif_start(tp); tg3_full_unlock(tp); if (!err) tg3_phy_start(tp); return err; } static const struct net_device_ops tg3_netdev_ops = { .ndo_open = tg3_open, .ndo_stop = tg3_close, .ndo_start_xmit = tg3_start_xmit, .ndo_get_stats64 = tg3_get_stats64, .ndo_validate_addr = eth_validate_addr, .ndo_set_rx_mode = tg3_set_rx_mode, .ndo_set_mac_address = tg3_set_mac_addr, .ndo_do_ioctl = tg3_ioctl, .ndo_tx_timeout = tg3_tx_timeout, .ndo_change_mtu = tg3_change_mtu, .ndo_fix_features = tg3_fix_features, .ndo_set_features = tg3_set_features, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tg3_poll_controller, #endif }; static void tg3_get_eeprom_size(struct tg3 *tp) { u32 cursize, val, magic; tp->nvram_size = EEPROM_CHIP_SIZE; if (tg3_nvram_read(tp, 0, &magic) != 0) return; if ((magic != TG3_EEPROM_MAGIC) && ((magic & TG3_EEPROM_MAGIC_FW_MSK) != TG3_EEPROM_MAGIC_FW) && ((magic & TG3_EEPROM_MAGIC_HW_MSK) != TG3_EEPROM_MAGIC_HW)) return; /* * Size the chip by reading offsets at increasing powers of two. * When we encounter our validation signature, we know the addressing * has wrapped around, and thus have our chip size. */ cursize = 0x10; while (cursize < tp->nvram_size) { if (tg3_nvram_read(tp, cursize, &val) != 0) return; if (val == magic) break; cursize <<= 1; } tp->nvram_size = cursize; } static void tg3_get_nvram_size(struct tg3 *tp) { u32 val; if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &val) != 0) return; /* Selfboot format */ if (val != TG3_EEPROM_MAGIC) { tg3_get_eeprom_size(tp); return; } if (tg3_nvram_read(tp, 0xf0, &val) == 0) { if (val != 0) { /* This is confusing. We want to operate on the * 16-bit value at offset 0xf2. The tg3_nvram_read() * call will read from NVRAM and byteswap the data * according to the byteswapping settings for all * other register accesses. This ensures the data we * want will always reside in the lower 16-bits. * However, the data in NVRAM is in LE format, which * means the data from the NVRAM read will always be * opposite the endianness of the CPU. The 16-bit * byteswap then brings the data to CPU endianness. */ tp->nvram_size = swab16((u16)(val & 0x0000ffff)) * 1024; return; } } tp->nvram_size = TG3_NVRAM_SIZE_512KB; } static void tg3_get_nvram_info(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); if (nvcfg1 & NVRAM_CFG1_FLASHIF_ENAB) { tg3_flag_set(tp, FLASH); } else { nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS; tw32(NVRAM_CFG1, nvcfg1); } if (tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_flag(tp, 5780_CLASS)) { switch (nvcfg1 & NVRAM_CFG1_VENDOR_MASK) { case FLASH_VENDOR_ATMEL_FLASH_BUFFERED: tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = ATMEL_AT45DB0X1B_PAGE_SIZE; tg3_flag_set(tp, NVRAM_BUFFERED); break; case FLASH_VENDOR_ATMEL_FLASH_UNBUFFERED: tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = ATMEL_AT25F512_PAGE_SIZE; break; case FLASH_VENDOR_ATMEL_EEPROM: tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; tg3_flag_set(tp, NVRAM_BUFFERED); break; case FLASH_VENDOR_ST: tp->nvram_jedecnum = JEDEC_ST; tp->nvram_pagesize = ST_M45PEX0_PAGE_SIZE; tg3_flag_set(tp, NVRAM_BUFFERED); break; case FLASH_VENDOR_SAIFUN: tp->nvram_jedecnum = JEDEC_SAIFUN; tp->nvram_pagesize = SAIFUN_SA25F0XX_PAGE_SIZE; break; case FLASH_VENDOR_SST_SMALL: case FLASH_VENDOR_SST_LARGE: tp->nvram_jedecnum = JEDEC_SST; tp->nvram_pagesize = SST_25VF0X0_PAGE_SIZE; break; } } else { tp->nvram_jedecnum = JEDEC_ATMEL; tp->nvram_pagesize = ATMEL_AT45DB0X1B_PAGE_SIZE; tg3_flag_set(tp, NVRAM_BUFFERED); } } static void tg3_nvram_get_pagesize(struct tg3 *tp, u32 nvmcfg1) { switch (nvmcfg1 & NVRAM_CFG1_5752PAGE_SIZE_MASK) { case FLASH_5752PAGE_SIZE_256: tp->nvram_pagesize = 256; break; case FLASH_5752PAGE_SIZE_512: tp->nvram_pagesize = 512; break; case FLASH_5752PAGE_SIZE_1K: tp->nvram_pagesize = 1024; break; case FLASH_5752PAGE_SIZE_2K: tp->nvram_pagesize = 2048; break; case FLASH_5752PAGE_SIZE_4K: tp->nvram_pagesize = 4096; break; case FLASH_5752PAGE_SIZE_264: tp->nvram_pagesize = 264; break; case FLASH_5752PAGE_SIZE_528: tp->nvram_pagesize = 528; break; } } static void tg3_get_5752_nvram_info(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); /* NVRAM protection for TPM */ if (nvcfg1 & (1 << 27)) tg3_flag_set(tp, PROTECTED_NVRAM); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5752VENDOR_ATMEL_EEPROM_64KHZ: case FLASH_5752VENDOR_ATMEL_EEPROM_376KHZ: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); break; case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); break; case FLASH_5752VENDOR_ST_M45PE10: case FLASH_5752VENDOR_ST_M45PE20: case FLASH_5752VENDOR_ST_M45PE40: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); break; } if (tg3_flag(tp, FLASH)) { tg3_nvram_get_pagesize(tp, nvcfg1); } else { /* For eeprom, set pagesize to maximum eeprom size */ tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS; tw32(NVRAM_CFG1, nvcfg1); } } static void tg3_get_5755_nvram_info(struct tg3 *tp) { u32 nvcfg1, protect = 0; nvcfg1 = tr32(NVRAM_CFG1); /* NVRAM protection for TPM */ if (nvcfg1 & (1 << 27)) { tg3_flag_set(tp, PROTECTED_NVRAM); protect = 1; } nvcfg1 &= NVRAM_CFG1_5752VENDOR_MASK; switch (nvcfg1) { case FLASH_5755VENDOR_ATMEL_FLASH_1: case FLASH_5755VENDOR_ATMEL_FLASH_2: case FLASH_5755VENDOR_ATMEL_FLASH_3: case FLASH_5755VENDOR_ATMEL_FLASH_5: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 264; if (nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_1 || nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_5) tp->nvram_size = (protect ? 0x3e200 : TG3_NVRAM_SIZE_512KB); else if (nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_2) tp->nvram_size = (protect ? 0x1f200 : TG3_NVRAM_SIZE_256KB); else tp->nvram_size = (protect ? 0x1f200 : TG3_NVRAM_SIZE_128KB); break; case FLASH_5752VENDOR_ST_M45PE10: case FLASH_5752VENDOR_ST_M45PE20: case FLASH_5752VENDOR_ST_M45PE40: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 256; if (nvcfg1 == FLASH_5752VENDOR_ST_M45PE10) tp->nvram_size = (protect ? TG3_NVRAM_SIZE_64KB : TG3_NVRAM_SIZE_128KB); else if (nvcfg1 == FLASH_5752VENDOR_ST_M45PE20) tp->nvram_size = (protect ? TG3_NVRAM_SIZE_64KB : TG3_NVRAM_SIZE_256KB); else tp->nvram_size = (protect ? TG3_NVRAM_SIZE_128KB : TG3_NVRAM_SIZE_512KB); break; } } static void tg3_get_5787_nvram_info(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5787VENDOR_ATMEL_EEPROM_64KHZ: case FLASH_5787VENDOR_ATMEL_EEPROM_376KHZ: case FLASH_5787VENDOR_MICRO_EEPROM_64KHZ: case FLASH_5787VENDOR_MICRO_EEPROM_376KHZ: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS; tw32(NVRAM_CFG1, nvcfg1); break; case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED: case FLASH_5755VENDOR_ATMEL_FLASH_1: case FLASH_5755VENDOR_ATMEL_FLASH_2: case FLASH_5755VENDOR_ATMEL_FLASH_3: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 264; break; case FLASH_5752VENDOR_ST_M45PE10: case FLASH_5752VENDOR_ST_M45PE20: case FLASH_5752VENDOR_ST_M45PE40: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 256; break; } } static void tg3_get_5761_nvram_info(struct tg3 *tp) { u32 nvcfg1, protect = 0; nvcfg1 = tr32(NVRAM_CFG1); /* NVRAM protection for TPM */ if (nvcfg1 & (1 << 27)) { tg3_flag_set(tp, PROTECTED_NVRAM); protect = 1; } nvcfg1 &= NVRAM_CFG1_5752VENDOR_MASK; switch (nvcfg1) { case FLASH_5761VENDOR_ATMEL_ADB021D: case FLASH_5761VENDOR_ATMEL_ADB041D: case FLASH_5761VENDOR_ATMEL_ADB081D: case FLASH_5761VENDOR_ATMEL_ADB161D: case FLASH_5761VENDOR_ATMEL_MDB021D: case FLASH_5761VENDOR_ATMEL_MDB041D: case FLASH_5761VENDOR_ATMEL_MDB081D: case FLASH_5761VENDOR_ATMEL_MDB161D: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); tp->nvram_pagesize = 256; break; case FLASH_5761VENDOR_ST_A_M45PE20: case FLASH_5761VENDOR_ST_A_M45PE40: case FLASH_5761VENDOR_ST_A_M45PE80: case FLASH_5761VENDOR_ST_A_M45PE16: case FLASH_5761VENDOR_ST_M_M45PE20: case FLASH_5761VENDOR_ST_M_M45PE40: case FLASH_5761VENDOR_ST_M_M45PE80: case FLASH_5761VENDOR_ST_M_M45PE16: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); tp->nvram_pagesize = 256; break; } if (protect) { tp->nvram_size = tr32(NVRAM_ADDR_LOCKOUT); } else { switch (nvcfg1) { case FLASH_5761VENDOR_ATMEL_ADB161D: case FLASH_5761VENDOR_ATMEL_MDB161D: case FLASH_5761VENDOR_ST_A_M45PE16: case FLASH_5761VENDOR_ST_M_M45PE16: tp->nvram_size = TG3_NVRAM_SIZE_2MB; break; case FLASH_5761VENDOR_ATMEL_ADB081D: case FLASH_5761VENDOR_ATMEL_MDB081D: case FLASH_5761VENDOR_ST_A_M45PE80: case FLASH_5761VENDOR_ST_M_M45PE80: tp->nvram_size = TG3_NVRAM_SIZE_1MB; break; case FLASH_5761VENDOR_ATMEL_ADB041D: case FLASH_5761VENDOR_ATMEL_MDB041D: case FLASH_5761VENDOR_ST_A_M45PE40: case FLASH_5761VENDOR_ST_M_M45PE40: tp->nvram_size = TG3_NVRAM_SIZE_512KB; break; case FLASH_5761VENDOR_ATMEL_ADB021D: case FLASH_5761VENDOR_ATMEL_MDB021D: case FLASH_5761VENDOR_ST_A_M45PE20: case FLASH_5761VENDOR_ST_M_M45PE20: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; } } } static void tg3_get_5906_nvram_info(struct tg3 *tp) { tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; } static void tg3_get_57780_nvram_info(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5787VENDOR_ATMEL_EEPROM_376KHZ: case FLASH_5787VENDOR_MICRO_EEPROM_376KHZ: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS; tw32(NVRAM_CFG1, nvcfg1); return; case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED: case FLASH_57780VENDOR_ATMEL_AT45DB011D: case FLASH_57780VENDOR_ATMEL_AT45DB011B: case FLASH_57780VENDOR_ATMEL_AT45DB021D: case FLASH_57780VENDOR_ATMEL_AT45DB021B: case FLASH_57780VENDOR_ATMEL_AT45DB041D: case FLASH_57780VENDOR_ATMEL_AT45DB041B: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED: case FLASH_57780VENDOR_ATMEL_AT45DB011D: case FLASH_57780VENDOR_ATMEL_AT45DB011B: tp->nvram_size = TG3_NVRAM_SIZE_128KB; break; case FLASH_57780VENDOR_ATMEL_AT45DB021D: case FLASH_57780VENDOR_ATMEL_AT45DB021B: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; case FLASH_57780VENDOR_ATMEL_AT45DB041D: case FLASH_57780VENDOR_ATMEL_AT45DB041B: tp->nvram_size = TG3_NVRAM_SIZE_512KB; break; } break; case FLASH_5752VENDOR_ST_M45PE10: case FLASH_5752VENDOR_ST_M45PE20: case FLASH_5752VENDOR_ST_M45PE40: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5752VENDOR_ST_M45PE10: tp->nvram_size = TG3_NVRAM_SIZE_128KB; break; case FLASH_5752VENDOR_ST_M45PE20: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; case FLASH_5752VENDOR_ST_M45PE40: tp->nvram_size = TG3_NVRAM_SIZE_512KB; break; } break; default: tg3_flag_set(tp, NO_NVRAM); return; } tg3_nvram_get_pagesize(tp, nvcfg1); if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528) tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); } static void tg3_get_5717_nvram_info(struct tg3 *tp) { u32 nvcfg1; nvcfg1 = tr32(NVRAM_CFG1); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5717VENDOR_ATMEL_EEPROM: case FLASH_5717VENDOR_MICRO_EEPROM: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS; tw32(NVRAM_CFG1, nvcfg1); return; case FLASH_5717VENDOR_ATMEL_MDB011D: case FLASH_5717VENDOR_ATMEL_ADB011B: case FLASH_5717VENDOR_ATMEL_ADB011D: case FLASH_5717VENDOR_ATMEL_MDB021D: case FLASH_5717VENDOR_ATMEL_ADB021B: case FLASH_5717VENDOR_ATMEL_ADB021D: case FLASH_5717VENDOR_ATMEL_45USPT: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5717VENDOR_ATMEL_MDB021D: /* Detect size with tg3_nvram_get_size() */ break; case FLASH_5717VENDOR_ATMEL_ADB021B: case FLASH_5717VENDOR_ATMEL_ADB021D: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; default: tp->nvram_size = TG3_NVRAM_SIZE_128KB; break; } break; case FLASH_5717VENDOR_ST_M_M25PE10: case FLASH_5717VENDOR_ST_A_M25PE10: case FLASH_5717VENDOR_ST_M_M45PE10: case FLASH_5717VENDOR_ST_A_M45PE10: case FLASH_5717VENDOR_ST_M_M25PE20: case FLASH_5717VENDOR_ST_A_M25PE20: case FLASH_5717VENDOR_ST_M_M45PE20: case FLASH_5717VENDOR_ST_A_M45PE20: case FLASH_5717VENDOR_ST_25USPT: case FLASH_5717VENDOR_ST_45USPT: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) { case FLASH_5717VENDOR_ST_M_M25PE20: case FLASH_5717VENDOR_ST_M_M45PE20: /* Detect size with tg3_nvram_get_size() */ break; case FLASH_5717VENDOR_ST_A_M25PE20: case FLASH_5717VENDOR_ST_A_M45PE20: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; default: tp->nvram_size = TG3_NVRAM_SIZE_128KB; break; } break; default: tg3_flag_set(tp, NO_NVRAM); return; } tg3_nvram_get_pagesize(tp, nvcfg1); if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528) tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); } static void tg3_get_5720_nvram_info(struct tg3 *tp) { u32 nvcfg1, nvmpinstrp; nvcfg1 = tr32(NVRAM_CFG1); nvmpinstrp = nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK; if (tg3_asic_rev(tp) == ASIC_REV_5762) { if (!(nvcfg1 & NVRAM_CFG1_5762VENDOR_MASK)) { tg3_flag_set(tp, NO_NVRAM); return; } switch (nvmpinstrp) { case FLASH_5762_EEPROM_HD: nvmpinstrp = FLASH_5720_EEPROM_HD; break; case FLASH_5762_EEPROM_LD: nvmpinstrp = FLASH_5720_EEPROM_LD; break; } } switch (nvmpinstrp) { case FLASH_5720_EEPROM_HD: case FLASH_5720_EEPROM_LD: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS; tw32(NVRAM_CFG1, nvcfg1); if (nvmpinstrp == FLASH_5720_EEPROM_HD) tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE; else tp->nvram_pagesize = ATMEL_AT24C02_CHIP_SIZE; return; case FLASH_5720VENDOR_M_ATMEL_DB011D: case FLASH_5720VENDOR_A_ATMEL_DB011B: case FLASH_5720VENDOR_A_ATMEL_DB011D: case FLASH_5720VENDOR_M_ATMEL_DB021D: case FLASH_5720VENDOR_A_ATMEL_DB021B: case FLASH_5720VENDOR_A_ATMEL_DB021D: case FLASH_5720VENDOR_M_ATMEL_DB041D: case FLASH_5720VENDOR_A_ATMEL_DB041B: case FLASH_5720VENDOR_A_ATMEL_DB041D: case FLASH_5720VENDOR_M_ATMEL_DB081D: case FLASH_5720VENDOR_A_ATMEL_DB081D: case FLASH_5720VENDOR_ATMEL_45USPT: tp->nvram_jedecnum = JEDEC_ATMEL; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvmpinstrp) { case FLASH_5720VENDOR_M_ATMEL_DB021D: case FLASH_5720VENDOR_A_ATMEL_DB021B: case FLASH_5720VENDOR_A_ATMEL_DB021D: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; case FLASH_5720VENDOR_M_ATMEL_DB041D: case FLASH_5720VENDOR_A_ATMEL_DB041B: case FLASH_5720VENDOR_A_ATMEL_DB041D: tp->nvram_size = TG3_NVRAM_SIZE_512KB; break; case FLASH_5720VENDOR_M_ATMEL_DB081D: case FLASH_5720VENDOR_A_ATMEL_DB081D: tp->nvram_size = TG3_NVRAM_SIZE_1MB; break; default: if (tg3_asic_rev(tp) != ASIC_REV_5762) tp->nvram_size = TG3_NVRAM_SIZE_128KB; break; } break; case FLASH_5720VENDOR_M_ST_M25PE10: case FLASH_5720VENDOR_M_ST_M45PE10: case FLASH_5720VENDOR_A_ST_M25PE10: case FLASH_5720VENDOR_A_ST_M45PE10: case FLASH_5720VENDOR_M_ST_M25PE20: case FLASH_5720VENDOR_M_ST_M45PE20: case FLASH_5720VENDOR_A_ST_M25PE20: case FLASH_5720VENDOR_A_ST_M45PE20: case FLASH_5720VENDOR_M_ST_M25PE40: case FLASH_5720VENDOR_M_ST_M45PE40: case FLASH_5720VENDOR_A_ST_M25PE40: case FLASH_5720VENDOR_A_ST_M45PE40: case FLASH_5720VENDOR_M_ST_M25PE80: case FLASH_5720VENDOR_M_ST_M45PE80: case FLASH_5720VENDOR_A_ST_M25PE80: case FLASH_5720VENDOR_A_ST_M45PE80: case FLASH_5720VENDOR_ST_25USPT: case FLASH_5720VENDOR_ST_45USPT: tp->nvram_jedecnum = JEDEC_ST; tg3_flag_set(tp, NVRAM_BUFFERED); tg3_flag_set(tp, FLASH); switch (nvmpinstrp) { case FLASH_5720VENDOR_M_ST_M25PE20: case FLASH_5720VENDOR_M_ST_M45PE20: case FLASH_5720VENDOR_A_ST_M25PE20: case FLASH_5720VENDOR_A_ST_M45PE20: tp->nvram_size = TG3_NVRAM_SIZE_256KB; break; case FLASH_5720VENDOR_M_ST_M25PE40: case FLASH_5720VENDOR_M_ST_M45PE40: case FLASH_5720VENDOR_A_ST_M25PE40: case FLASH_5720VENDOR_A_ST_M45PE40: tp->nvram_size = TG3_NVRAM_SIZE_512KB; break; case FLASH_5720VENDOR_M_ST_M25PE80: case FLASH_5720VENDOR_M_ST_M45PE80: case FLASH_5720VENDOR_A_ST_M25PE80: case FLASH_5720VENDOR_A_ST_M45PE80: tp->nvram_size = TG3_NVRAM_SIZE_1MB; break; default: if (tg3_asic_rev(tp) != ASIC_REV_5762) tp->nvram_size = TG3_NVRAM_SIZE_128KB; break; } break; default: tg3_flag_set(tp, NO_NVRAM); return; } tg3_nvram_get_pagesize(tp, nvcfg1); if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528) tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS); if (tg3_asic_rev(tp) == ASIC_REV_5762) { u32 val; if (tg3_nvram_read(tp, 0, &val)) return; if (val != TG3_EEPROM_MAGIC && (val & TG3_EEPROM_MAGIC_FW_MSK) != TG3_EEPROM_MAGIC_FW) tg3_flag_set(tp, NO_NVRAM); } } /* Chips other than 5700/5701 use the NVRAM for fetching info. */ static void tg3_nvram_init(struct tg3 *tp) { if (tg3_flag(tp, IS_SSB_CORE)) { /* No NVRAM and EEPROM on the SSB Broadcom GigE core. */ tg3_flag_clear(tp, NVRAM); tg3_flag_clear(tp, NVRAM_BUFFERED); tg3_flag_set(tp, NO_NVRAM); return; } tw32_f(GRC_EEPROM_ADDR, (EEPROM_ADDR_FSM_RESET | (EEPROM_DEFAULT_CLOCK_PERIOD << EEPROM_ADDR_CLKPERD_SHIFT))); msleep(1); /* Enable seeprom accesses. */ tw32_f(GRC_LOCAL_CTRL, tr32(GRC_LOCAL_CTRL) | GRC_LCLCTRL_AUTO_SEEPROM); udelay(100); if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701) { tg3_flag_set(tp, NVRAM); if (tg3_nvram_lock(tp)) { netdev_warn(tp->dev, "Cannot get nvram lock, %s failed\n", __func__); return; } tg3_enable_nvram_access(tp); tp->nvram_size = 0; if (tg3_asic_rev(tp) == ASIC_REV_5752) tg3_get_5752_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5755) tg3_get_5755_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5787 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5785) tg3_get_5787_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5761) tg3_get_5761_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5906) tg3_get_5906_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_CLASS)) tg3_get_57780_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719) tg3_get_5717_nvram_info(tp); else if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_get_5720_nvram_info(tp); else tg3_get_nvram_info(tp); if (tp->nvram_size == 0) tg3_get_nvram_size(tp); tg3_disable_nvram_access(tp); tg3_nvram_unlock(tp); } else { tg3_flag_clear(tp, NVRAM); tg3_flag_clear(tp, NVRAM_BUFFERED); tg3_get_eeprom_size(tp); } } struct subsys_tbl_ent { u16 subsys_vendor, subsys_devid; u32 phy_id; }; static struct subsys_tbl_ent subsys_id_to_phy_id[] = { /* Broadcom boards. */ { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95700A6, TG3_PHY_ID_BCM5401 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95701A5, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95700T6, TG3_PHY_ID_BCM8002 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95700A9, 0 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95701T1, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95701T8, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95701A7, 0 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95701A10, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95701A12, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95703AX1, TG3_PHY_ID_BCM5703 }, { TG3PCI_SUBVENDOR_ID_BROADCOM, TG3PCI_SUBDEVICE_ID_BROADCOM_95703AX2, TG3_PHY_ID_BCM5703 }, /* 3com boards. */ { TG3PCI_SUBVENDOR_ID_3COM, TG3PCI_SUBDEVICE_ID_3COM_3C996T, TG3_PHY_ID_BCM5401 }, { TG3PCI_SUBVENDOR_ID_3COM, TG3PCI_SUBDEVICE_ID_3COM_3C996BT, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_3COM, TG3PCI_SUBDEVICE_ID_3COM_3C996SX, 0 }, { TG3PCI_SUBVENDOR_ID_3COM, TG3PCI_SUBDEVICE_ID_3COM_3C1000T, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_3COM, TG3PCI_SUBDEVICE_ID_3COM_3C940BR01, TG3_PHY_ID_BCM5701 }, /* DELL boards. */ { TG3PCI_SUBVENDOR_ID_DELL, TG3PCI_SUBDEVICE_ID_DELL_VIPER, TG3_PHY_ID_BCM5401 }, { TG3PCI_SUBVENDOR_ID_DELL, TG3PCI_SUBDEVICE_ID_DELL_JAGUAR, TG3_PHY_ID_BCM5401 }, { TG3PCI_SUBVENDOR_ID_DELL, TG3PCI_SUBDEVICE_ID_DELL_MERLOT, TG3_PHY_ID_BCM5411 }, { TG3PCI_SUBVENDOR_ID_DELL, TG3PCI_SUBDEVICE_ID_DELL_SLIM_MERLOT, TG3_PHY_ID_BCM5411 }, /* Compaq boards. */ { TG3PCI_SUBVENDOR_ID_COMPAQ, TG3PCI_SUBDEVICE_ID_COMPAQ_BANSHEE, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_COMPAQ, TG3PCI_SUBDEVICE_ID_COMPAQ_BANSHEE_2, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_COMPAQ, TG3PCI_SUBDEVICE_ID_COMPAQ_CHANGELING, 0 }, { TG3PCI_SUBVENDOR_ID_COMPAQ, TG3PCI_SUBDEVICE_ID_COMPAQ_NC7780, TG3_PHY_ID_BCM5701 }, { TG3PCI_SUBVENDOR_ID_COMPAQ, TG3PCI_SUBDEVICE_ID_COMPAQ_NC7780_2, TG3_PHY_ID_BCM5701 }, /* IBM boards. */ { TG3PCI_SUBVENDOR_ID_IBM, TG3PCI_SUBDEVICE_ID_IBM_5703SAX2, 0 } }; static struct subsys_tbl_ent *tg3_lookup_by_subsys(struct tg3 *tp) { int i; for (i = 0; i < ARRAY_SIZE(subsys_id_to_phy_id); i++) { if ((subsys_id_to_phy_id[i].subsys_vendor == tp->pdev->subsystem_vendor) && (subsys_id_to_phy_id[i].subsys_devid == tp->pdev->subsystem_device)) return &subsys_id_to_phy_id[i]; } return NULL; } static void tg3_get_eeprom_hw_cfg(struct tg3 *tp) { u32 val; tp->phy_id = TG3_PHY_ID_INVALID; tp->led_ctrl = LED_CTRL_MODE_PHY_1; /* Assume an onboard device and WOL capable by default. */ tg3_flag_set(tp, EEPROM_WRITE_PROT); tg3_flag_set(tp, WOL_CAP); if (tg3_asic_rev(tp) == ASIC_REV_5906) { if (!(tr32(PCIE_TRANSACTION_CFG) & PCIE_TRANS_CFG_LOM)) { tg3_flag_clear(tp, EEPROM_WRITE_PROT); tg3_flag_set(tp, IS_NIC); } val = tr32(VCPU_CFGSHDW); if (val & VCPU_CFGSHDW_ASPM_DBNC) tg3_flag_set(tp, ASPM_WORKAROUND); if ((val & VCPU_CFGSHDW_WOL_ENABLE) && (val & VCPU_CFGSHDW_WOL_MAGPKT)) { tg3_flag_set(tp, WOL_ENABLE); device_set_wakeup_enable(&tp->pdev->dev, true); } goto done; } tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val); if (val == NIC_SRAM_DATA_SIG_MAGIC) { u32 nic_cfg, led_cfg; u32 nic_phy_id, ver, cfg2 = 0, cfg4 = 0, eeprom_phy_id; int eeprom_phy_serdes = 0; tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg); tp->nic_sram_data_cfg = nic_cfg; tg3_read_mem(tp, NIC_SRAM_DATA_VER, &ver); ver >>= NIC_SRAM_DATA_VER_SHIFT; if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && tg3_asic_rev(tp) != ASIC_REV_5703 && (ver > 0) && (ver < 0x100)) tg3_read_mem(tp, NIC_SRAM_DATA_CFG_2, &cfg2); if (tg3_asic_rev(tp) == ASIC_REV_5785) tg3_read_mem(tp, NIC_SRAM_DATA_CFG_4, &cfg4); if ((nic_cfg & NIC_SRAM_DATA_CFG_PHY_TYPE_MASK) == NIC_SRAM_DATA_CFG_PHY_TYPE_FIBER) eeprom_phy_serdes = 1; tg3_read_mem(tp, NIC_SRAM_DATA_PHY_ID, &nic_phy_id); if (nic_phy_id != 0) { u32 id1 = nic_phy_id & NIC_SRAM_DATA_PHY_ID1_MASK; u32 id2 = nic_phy_id & NIC_SRAM_DATA_PHY_ID2_MASK; eeprom_phy_id = (id1 >> 16) << 10; eeprom_phy_id |= (id2 & 0xfc00) << 16; eeprom_phy_id |= (id2 & 0x03ff) << 0; } else eeprom_phy_id = 0; tp->phy_id = eeprom_phy_id; if (eeprom_phy_serdes) { if (!tg3_flag(tp, 5705_PLUS)) tp->phy_flags |= TG3_PHYFLG_PHY_SERDES; else tp->phy_flags |= TG3_PHYFLG_MII_SERDES; } if (tg3_flag(tp, 5750_PLUS)) led_cfg = cfg2 & (NIC_SRAM_DATA_CFG_LED_MODE_MASK | SHASTA_EXT_LED_MODE_MASK); else led_cfg = nic_cfg & NIC_SRAM_DATA_CFG_LED_MODE_MASK; switch (led_cfg) { default: case NIC_SRAM_DATA_CFG_LED_MODE_PHY_1: tp->led_ctrl = LED_CTRL_MODE_PHY_1; break; case NIC_SRAM_DATA_CFG_LED_MODE_PHY_2: tp->led_ctrl = LED_CTRL_MODE_PHY_2; break; case NIC_SRAM_DATA_CFG_LED_MODE_MAC: tp->led_ctrl = LED_CTRL_MODE_MAC; /* Default to PHY_1_MODE if 0 (MAC_MODE) is * read on some older 5700/5701 bootcode. */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) tp->led_ctrl = LED_CTRL_MODE_PHY_1; break; case SHASTA_EXT_LED_SHARED: tp->led_ctrl = LED_CTRL_MODE_SHARED; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0 && tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A1) tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 | LED_CTRL_MODE_PHY_2); break; case SHASTA_EXT_LED_MAC: tp->led_ctrl = LED_CTRL_MODE_SHASTA_MAC; break; case SHASTA_EXT_LED_COMBO: tp->led_ctrl = LED_CTRL_MODE_COMBO; if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0) tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 | LED_CTRL_MODE_PHY_2); break; } if ((tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) && tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL) tp->led_ctrl = LED_CTRL_MODE_PHY_2; if (tg3_chip_rev(tp) == CHIPREV_5784_AX) tp->led_ctrl = LED_CTRL_MODE_PHY_1; if (nic_cfg & NIC_SRAM_DATA_CFG_EEPROM_WP) { tg3_flag_set(tp, EEPROM_WRITE_PROT); if ((tp->pdev->subsystem_vendor == PCI_VENDOR_ID_ARIMA) && (tp->pdev->subsystem_device == 0x205a || tp->pdev->subsystem_device == 0x2063)) tg3_flag_clear(tp, EEPROM_WRITE_PROT); } else { tg3_flag_clear(tp, EEPROM_WRITE_PROT); tg3_flag_set(tp, IS_NIC); } if (nic_cfg & NIC_SRAM_DATA_CFG_ASF_ENABLE) { tg3_flag_set(tp, ENABLE_ASF); if (tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, ASF_NEW_HANDSHAKE); } if ((nic_cfg & NIC_SRAM_DATA_CFG_APE_ENABLE) && tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, ENABLE_APE); if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES && !(nic_cfg & NIC_SRAM_DATA_CFG_FIBER_WOL)) tg3_flag_clear(tp, WOL_CAP); if (tg3_flag(tp, WOL_CAP) && (nic_cfg & NIC_SRAM_DATA_CFG_WOL_ENABLE)) { tg3_flag_set(tp, WOL_ENABLE); device_set_wakeup_enable(&tp->pdev->dev, true); } if (cfg2 & (1 << 17)) tp->phy_flags |= TG3_PHYFLG_CAPACITIVE_COUPLING; /* serdes signal pre-emphasis in register 0x590 set by */ /* bootcode if bit 18 is set */ if (cfg2 & (1 << 18)) tp->phy_flags |= TG3_PHYFLG_SERDES_PREEMPHASIS; if ((tg3_flag(tp, 57765_PLUS) || (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX)) && (cfg2 & NIC_SRAM_DATA_CFG_2_APD_EN)) tp->phy_flags |= TG3_PHYFLG_ENABLE_APD; if (tg3_flag(tp, PCI_EXPRESS) && tg3_asic_rev(tp) != ASIC_REV_5785 && !tg3_flag(tp, 57765_PLUS)) { u32 cfg3; tg3_read_mem(tp, NIC_SRAM_DATA_CFG_3, &cfg3); if (cfg3 & NIC_SRAM_ASPM_DEBOUNCE) tg3_flag_set(tp, ASPM_WORKAROUND); } if (cfg4 & NIC_SRAM_RGMII_INBAND_DISABLE) tg3_flag_set(tp, RGMII_INBAND_DISABLE); if (cfg4 & NIC_SRAM_RGMII_EXT_IBND_RX_EN) tg3_flag_set(tp, RGMII_EXT_IBND_RX_EN); if (cfg4 & NIC_SRAM_RGMII_EXT_IBND_TX_EN) tg3_flag_set(tp, RGMII_EXT_IBND_TX_EN); } done: if (tg3_flag(tp, WOL_CAP)) device_set_wakeup_enable(&tp->pdev->dev, tg3_flag(tp, WOL_ENABLE)); else device_set_wakeup_capable(&tp->pdev->dev, false); } static int tg3_ape_otp_read(struct tg3 *tp, u32 offset, u32 *val) { int i, err; u32 val2, off = offset * 8; err = tg3_nvram_lock(tp); if (err) return err; tg3_ape_write32(tp, TG3_APE_OTP_ADDR, off | APE_OTP_ADDR_CPU_ENABLE); tg3_ape_write32(tp, TG3_APE_OTP_CTRL, APE_OTP_CTRL_PROG_EN | APE_OTP_CTRL_CMD_RD | APE_OTP_CTRL_START); tg3_ape_read32(tp, TG3_APE_OTP_CTRL); udelay(10); for (i = 0; i < 100; i++) { val2 = tg3_ape_read32(tp, TG3_APE_OTP_STATUS); if (val2 & APE_OTP_STATUS_CMD_DONE) { *val = tg3_ape_read32(tp, TG3_APE_OTP_RD_DATA); break; } udelay(10); } tg3_ape_write32(tp, TG3_APE_OTP_CTRL, 0); tg3_nvram_unlock(tp); if (val2 & APE_OTP_STATUS_CMD_DONE) return 0; return -EBUSY; } static int tg3_issue_otp_command(struct tg3 *tp, u32 cmd) { int i; u32 val; tw32(OTP_CTRL, cmd | OTP_CTRL_OTP_CMD_START); tw32(OTP_CTRL, cmd); /* Wait for up to 1 ms for command to execute. */ for (i = 0; i < 100; i++) { val = tr32(OTP_STATUS); if (val & OTP_STATUS_CMD_DONE) break; udelay(10); } return (val & OTP_STATUS_CMD_DONE) ? 0 : -EBUSY; } /* Read the gphy configuration from the OTP region of the chip. The gphy * configuration is a 32-bit value that straddles the alignment boundary. * We do two 32-bit reads and then shift and merge the results. */ static u32 tg3_read_otp_phycfg(struct tg3 *tp) { u32 bhalf_otp, thalf_otp; tw32(OTP_MODE, OTP_MODE_OTP_THRU_GRC); if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_INIT)) return 0; tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC1); if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_READ)) return 0; thalf_otp = tr32(OTP_READ_DATA); tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC2); if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_READ)) return 0; bhalf_otp = tr32(OTP_READ_DATA); return ((thalf_otp & 0x0000ffff) << 16) | (bhalf_otp >> 16); } static void tg3_phy_init_link_config(struct tg3 *tp) { u32 adv = ADVERTISED_Autoneg; if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) adv |= ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full; if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) adv |= ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_TP; else adv |= ADVERTISED_FIBRE; tp->link_config.advertising = adv; tp->link_config.speed = SPEED_UNKNOWN; tp->link_config.duplex = DUPLEX_UNKNOWN; tp->link_config.autoneg = AUTONEG_ENABLE; tp->link_config.active_speed = SPEED_UNKNOWN; tp->link_config.active_duplex = DUPLEX_UNKNOWN; tp->old_link = -1; } static int tg3_phy_probe(struct tg3 *tp) { u32 hw_phy_id_1, hw_phy_id_2; u32 hw_phy_id, hw_phy_id_masked; int err; /* flow control autonegotiation is default behavior */ tg3_flag_set(tp, PAUSE_AUTONEG); tp->link_config.flowctrl = FLOW_CTRL_TX | FLOW_CTRL_RX; if (tg3_flag(tp, ENABLE_APE)) { switch (tp->pci_fn) { case 0: tp->phy_ape_lock = TG3_APE_LOCK_PHY0; break; case 1: tp->phy_ape_lock = TG3_APE_LOCK_PHY1; break; case 2: tp->phy_ape_lock = TG3_APE_LOCK_PHY2; break; case 3: tp->phy_ape_lock = TG3_APE_LOCK_PHY3; break; } } if (tg3_flag(tp, USE_PHYLIB)) return tg3_phy_init(tp); /* Reading the PHY ID register can conflict with ASF * firmware access to the PHY hardware. */ err = 0; if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE)) { hw_phy_id = hw_phy_id_masked = TG3_PHY_ID_INVALID; } else { /* Now read the physical PHY_ID from the chip and verify * that it is sane. If it doesn't look good, we fall back * to either the hard-coded table based PHY_ID and failing * that the value found in the eeprom area. */ err |= tg3_readphy(tp, MII_PHYSID1, &hw_phy_id_1); err |= tg3_readphy(tp, MII_PHYSID2, &hw_phy_id_2); hw_phy_id = (hw_phy_id_1 & 0xffff) << 10; hw_phy_id |= (hw_phy_id_2 & 0xfc00) << 16; hw_phy_id |= (hw_phy_id_2 & 0x03ff) << 0; hw_phy_id_masked = hw_phy_id & TG3_PHY_ID_MASK; } if (!err && TG3_KNOWN_PHY_ID(hw_phy_id_masked)) { tp->phy_id = hw_phy_id; if (hw_phy_id_masked == TG3_PHY_ID_BCM8002) tp->phy_flags |= TG3_PHYFLG_PHY_SERDES; else tp->phy_flags &= ~TG3_PHYFLG_PHY_SERDES; } else { if (tp->phy_id != TG3_PHY_ID_INVALID) { /* Do nothing, phy ID already set up in * tg3_get_eeprom_hw_cfg(). */ } else { struct subsys_tbl_ent *p; /* No eeprom signature? Try the hardcoded * subsys device table. */ p = tg3_lookup_by_subsys(tp); if (p) { tp->phy_id = p->phy_id; } else if (!tg3_flag(tp, IS_SSB_CORE)) { /* For now we saw the IDs 0xbc050cd0, * 0xbc050f80 and 0xbc050c30 on devices * connected to an BCM4785 and there are * probably more. Just assume that the phy is * supported when it is connected to a SSB core * for now. */ return -ENODEV; } if (!tp->phy_id || tp->phy_id == TG3_PHY_ID_BCM8002) tp->phy_flags |= TG3_PHYFLG_PHY_SERDES; } } if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) && (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762 || (tg3_asic_rev(tp) == ASIC_REV_5717 && tg3_chip_rev_id(tp) != CHIPREV_ID_5717_A0) || (tg3_asic_rev(tp) == ASIC_REV_57765 && tg3_chip_rev_id(tp) != CHIPREV_ID_57765_A0))) tp->phy_flags |= TG3_PHYFLG_EEE_CAP; tg3_phy_init_link_config(tp); if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) && !tg3_flag(tp, ENABLE_APE) && !tg3_flag(tp, ENABLE_ASF)) { u32 bmsr, dummy; tg3_readphy(tp, MII_BMSR, &bmsr); if (!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) goto skip_phy_reset; err = tg3_phy_reset(tp); if (err) return err; tg3_phy_set_wirespeed(tp); if (!tg3_phy_copper_an_config_ok(tp, &dummy)) { tg3_phy_autoneg_cfg(tp, tp->link_config.advertising, tp->link_config.flowctrl); tg3_writephy(tp, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART); } } skip_phy_reset: if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) { err = tg3_init_5401phy_dsp(tp); if (err) return err; err = tg3_init_5401phy_dsp(tp); } return err; } static void tg3_read_vpd(struct tg3 *tp) { u8 *vpd_data; unsigned int block_end, rosize, len; u32 vpdlen; int j, i = 0; vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen); if (!vpd_data) goto out_no_vpd; i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA); if (i < 0) goto out_not_found; rosize = pci_vpd_lrdt_size(&vpd_data[i]); block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize; i += PCI_VPD_LRDT_TAG_SIZE; if (block_end > vpdlen) goto out_not_found; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_MFR_ID); if (j > 0) { len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end || len != 4 || memcmp(&vpd_data[j], "1028", 4)) goto partno; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_VENDOR0); if (j < 0) goto partno; len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end) goto partno; if (len >= sizeof(tp->fw_ver)) len = sizeof(tp->fw_ver) - 1; memset(tp->fw_ver, 0, sizeof(tp->fw_ver)); snprintf(tp->fw_ver, sizeof(tp->fw_ver), "%.*s bc ", len, &vpd_data[j]); } partno: i = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_PARTNO); if (i < 0) goto out_not_found; len = pci_vpd_info_field_size(&vpd_data[i]); i += PCI_VPD_INFO_FLD_HDR_SIZE; if (len > TG3_BPN_SIZE || (len + i) > vpdlen) goto out_not_found; memcpy(tp->board_part_number, &vpd_data[i], len); out_not_found: kfree(vpd_data); if (tp->board_part_number[0]) return; out_no_vpd: if (tg3_asic_rev(tp) == ASIC_REV_5717) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C) strcpy(tp->board_part_number, "BCM5717"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718) strcpy(tp->board_part_number, "BCM5718"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57780) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780) strcpy(tp->board_part_number, "BCM57780"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760) strcpy(tp->board_part_number, "BCM57760"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790) strcpy(tp->board_part_number, "BCM57790"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788) strcpy(tp->board_part_number, "BCM57788"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57765) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761) strcpy(tp->board_part_number, "BCM57761"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765) strcpy(tp->board_part_number, "BCM57765"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781) strcpy(tp->board_part_number, "BCM57781"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785) strcpy(tp->board_part_number, "BCM57785"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791) strcpy(tp->board_part_number, "BCM57791"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795) strcpy(tp->board_part_number, "BCM57795"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762) strcpy(tp->board_part_number, "BCM57762"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766) strcpy(tp->board_part_number, "BCM57766"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782) strcpy(tp->board_part_number, "BCM57782"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786) strcpy(tp->board_part_number, "BCM57786"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) { strcpy(tp->board_part_number, "BCM95906"); } else { nomatch: strcpy(tp->board_part_number, "none"); } } static int tg3_fw_img_is_valid(struct tg3 *tp, u32 offset) { u32 val; if (tg3_nvram_read(tp, offset, &val) || (val & 0xfc000000) != 0x0c000000 || tg3_nvram_read(tp, offset + 4, &val) || val != 0) return 0; return 1; } static void tg3_read_bc_ver(struct tg3 *tp) { u32 val, offset, start, ver_offset; int i, dst_off; bool newver = false; if (tg3_nvram_read(tp, 0xc, &offset) || tg3_nvram_read(tp, 0x4, &start)) return; offset = tg3_nvram_logical_addr(tp, offset); if (tg3_nvram_read(tp, offset, &val)) return; if ((val & 0xfc000000) == 0x0c000000) { if (tg3_nvram_read(tp, offset + 4, &val)) return; if (val == 0) newver = true; } dst_off = strlen(tp->fw_ver); if (newver) { if (TG3_VER_SIZE - dst_off < 16 || tg3_nvram_read(tp, offset + 8, &ver_offset)) return; offset = offset + ver_offset - start; for (i = 0; i < 16; i += 4) { __be32 v; if (tg3_nvram_read_be32(tp, offset + i, &v)) return; memcpy(tp->fw_ver + dst_off + i, &v, sizeof(v)); } } else { u32 major, minor; if (tg3_nvram_read(tp, TG3_NVM_PTREV_BCVER, &ver_offset)) return; major = (ver_offset & TG3_NVM_BCVER_MAJMSK) >> TG3_NVM_BCVER_MAJSFT; minor = ver_offset & TG3_NVM_BCVER_MINMSK; snprintf(&tp->fw_ver[dst_off], TG3_VER_SIZE - dst_off, "v%d.%02d", major, minor); } } static void tg3_read_hwsb_ver(struct tg3 *tp) { u32 val, major, minor; /* Use native endian representation */ if (tg3_nvram_read(tp, TG3_NVM_HWSB_CFG1, &val)) return; major = (val & TG3_NVM_HWSB_CFG1_MAJMSK) >> TG3_NVM_HWSB_CFG1_MAJSFT; minor = (val & TG3_NVM_HWSB_CFG1_MINMSK) >> TG3_NVM_HWSB_CFG1_MINSFT; snprintf(&tp->fw_ver[0], 32, "sb v%d.%02d", major, minor); } static void tg3_read_sb_ver(struct tg3 *tp, u32 val) { u32 offset, major, minor, build; strncat(tp->fw_ver, "sb", TG3_VER_SIZE - strlen(tp->fw_ver) - 1); if ((val & TG3_EEPROM_SB_FORMAT_MASK) != TG3_EEPROM_SB_FORMAT_1) return; switch (val & TG3_EEPROM_SB_REVISION_MASK) { case TG3_EEPROM_SB_REVISION_0: offset = TG3_EEPROM_SB_F1R0_EDH_OFF; break; case TG3_EEPROM_SB_REVISION_2: offset = TG3_EEPROM_SB_F1R2_EDH_OFF; break; case TG3_EEPROM_SB_REVISION_3: offset = TG3_EEPROM_SB_F1R3_EDH_OFF; break; case TG3_EEPROM_SB_REVISION_4: offset = TG3_EEPROM_SB_F1R4_EDH_OFF; break; case TG3_EEPROM_SB_REVISION_5: offset = TG3_EEPROM_SB_F1R5_EDH_OFF; break; case TG3_EEPROM_SB_REVISION_6: offset = TG3_EEPROM_SB_F1R6_EDH_OFF; break; default: return; } if (tg3_nvram_read(tp, offset, &val)) return; build = (val & TG3_EEPROM_SB_EDH_BLD_MASK) >> TG3_EEPROM_SB_EDH_BLD_SHFT; major = (val & TG3_EEPROM_SB_EDH_MAJ_MASK) >> TG3_EEPROM_SB_EDH_MAJ_SHFT; minor = val & TG3_EEPROM_SB_EDH_MIN_MASK; if (minor > 99 || build > 26) return; offset = strlen(tp->fw_ver); snprintf(&tp->fw_ver[offset], TG3_VER_SIZE - offset, " v%d.%02d", major, minor); if (build > 0) { offset = strlen(tp->fw_ver); if (offset < TG3_VER_SIZE - 1) tp->fw_ver[offset] = 'a' + build - 1; } } static void tg3_read_mgmtfw_ver(struct tg3 *tp) { u32 val, offset, start; int i, vlen; for (offset = TG3_NVM_DIR_START; offset < TG3_NVM_DIR_END; offset += TG3_NVM_DIRENT_SIZE) { if (tg3_nvram_read(tp, offset, &val)) return; if ((val >> TG3_NVM_DIRTYPE_SHIFT) == TG3_NVM_DIRTYPE_ASFINI) break; } if (offset == TG3_NVM_DIR_END) return; if (!tg3_flag(tp, 5705_PLUS)) start = 0x08000000; else if (tg3_nvram_read(tp, offset - 4, &start)) return; if (tg3_nvram_read(tp, offset + 4, &offset) || !tg3_fw_img_is_valid(tp, offset) || tg3_nvram_read(tp, offset + 8, &val)) return; offset += val - start; vlen = strlen(tp->fw_ver); tp->fw_ver[vlen++] = ','; tp->fw_ver[vlen++] = ' '; for (i = 0; i < 4; i++) { __be32 v; if (tg3_nvram_read_be32(tp, offset, &v)) return; offset += sizeof(v); if (vlen > TG3_VER_SIZE - sizeof(v)) { memcpy(&tp->fw_ver[vlen], &v, TG3_VER_SIZE - vlen); break; } memcpy(&tp->fw_ver[vlen], &v, sizeof(v)); vlen += sizeof(v); } } static void tg3_probe_ncsi(struct tg3 *tp) { u32 apedata; apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG); if (apedata != APE_SEG_SIG_MAGIC) return; apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS); if (!(apedata & APE_FW_STATUS_READY)) return; if (tg3_ape_read32(tp, TG3_APE_FW_FEATURES) & TG3_APE_FW_FEATURE_NCSI) tg3_flag_set(tp, APE_HAS_NCSI); } static void tg3_read_dash_ver(struct tg3 *tp) { int vlen; u32 apedata; char *fwtype; apedata = tg3_ape_read32(tp, TG3_APE_FW_VERSION); if (tg3_flag(tp, APE_HAS_NCSI)) fwtype = "NCSI"; else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5725) fwtype = "SMASH"; else fwtype = "DASH"; vlen = strlen(tp->fw_ver); snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " %s v%d.%d.%d.%d", fwtype, (apedata & APE_FW_VERSION_MAJMSK) >> APE_FW_VERSION_MAJSFT, (apedata & APE_FW_VERSION_MINMSK) >> APE_FW_VERSION_MINSFT, (apedata & APE_FW_VERSION_REVMSK) >> APE_FW_VERSION_REVSFT, (apedata & APE_FW_VERSION_BLDMSK)); } static void tg3_read_otp_ver(struct tg3 *tp) { u32 val, val2; if (tg3_asic_rev(tp) != ASIC_REV_5762) return; if (!tg3_ape_otp_read(tp, OTP_ADDRESS_MAGIC0, &val) && !tg3_ape_otp_read(tp, OTP_ADDRESS_MAGIC0 + 4, &val2) && TG3_OTP_MAGIC0_VALID(val)) { u64 val64 = (u64) val << 32 | val2; u32 ver = 0; int i, vlen; for (i = 0; i < 7; i++) { if ((val64 & 0xff) == 0) break; ver = val64 & 0xff; val64 >>= 8; } vlen = strlen(tp->fw_ver); snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " .%02d", ver); } } static void tg3_read_fw_ver(struct tg3 *tp) { u32 val; bool vpd_vers = false; if (tp->fw_ver[0] != 0) vpd_vers = true; if (tg3_flag(tp, NO_NVRAM)) { strcat(tp->fw_ver, "sb"); tg3_read_otp_ver(tp); return; } if (tg3_nvram_read(tp, 0, &val)) return; if (val == TG3_EEPROM_MAGIC) tg3_read_bc_ver(tp); else if ((val & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW) tg3_read_sb_ver(tp, val); else if ((val & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW) tg3_read_hwsb_ver(tp); if (tg3_flag(tp, ENABLE_ASF)) { if (tg3_flag(tp, ENABLE_APE)) { tg3_probe_ncsi(tp); if (!vpd_vers) tg3_read_dash_ver(tp); } else if (!vpd_vers) { tg3_read_mgmtfw_ver(tp); } } tp->fw_ver[TG3_VER_SIZE - 1] = 0; } static inline u32 tg3_rx_ret_ring_size(struct tg3 *tp) { if (tg3_flag(tp, LRG_PROD_RING_CAP)) return TG3_RX_RET_MAX_SIZE_5717; else if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) return TG3_RX_RET_MAX_SIZE_5700; else return TG3_RX_RET_MAX_SIZE_5705; } static DEFINE_PCI_DEVICE_TABLE(tg3_write_reorder_chipsets) = { { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C) }, { PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE) }, { PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8385_0) }, { }, }; static struct pci_dev *tg3_find_peer(struct tg3 *tp) { struct pci_dev *peer; unsigned int func, devnr = tp->pdev->devfn & ~7; for (func = 0; func < 8; func++) { peer = pci_get_slot(tp->pdev->bus, devnr | func); if (peer && peer != tp->pdev) break; pci_dev_put(peer); } /* 5704 can be configured in single-port mode, set peer to * tp->pdev in that case. */ if (!peer) { peer = tp->pdev; return peer; } /* * We don't need to keep the refcount elevated; there's no way * to remove one half of this device without removing the other */ pci_dev_put(peer); return peer; } static void tg3_detect_asic_rev(struct tg3 *tp, u32 misc_ctrl_reg) { tp->pci_chip_rev_id = misc_ctrl_reg >> MISC_HOST_CTRL_CHIPREV_SHIFT; if (tg3_asic_rev(tp) == ASIC_REV_USE_PROD_ID_REG) { u32 reg; /* All devices that use the alternate * ASIC REV location have a CPMU. */ tg3_flag_set(tp, CPMU_PRESENT); if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5719 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5720 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5762 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5725 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5727) reg = TG3PCI_GEN2_PRODID_ASICREV; else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786) reg = TG3PCI_GEN15_PRODID_ASICREV; else reg = TG3PCI_PRODID_ASICREV; pci_read_config_dword(tp->pdev, reg, &tp->pci_chip_rev_id); } /* Wrong chip ID in 5752 A0. This code can be removed later * as A0 is not in production. */ if (tg3_chip_rev_id(tp) == CHIPREV_ID_5752_A0_HW) tp->pci_chip_rev_id = CHIPREV_ID_5752_A0; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5717_C0) tp->pci_chip_rev_id = CHIPREV_ID_5720_A0; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) tg3_flag_set(tp, 5717_PLUS); if (tg3_asic_rev(tp) == ASIC_REV_57765 || tg3_asic_rev(tp) == ASIC_REV_57766) tg3_flag_set(tp, 57765_CLASS); if (tg3_flag(tp, 57765_CLASS) || tg3_flag(tp, 5717_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_flag_set(tp, 57765_PLUS); /* Intentionally exclude ASIC_REV_5906 */ if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5787 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5761 || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_PLUS)) tg3_flag_set(tp, 5755_PLUS); if (tg3_asic_rev(tp) == ASIC_REV_5780 || tg3_asic_rev(tp) == ASIC_REV_5714) tg3_flag_set(tp, 5780_CLASS); if (tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_asic_rev(tp) == ASIC_REV_5906 || tg3_flag(tp, 5755_PLUS) || tg3_flag(tp, 5780_CLASS)) tg3_flag_set(tp, 5750_PLUS); if (tg3_asic_rev(tp) == ASIC_REV_5705 || tg3_flag(tp, 5750_PLUS)) tg3_flag_set(tp, 5705_PLUS); } static bool tg3_10_100_only_device(struct tg3 *tp, const struct pci_device_id *ent) { u32 grc_misc_cfg = tr32(GRC_MISC_CFG) & GRC_MISC_CFG_BOARD_ID_MASK; if ((tg3_asic_rev(tp) == ASIC_REV_5703 && (grc_misc_cfg == 0x8000 || grc_misc_cfg == 0x4000)) || (tp->phy_flags & TG3_PHYFLG_IS_FET)) return true; if (ent->driver_data & TG3_DRV_DATA_FLAG_10_100_ONLY) { if (tg3_asic_rev(tp) == ASIC_REV_5705) { if (ent->driver_data & TG3_DRV_DATA_FLAG_5705_10_100) return true; } else { return true; } } return false; } static int tg3_get_invariants(struct tg3 *tp, const struct pci_device_id *ent) { u32 misc_ctrl_reg; u32 pci_state_reg, grc_misc_cfg; u32 val; u16 pci_cmd; int err; /* Force memory write invalidate off. If we leave it on, * then on 5700_BX chips we have to enable a workaround. * The workaround is to set the TG3PCI_DMA_RW_CTRL boundary * to match the cacheline size. The Broadcom driver have this * workaround but turns MWI off all the times so never uses * it. This seems to suggest that the workaround is insufficient. */ pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd); pci_cmd &= ~PCI_COMMAND_INVALIDATE; pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd); /* Important! -- Make sure register accesses are byteswapped * correctly. Also, for those chips that require it, make * sure that indirect register accesses are enabled before * the first operation. */ pci_read_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL, &misc_ctrl_reg); tp->misc_host_ctrl |= (misc_ctrl_reg & MISC_HOST_CTRL_CHIPREV); pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL, tp->misc_host_ctrl); tg3_detect_asic_rev(tp, misc_ctrl_reg); /* If we have 5702/03 A1 or A2 on certain ICH chipsets, * we need to disable memory and use config. cycles * only to access all registers. The 5702/03 chips * can mistakenly decode the special cycles from the * ICH chipsets as memory write cycles, causing corruption * of register and memory space. Only certain ICH bridges * will drive special cycles with non-zero data during the * address phase which can fall within the 5703's address * range. This is not an ICH bug as the PCI spec allows * non-zero address during special cycles. However, only * these ICH bridges are known to drive non-zero addresses * during special cycles. * * Since special cycles do not cross PCI bridges, we only * enable this workaround if the 5703 is on the secondary * bus of these ICH bridges. */ if ((tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A1) || (tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A2)) { static struct tg3_dev_id { u32 vendor; u32 device; u32 rev; } ich_chipsets[] = { { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_8, PCI_ANY_ID }, { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AB_8, PCI_ANY_ID }, { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_11, 0xa }, { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_6, PCI_ANY_ID }, { }, }; struct tg3_dev_id *pci_id = &ich_chipsets[0]; struct pci_dev *bridge = NULL; while (pci_id->vendor != 0) { bridge = pci_get_device(pci_id->vendor, pci_id->device, bridge); if (!bridge) { pci_id++; continue; } if (pci_id->rev != PCI_ANY_ID) { if (bridge->revision > pci_id->rev) continue; } if (bridge->subordinate && (bridge->subordinate->number == tp->pdev->bus->number)) { tg3_flag_set(tp, ICH_WORKAROUND); pci_dev_put(bridge); break; } } } if (tg3_asic_rev(tp) == ASIC_REV_5701) { static struct tg3_dev_id { u32 vendor; u32 device; } bridge_chipsets[] = { { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0 }, { PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1 }, { }, }; struct tg3_dev_id *pci_id = &bridge_chipsets[0]; struct pci_dev *bridge = NULL; while (pci_id->vendor != 0) { bridge = pci_get_device(pci_id->vendor, pci_id->device, bridge); if (!bridge) { pci_id++; continue; } if (bridge->subordinate && (bridge->subordinate->number <= tp->pdev->bus->number) && (bridge->subordinate->busn_res.end >= tp->pdev->bus->number)) { tg3_flag_set(tp, 5701_DMA_BUG); pci_dev_put(bridge); break; } } } /* The EPB bridge inside 5714, 5715, and 5780 cannot support * DMA addresses > 40-bit. This bridge may have other additional * 57xx devices behind it in some 4-port NIC designs for example. * Any tg3 device found behind the bridge will also need the 40-bit * DMA workaround. */ if (tg3_flag(tp, 5780_CLASS)) { tg3_flag_set(tp, 40BIT_DMA_BUG); tp->msi_cap = pci_find_capability(tp->pdev, PCI_CAP_ID_MSI); } else { struct pci_dev *bridge = NULL; do { bridge = pci_get_device(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_EPB, bridge); if (bridge && bridge->subordinate && (bridge->subordinate->number <= tp->pdev->bus->number) && (bridge->subordinate->busn_res.end >= tp->pdev->bus->number)) { tg3_flag_set(tp, 40BIT_DMA_BUG); pci_dev_put(bridge); break; } } while (bridge); } if (tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_asic_rev(tp) == ASIC_REV_5714) tp->pdev_peer = tg3_find_peer(tp); /* Determine TSO capabilities */ if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0) ; /* Do nothing. HW bug. */ else if (tg3_flag(tp, 57765_PLUS)) tg3_flag_set(tp, HW_TSO_3); else if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) tg3_flag_set(tp, HW_TSO_2); else if (tg3_flag(tp, 5750_PLUS)) { tg3_flag_set(tp, HW_TSO_1); tg3_flag_set(tp, TSO_BUG); if (tg3_asic_rev(tp) == ASIC_REV_5750 && tg3_chip_rev_id(tp) >= CHIPREV_ID_5750_C2) tg3_flag_clear(tp, TSO_BUG); } else if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) { tg3_flag_set(tp, TSO_BUG); if (tg3_asic_rev(tp) == ASIC_REV_5705) tp->fw_needed = FIRMWARE_TG3TSO5; else tp->fw_needed = FIRMWARE_TG3TSO; } /* Selectively allow TSO based on operating conditions */ if (tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3) || tp->fw_needed) { /* For firmware TSO, assume ASF is disabled. * We'll disable TSO later if we discover ASF * is enabled in tg3_get_eeprom_hw_cfg(). */ tg3_flag_set(tp, TSO_CAPABLE); } else { tg3_flag_clear(tp, TSO_CAPABLE); tg3_flag_clear(tp, TSO_BUG); tp->fw_needed = NULL; } if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) tp->fw_needed = FIRMWARE_TG3; tp->irq_max = 1; if (tg3_flag(tp, 5750_PLUS)) { tg3_flag_set(tp, SUPPORT_MSI); if (tg3_chip_rev(tp) == CHIPREV_5750_AX || tg3_chip_rev(tp) == CHIPREV_5750_BX || (tg3_asic_rev(tp) == ASIC_REV_5714 && tg3_chip_rev_id(tp) <= CHIPREV_ID_5714_A2 && tp->pdev_peer == tp->pdev)) tg3_flag_clear(tp, SUPPORT_MSI); if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) { tg3_flag_set(tp, 1SHOT_MSI); } if (tg3_flag(tp, 57765_PLUS)) { tg3_flag_set(tp, SUPPORT_MSIX); tp->irq_max = TG3_IRQ_MAX_VECS; } } tp->txq_max = 1; tp->rxq_max = 1; if (tp->irq_max > 1) { tp->rxq_max = TG3_RSS_MAX_NUM_QS; tg3_rss_init_dflt_indir_tbl(tp, TG3_RSS_MAX_NUM_QS); if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) tp->txq_max = tp->irq_max - 1; } if (tg3_flag(tp, 5755_PLUS) || tg3_asic_rev(tp) == ASIC_REV_5906) tg3_flag_set(tp, SHORT_DMA_BUG); if (tg3_asic_rev(tp) == ASIC_REV_5719) tp->dma_limit = TG3_TX_BD_DMA_MAX_4K; if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_flag_set(tp, LRG_PROD_RING_CAP); if (tg3_flag(tp, 57765_PLUS) && tg3_chip_rev_id(tp) != CHIPREV_ID_5719_A0) tg3_flag_set(tp, USE_JUMBO_BDFLAG); if (!tg3_flag(tp, 5705_PLUS) || tg3_flag(tp, 5780_CLASS) || tg3_flag(tp, USE_JUMBO_BDFLAG)) tg3_flag_set(tp, JUMBO_CAPABLE); pci_read_config_dword(tp->pdev, TG3PCI_PCISTATE, &pci_state_reg); if (pci_is_pcie(tp->pdev)) { u16 lnkctl; tg3_flag_set(tp, PCI_EXPRESS); pcie_capability_read_word(tp->pdev, PCI_EXP_LNKCTL, &lnkctl); if (lnkctl & PCI_EXP_LNKCTL_CLKREQ_EN) { if (tg3_asic_rev(tp) == ASIC_REV_5906) { tg3_flag_clear(tp, HW_TSO_2); tg3_flag_clear(tp, TSO_CAPABLE); } if (tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5761 || tg3_chip_rev_id(tp) == CHIPREV_ID_57780_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_57780_A1) tg3_flag_set(tp, CLKREQ_BUG); } else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5717_A0) { tg3_flag_set(tp, L1PLLPD_EN); } } else if (tg3_asic_rev(tp) == ASIC_REV_5785) { /* BCM5785 devices are effectively PCIe devices, and should * follow PCIe codepaths, but do not have a PCIe capabilities * section. */ tg3_flag_set(tp, PCI_EXPRESS); } else if (!tg3_flag(tp, 5705_PLUS) || tg3_flag(tp, 5780_CLASS)) { tp->pcix_cap = pci_find_capability(tp->pdev, PCI_CAP_ID_PCIX); if (!tp->pcix_cap) { dev_err(&tp->pdev->dev, "Cannot find PCI-X capability, aborting\n"); return -EIO; } if (!(pci_state_reg & PCISTATE_CONV_PCI_MODE)) tg3_flag_set(tp, PCIX_MODE); } /* If we have an AMD 762 or VIA K8T800 chipset, write * reordering to the mailbox registers done by the host * controller can cause major troubles. We read back from * every mailbox register write to force the writes to be * posted to the chip in order. */ if (pci_dev_present(tg3_write_reorder_chipsets) && !tg3_flag(tp, PCI_EXPRESS)) tg3_flag_set(tp, MBOX_WRITE_REORDER); pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE, &tp->pci_cacheline_sz); pci_read_config_byte(tp->pdev, PCI_LATENCY_TIMER, &tp->pci_lat_timer); if (tg3_asic_rev(tp) == ASIC_REV_5703 && tp->pci_lat_timer < 64) { tp->pci_lat_timer = 64; pci_write_config_byte(tp->pdev, PCI_LATENCY_TIMER, tp->pci_lat_timer); } /* Important! -- It is critical that the PCI-X hw workaround * situation is decided before the first MMIO register access. */ if (tg3_chip_rev(tp) == CHIPREV_5700_BX) { /* 5700 BX chips need to have their TX producer index * mailboxes written twice to workaround a bug. */ tg3_flag_set(tp, TXD_MBOX_HWBUG); /* If we are in PCI-X mode, enable register write workaround. * * The workaround is to use indirect register accesses * for all chip writes not to mailbox registers. */ if (tg3_flag(tp, PCIX_MODE)) { u32 pm_reg; tg3_flag_set(tp, PCIX_TARGET_HWBUG); /* The chip can have it's power management PCI config * space registers clobbered due to this bug. * So explicitly force the chip into D0 here. */ pci_read_config_dword(tp->pdev, tp->pm_cap + PCI_PM_CTRL, &pm_reg); pm_reg &= ~PCI_PM_CTRL_STATE_MASK; pm_reg |= PCI_PM_CTRL_PME_ENABLE | 0 /* D0 */; pci_write_config_dword(tp->pdev, tp->pm_cap + PCI_PM_CTRL, pm_reg); /* Also, force SERR#/PERR# in PCI command. */ pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd); pci_cmd |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR; pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd); } } if ((pci_state_reg & PCISTATE_BUS_SPEED_HIGH) != 0) tg3_flag_set(tp, PCI_HIGH_SPEED); if ((pci_state_reg & PCISTATE_BUS_32BIT) != 0) tg3_flag_set(tp, PCI_32BIT); /* Chip-specific fixup from Broadcom driver */ if ((tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0) && (!(pci_state_reg & PCISTATE_RETRY_SAME_DMA))) { pci_state_reg |= PCISTATE_RETRY_SAME_DMA; pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, pci_state_reg); } /* Default fast path register access methods */ tp->read32 = tg3_read32; tp->write32 = tg3_write32; tp->read32_mbox = tg3_read32; tp->write32_mbox = tg3_write32; tp->write32_tx_mbox = tg3_write32; tp->write32_rx_mbox = tg3_write32; /* Various workaround register access methods */ if (tg3_flag(tp, PCIX_TARGET_HWBUG)) tp->write32 = tg3_write_indirect_reg32; else if (tg3_asic_rev(tp) == ASIC_REV_5701 || (tg3_flag(tp, PCI_EXPRESS) && tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A0)) { /* * Back to back register writes can cause problems on these * chips, the workaround is to read back all reg writes * except those to mailbox regs. * * See tg3_write_indirect_reg32(). */ tp->write32 = tg3_write_flush_reg32; } if (tg3_flag(tp, TXD_MBOX_HWBUG) || tg3_flag(tp, MBOX_WRITE_REORDER)) { tp->write32_tx_mbox = tg3_write32_tx_mbox; if (tg3_flag(tp, MBOX_WRITE_REORDER)) tp->write32_rx_mbox = tg3_write_flush_reg32; } if (tg3_flag(tp, ICH_WORKAROUND)) { tp->read32 = tg3_read_indirect_reg32; tp->write32 = tg3_write_indirect_reg32; tp->read32_mbox = tg3_read_indirect_mbox; tp->write32_mbox = tg3_write_indirect_mbox; tp->write32_tx_mbox = tg3_write_indirect_mbox; tp->write32_rx_mbox = tg3_write_indirect_mbox; iounmap(tp->regs); tp->regs = NULL; pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd); pci_cmd &= ~PCI_COMMAND_MEMORY; pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd); } if (tg3_asic_rev(tp) == ASIC_REV_5906) { tp->read32_mbox = tg3_read32_mbox_5906; tp->write32_mbox = tg3_write32_mbox_5906; tp->write32_tx_mbox = tg3_write32_mbox_5906; tp->write32_rx_mbox = tg3_write32_mbox_5906; } if (tp->write32 == tg3_write_indirect_reg32 || (tg3_flag(tp, PCIX_MODE) && (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701))) tg3_flag_set(tp, SRAM_USE_CONFIG); /* The memory arbiter has to be enabled in order for SRAM accesses * to succeed. Normally on powerup the tg3 chip firmware will make * sure it is enabled, but other entities such as system netboot * code might disable it. */ val = tr32(MEMARB_MODE); tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE); tp->pci_fn = PCI_FUNC(tp->pdev->devfn) & 3; if (tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_flag(tp, 5780_CLASS)) { if (tg3_flag(tp, PCIX_MODE)) { pci_read_config_dword(tp->pdev, tp->pcix_cap + PCI_X_STATUS, &val); tp->pci_fn = val & 0x7; } } else if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720) { tg3_read_mem(tp, NIC_SRAM_CPMU_STATUS, &val); if ((val & NIC_SRAM_CPMUSTAT_SIG_MSK) != NIC_SRAM_CPMUSTAT_SIG) val = tr32(TG3_CPMU_STATUS); if (tg3_asic_rev(tp) == ASIC_REV_5717) tp->pci_fn = (val & TG3_CPMU_STATUS_FMSK_5717) ? 1 : 0; else tp->pci_fn = (val & TG3_CPMU_STATUS_FMSK_5719) >> TG3_CPMU_STATUS_FSHFT_5719; } if (tg3_flag(tp, FLUSH_POSTED_WRITES)) { tp->write32_tx_mbox = tg3_write_flush_reg32; tp->write32_rx_mbox = tg3_write_flush_reg32; } /* Get eeprom hw config before calling tg3_set_power_state(). * In particular, the TG3_FLAG_IS_NIC flag must be * determined before calling tg3_set_power_state() so that * we know whether or not to switch out of Vaux power. * When the flag is set, it means that GPIO1 is used for eeprom * write protect and also implies that it is a LOM where GPIOs * are not used to switch power. */ tg3_get_eeprom_hw_cfg(tp); if (tp->fw_needed && tg3_flag(tp, ENABLE_ASF)) { tg3_flag_clear(tp, TSO_CAPABLE); tg3_flag_clear(tp, TSO_BUG); tp->fw_needed = NULL; } if (tg3_flag(tp, ENABLE_APE)) { /* Allow reads and writes to the * APE register and memory space. */ pci_state_reg |= PCISTATE_ALLOW_APE_CTLSPC_WR | PCISTATE_ALLOW_APE_SHMEM_WR | PCISTATE_ALLOW_APE_PSPACE_WR; pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, pci_state_reg); tg3_ape_lock_init(tp); } /* Set up tp->grc_local_ctrl before calling * tg3_pwrsrc_switch_to_vmain(). GPIO1 driven high * will bring 5700's external PHY out of reset. * It is also used as eeprom write protect on LOMs. */ tp->grc_local_ctrl = GRC_LCLCTRL_INT_ON_ATTN | GRC_LCLCTRL_AUTO_SEEPROM; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_flag(tp, EEPROM_WRITE_PROT)) tp->grc_local_ctrl |= (GRC_LCLCTRL_GPIO_OE1 | GRC_LCLCTRL_GPIO_OUTPUT1); /* Unused GPIO3 must be driven as output on 5752 because there * are no pull-up resistors on unused GPIO pins. */ else if (tg3_asic_rev(tp) == ASIC_REV_5752) tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE3; if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_57780 || tg3_flag(tp, 57765_CLASS)) tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_UART_SEL; if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S) { /* Turn off the debug UART. */ tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_UART_SEL; if (tg3_flag(tp, IS_NIC)) /* Keep VMain power. */ tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OUTPUT0; } if (tg3_asic_rev(tp) == ASIC_REV_5762) tp->grc_local_ctrl |= tr32(GRC_LOCAL_CTRL) & GRC_LCLCTRL_GPIO_UART_SEL; /* Switch out of Vaux if it is a NIC */ tg3_pwrsrc_switch_to_vmain(tp); /* Derive initial jumbo mode from MTU assigned in * ether_setup() via the alloc_etherdev() call */ if (tp->dev->mtu > ETH_DATA_LEN && !tg3_flag(tp, 5780_CLASS)) tg3_flag_set(tp, JUMBO_RING_ENABLE); /* Determine WakeOnLan speed to use. */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B2) { tg3_flag_clear(tp, WOL_SPEED_100MB); } else { tg3_flag_set(tp, WOL_SPEED_100MB); } if (tg3_asic_rev(tp) == ASIC_REV_5906) tp->phy_flags |= TG3_PHYFLG_IS_FET; /* A few boards don't want Ethernet@WireSpeed phy feature */ if (tg3_asic_rev(tp) == ASIC_REV_5700 || (tg3_asic_rev(tp) == ASIC_REV_5705 && (tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) && (tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A1)) || (tp->phy_flags & TG3_PHYFLG_IS_FET) || (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) tp->phy_flags |= TG3_PHYFLG_NO_ETH_WIRE_SPEED; if (tg3_chip_rev(tp) == CHIPREV_5703_AX || tg3_chip_rev(tp) == CHIPREV_5704_AX) tp->phy_flags |= TG3_PHYFLG_ADC_BUG; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0) tp->phy_flags |= TG3_PHYFLG_5704_A0_BUG; if (tg3_flag(tp, 5705_PLUS) && !(tp->phy_flags & TG3_PHYFLG_IS_FET) && tg3_asic_rev(tp) != ASIC_REV_5785 && tg3_asic_rev(tp) != ASIC_REV_57780 && !tg3_flag(tp, 57765_PLUS)) { if (tg3_asic_rev(tp) == ASIC_REV_5755 || tg3_asic_rev(tp) == ASIC_REV_5787 || tg3_asic_rev(tp) == ASIC_REV_5784 || tg3_asic_rev(tp) == ASIC_REV_5761) { if (tp->pdev->device != PCI_DEVICE_ID_TIGON3_5756 && tp->pdev->device != PCI_DEVICE_ID_TIGON3_5722) tp->phy_flags |= TG3_PHYFLG_JITTER_BUG; if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5755M) tp->phy_flags |= TG3_PHYFLG_ADJUST_TRIM; } else tp->phy_flags |= TG3_PHYFLG_BER_BUG; } if (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX) { tp->phy_otp = tg3_read_otp_phycfg(tp); if (tp->phy_otp == 0) tp->phy_otp = TG3_OTP_DEFAULT; } if (tg3_flag(tp, CPMU_PRESENT)) tp->mi_mode = MAC_MI_MODE_500KHZ_CONST; else tp->mi_mode = MAC_MI_MODE_BASE; tp->coalesce_mode = 0; if (tg3_chip_rev(tp) != CHIPREV_5700_AX && tg3_chip_rev(tp) != CHIPREV_5700_BX) tp->coalesce_mode |= HOSTCC_MODE_32BYTE; /* Set these bits to enable statistics workaround. */ if (tg3_asic_rev(tp) == ASIC_REV_5717 || tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5720_A0) { tp->coalesce_mode |= HOSTCC_MODE_ATTN; tp->grc_mode |= GRC_MODE_IRQ_ON_FLOW_ATTN; } if (tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) tg3_flag_set(tp, USE_PHYLIB); err = tg3_mdio_init(tp); if (err) return err; /* Initialize data/descriptor byte/word swapping. */ val = tr32(GRC_MODE); if (tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) val &= (GRC_MODE_BYTE_SWAP_B2HRX_DATA | GRC_MODE_WORD_SWAP_B2HRX_DATA | GRC_MODE_B2HRX_ENABLE | GRC_MODE_HTX2B_ENABLE | GRC_MODE_HOST_STACKUP); else val &= GRC_MODE_HOST_STACKUP; tw32(GRC_MODE, val | tp->grc_mode); tg3_switch_clocks(tp); /* Clear this out for sanity. */ tw32(TG3PCI_MEM_WIN_BASE_ADDR, 0); pci_read_config_dword(tp->pdev, TG3PCI_PCISTATE, &pci_state_reg); if ((pci_state_reg & PCISTATE_CONV_PCI_MODE) == 0 && !tg3_flag(tp, PCIX_TARGET_HWBUG)) { if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B2 || tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B5) { void __iomem *sram_base; /* Write some dummy words into the SRAM status block * area, see if it reads back correctly. If the return * value is bad, force enable the PCIX workaround. */ sram_base = tp->regs + NIC_SRAM_WIN_BASE + NIC_SRAM_STATS_BLK; writel(0x00000000, sram_base); writel(0x00000000, sram_base + 4); writel(0xffffffff, sram_base + 4); if (readl(sram_base) != 0x00000000) tg3_flag_set(tp, PCIX_TARGET_HWBUG); } } udelay(50); tg3_nvram_init(tp); grc_misc_cfg = tr32(GRC_MISC_CFG); grc_misc_cfg &= GRC_MISC_CFG_BOARD_ID_MASK; if (tg3_asic_rev(tp) == ASIC_REV_5705 && (grc_misc_cfg == GRC_MISC_CFG_BOARD_ID_5788 || grc_misc_cfg == GRC_MISC_CFG_BOARD_ID_5788M)) tg3_flag_set(tp, IS_5788); if (!tg3_flag(tp, IS_5788) && tg3_asic_rev(tp) != ASIC_REV_5700) tg3_flag_set(tp, TAGGED_STATUS); if (tg3_flag(tp, TAGGED_STATUS)) { tp->coalesce_mode |= (HOSTCC_MODE_CLRTICK_RXBD | HOSTCC_MODE_CLRTICK_TXBD); tp->misc_host_ctrl |= MISC_HOST_CTRL_TAGGED_STATUS; pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL, tp->misc_host_ctrl); } /* Preserve the APE MAC_MODE bits */ if (tg3_flag(tp, ENABLE_APE)) tp->mac_mode = MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN; else tp->mac_mode = 0; if (tg3_10_100_only_device(tp, ent)) tp->phy_flags |= TG3_PHYFLG_10_100_ONLY; err = tg3_phy_probe(tp); if (err) { dev_err(&tp->pdev->dev, "phy probe failed, err %d\n", err); /* ... but do not return immediately ... */ tg3_mdio_fini(tp); } tg3_read_vpd(tp); tg3_read_fw_ver(tp); if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) { tp->phy_flags &= ~TG3_PHYFLG_USE_MI_INTERRUPT; } else { if (tg3_asic_rev(tp) == ASIC_REV_5700) tp->phy_flags |= TG3_PHYFLG_USE_MI_INTERRUPT; else tp->phy_flags &= ~TG3_PHYFLG_USE_MI_INTERRUPT; } /* 5700 {AX,BX} chips have a broken status block link * change bit implementation, so we must use the * status register in those cases. */ if (tg3_asic_rev(tp) == ASIC_REV_5700) tg3_flag_set(tp, USE_LINKCHG_REG); else tg3_flag_clear(tp, USE_LINKCHG_REG); /* The led_ctrl is set during tg3_phy_probe, here we might * have to force the link status polling mechanism based * upon subsystem IDs. */ if (tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL && tg3_asic_rev(tp) == ASIC_REV_5701 && !(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) { tp->phy_flags |= TG3_PHYFLG_USE_MI_INTERRUPT; tg3_flag_set(tp, USE_LINKCHG_REG); } /* For all SERDES we poll the MAC status register. */ if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) tg3_flag_set(tp, POLL_SERDES); else tg3_flag_clear(tp, POLL_SERDES); tp->rx_offset = NET_SKB_PAD + NET_IP_ALIGN; tp->rx_copy_thresh = TG3_RX_COPY_THRESHOLD; if (tg3_asic_rev(tp) == ASIC_REV_5701 && tg3_flag(tp, PCIX_MODE)) { tp->rx_offset = NET_SKB_PAD; #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS tp->rx_copy_thresh = ~(u16)0; #endif } tp->rx_std_ring_mask = TG3_RX_STD_RING_SIZE(tp) - 1; tp->rx_jmb_ring_mask = TG3_RX_JMB_RING_SIZE(tp) - 1; tp->rx_ret_ring_mask = tg3_rx_ret_ring_size(tp) - 1; tp->rx_std_max_post = tp->rx_std_ring_mask + 1; /* Increment the rx prod index on the rx std ring by at most * 8 for these chips to workaround hw errata. */ if (tg3_asic_rev(tp) == ASIC_REV_5750 || tg3_asic_rev(tp) == ASIC_REV_5752 || tg3_asic_rev(tp) == ASIC_REV_5755) tp->rx_std_max_post = 8; if (tg3_flag(tp, ASPM_WORKAROUND)) tp->pwrmgmt_thresh = tr32(PCIE_PWR_MGMT_THRESH) & PCIE_PWR_MGMT_L1_THRESH_MSK; return err; } #ifdef CONFIG_SPARC static int tg3_get_macaddr_sparc(struct tg3 *tp) { struct net_device *dev = tp->dev; struct pci_dev *pdev = tp->pdev; struct device_node *dp = pci_device_to_OF_node(pdev); const unsigned char *addr; int len; addr = of_get_property(dp, "local-mac-address", &len); if (addr && len == 6) { memcpy(dev->dev_addr, addr, 6); return 0; } return -ENODEV; } static int tg3_get_default_macaddr_sparc(struct tg3 *tp) { struct net_device *dev = tp->dev; memcpy(dev->dev_addr, idprom->id_ethaddr, 6); return 0; } #endif static int tg3_get_device_address(struct tg3 *tp) { struct net_device *dev = tp->dev; u32 hi, lo, mac_offset; int addr_ok = 0; int err; #ifdef CONFIG_SPARC if (!tg3_get_macaddr_sparc(tp)) return 0; #endif if (tg3_flag(tp, IS_SSB_CORE)) { err = ssb_gige_get_macaddr(tp->pdev, &dev->dev_addr[0]); if (!err && is_valid_ether_addr(&dev->dev_addr[0])) return 0; } mac_offset = 0x7c; if (tg3_asic_rev(tp) == ASIC_REV_5704 || tg3_flag(tp, 5780_CLASS)) { if (tr32(TG3PCI_DUAL_MAC_CTRL) & DUAL_MAC_CTRL_ID) mac_offset = 0xcc; if (tg3_nvram_lock(tp)) tw32_f(NVRAM_CMD, NVRAM_CMD_RESET); else tg3_nvram_unlock(tp); } else if (tg3_flag(tp, 5717_PLUS)) { if (tp->pci_fn & 1) mac_offset = 0xcc; if (tp->pci_fn > 1) mac_offset += 0x18c; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) mac_offset = 0x10; /* First try to get it from MAC address mailbox. */ tg3_read_mem(tp, NIC_SRAM_MAC_ADDR_HIGH_MBOX, &hi); if ((hi >> 16) == 0x484b) { dev->dev_addr[0] = (hi >> 8) & 0xff; dev->dev_addr[1] = (hi >> 0) & 0xff; tg3_read_mem(tp, NIC_SRAM_MAC_ADDR_LOW_MBOX, &lo); dev->dev_addr[2] = (lo >> 24) & 0xff; dev->dev_addr[3] = (lo >> 16) & 0xff; dev->dev_addr[4] = (lo >> 8) & 0xff; dev->dev_addr[5] = (lo >> 0) & 0xff; /* Some old bootcode may report a 0 MAC address in SRAM */ addr_ok = is_valid_ether_addr(&dev->dev_addr[0]); } if (!addr_ok) { /* Next, try NVRAM. */ if (!tg3_flag(tp, NO_NVRAM) && !tg3_nvram_read_be32(tp, mac_offset + 0, &hi) && !tg3_nvram_read_be32(tp, mac_offset + 4, &lo)) { memcpy(&dev->dev_addr[0], ((char *)&hi) + 2, 2); memcpy(&dev->dev_addr[2], (char *)&lo, sizeof(lo)); } /* Finally just fetch it out of the MAC control regs. */ else { hi = tr32(MAC_ADDR_0_HIGH); lo = tr32(MAC_ADDR_0_LOW); dev->dev_addr[5] = lo & 0xff; dev->dev_addr[4] = (lo >> 8) & 0xff; dev->dev_addr[3] = (lo >> 16) & 0xff; dev->dev_addr[2] = (lo >> 24) & 0xff; dev->dev_addr[1] = hi & 0xff; dev->dev_addr[0] = (hi >> 8) & 0xff; } } if (!is_valid_ether_addr(&dev->dev_addr[0])) { #ifdef CONFIG_SPARC if (!tg3_get_default_macaddr_sparc(tp)) return 0; #endif return -EINVAL; } return 0; } #define BOUNDARY_SINGLE_CACHELINE 1 #define BOUNDARY_MULTI_CACHELINE 2 static u32 tg3_calc_dma_bndry(struct tg3 *tp, u32 val) { int cacheline_size; u8 byte; int goal; pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE, &byte); if (byte == 0) cacheline_size = 1024; else cacheline_size = (int) byte * 4; /* On 5703 and later chips, the boundary bits have no * effect. */ if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && !tg3_flag(tp, PCI_EXPRESS)) goto out; #if defined(CONFIG_PPC64) || defined(CONFIG_IA64) || defined(CONFIG_PARISC) goal = BOUNDARY_MULTI_CACHELINE; #else #if defined(CONFIG_SPARC64) || defined(CONFIG_ALPHA) goal = BOUNDARY_SINGLE_CACHELINE; #else goal = 0; #endif #endif if (tg3_flag(tp, 57765_PLUS)) { val = goal ? 0 : DMA_RWCTRL_DIS_CACHE_ALIGNMENT; goto out; } if (!goal) goto out; /* PCI controllers on most RISC systems tend to disconnect * when a device tries to burst across a cache-line boundary. * Therefore, letting tg3 do so just wastes PCI bandwidth. * * Unfortunately, for PCI-E there are only limited * write-side controls for this, and thus for reads * we will still get the disconnects. We'll also waste * these PCI cycles for both read and write for chips * other than 5700 and 5701 which do not implement the * boundary bits. */ if (tg3_flag(tp, PCIX_MODE) && !tg3_flag(tp, PCI_EXPRESS)) { switch (cacheline_size) { case 16: case 32: case 64: case 128: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_128_PCIX | DMA_RWCTRL_WRITE_BNDRY_128_PCIX); } else { val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX | DMA_RWCTRL_WRITE_BNDRY_384_PCIX); } break; case 256: val |= (DMA_RWCTRL_READ_BNDRY_256_PCIX | DMA_RWCTRL_WRITE_BNDRY_256_PCIX); break; default: val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX | DMA_RWCTRL_WRITE_BNDRY_384_PCIX); break; } } else if (tg3_flag(tp, PCI_EXPRESS)) { switch (cacheline_size) { case 16: case 32: case 64: if (goal == BOUNDARY_SINGLE_CACHELINE) { val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE; val |= DMA_RWCTRL_WRITE_BNDRY_64_PCIE; break; } /* fallthrough */ case 128: default: val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE; val |= DMA_RWCTRL_WRITE_BNDRY_128_PCIE; break; } } else { switch (cacheline_size) { case 16: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_16 | DMA_RWCTRL_WRITE_BNDRY_16); break; } /* fallthrough */ case 32: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_32 | DMA_RWCTRL_WRITE_BNDRY_32); break; } /* fallthrough */ case 64: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_64 | DMA_RWCTRL_WRITE_BNDRY_64); break; } /* fallthrough */ case 128: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_128 | DMA_RWCTRL_WRITE_BNDRY_128); break; } /* fallthrough */ case 256: val |= (DMA_RWCTRL_READ_BNDRY_256 | DMA_RWCTRL_WRITE_BNDRY_256); break; case 512: val |= (DMA_RWCTRL_READ_BNDRY_512 | DMA_RWCTRL_WRITE_BNDRY_512); break; case 1024: default: val |= (DMA_RWCTRL_READ_BNDRY_1024 | DMA_RWCTRL_WRITE_BNDRY_1024); break; } } out: return val; } static int tg3_do_test_dma(struct tg3 *tp, u32 *buf, dma_addr_t buf_dma, int size, int to_device) { struct tg3_internal_buffer_desc test_desc; u32 sram_dma_descs; int i, ret; sram_dma_descs = NIC_SRAM_DMA_DESC_POOL_BASE; tw32(FTQ_RCVBD_COMP_FIFO_ENQDEQ, 0); tw32(FTQ_RCVDATA_COMP_FIFO_ENQDEQ, 0); tw32(RDMAC_STATUS, 0); tw32(WDMAC_STATUS, 0); tw32(BUFMGR_MODE, 0); tw32(FTQ_RESET, 0); test_desc.addr_hi = ((u64) buf_dma) >> 32; test_desc.addr_lo = buf_dma & 0xffffffff; test_desc.nic_mbuf = 0x00002100; test_desc.len = size; /* * HP ZX1 was seeing test failures for 5701 cards running at 33Mhz * the *second* time the tg3 driver was getting loaded after an * initial scan. * * Broadcom tells me: * ...the DMA engine is connected to the GRC block and a DMA * reset may affect the GRC block in some unpredictable way... * The behavior of resets to individual blocks has not been tested. * * Broadcom noted the GRC reset will also reset all sub-components. */ if (to_device) { test_desc.cqid_sqid = (13 << 8) | 2; tw32_f(RDMAC_MODE, RDMAC_MODE_ENABLE); udelay(40); } else { test_desc.cqid_sqid = (16 << 8) | 7; tw32_f(WDMAC_MODE, WDMAC_MODE_ENABLE); udelay(40); } test_desc.flags = 0x00000005; for (i = 0; i < (sizeof(test_desc) / sizeof(u32)); i++) { u32 val; val = *(((u32 *)&test_desc) + i); pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, sram_dma_descs + (i * sizeof(u32))); pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val); } pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0); if (to_device) tw32(FTQ_DMA_HIGH_READ_FIFO_ENQDEQ, sram_dma_descs); else tw32(FTQ_DMA_HIGH_WRITE_FIFO_ENQDEQ, sram_dma_descs); ret = -ENODEV; for (i = 0; i < 40; i++) { u32 val; if (to_device) val = tr32(FTQ_RCVBD_COMP_FIFO_ENQDEQ); else val = tr32(FTQ_RCVDATA_COMP_FIFO_ENQDEQ); if ((val & 0xffff) == sram_dma_descs) { ret = 0; break; } udelay(100); } return ret; } #define TEST_BUFFER_SIZE 0x2000 static DEFINE_PCI_DEVICE_TABLE(tg3_dma_wait_state_chipsets) = { { PCI_DEVICE(PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_PCI15) }, { }, }; static int tg3_test_dma(struct tg3 *tp) { dma_addr_t buf_dma; u32 *buf, saved_dma_rwctrl; int ret = 0; buf = dma_alloc_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE, &buf_dma, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto out_nofree; } tp->dma_rwctrl = ((0x7 << DMA_RWCTRL_PCI_WRITE_CMD_SHIFT) | (0x6 << DMA_RWCTRL_PCI_READ_CMD_SHIFT)); tp->dma_rwctrl = tg3_calc_dma_bndry(tp, tp->dma_rwctrl); if (tg3_flag(tp, 57765_PLUS)) goto out; if (tg3_flag(tp, PCI_EXPRESS)) { /* DMA read watermark not used on PCIE */ tp->dma_rwctrl |= 0x00180000; } else if (!tg3_flag(tp, PCIX_MODE)) { if (tg3_asic_rev(tp) == ASIC_REV_5705 || tg3_asic_rev(tp) == ASIC_REV_5750) tp->dma_rwctrl |= 0x003f0000; else tp->dma_rwctrl |= 0x003f000f; } else { if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704) { u32 ccval = (tr32(TG3PCI_CLOCK_CTRL) & 0x1f); u32 read_water = 0x7; /* If the 5704 is behind the EPB bridge, we can * do the less restrictive ONE_DMA workaround for * better performance. */ if (tg3_flag(tp, 40BIT_DMA_BUG) && tg3_asic_rev(tp) == ASIC_REV_5704) tp->dma_rwctrl |= 0x8000; else if (ccval == 0x6 || ccval == 0x7) tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA; if (tg3_asic_rev(tp) == ASIC_REV_5703) read_water = 4; /* Set bit 23 to enable PCIX hw bug fix */ tp->dma_rwctrl |= (read_water << DMA_RWCTRL_READ_WATER_SHIFT) | (0x3 << DMA_RWCTRL_WRITE_WATER_SHIFT) | (1 << 23); } else if (tg3_asic_rev(tp) == ASIC_REV_5780) { /* 5780 always in PCIX mode */ tp->dma_rwctrl |= 0x00144000; } else if (tg3_asic_rev(tp) == ASIC_REV_5714) { /* 5714 always in PCIX mode */ tp->dma_rwctrl |= 0x00148000; } else { tp->dma_rwctrl |= 0x001b000f; } } if (tg3_flag(tp, ONE_DMA_AT_ONCE)) tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA; if (tg3_asic_rev(tp) == ASIC_REV_5703 || tg3_asic_rev(tp) == ASIC_REV_5704) tp->dma_rwctrl &= 0xfffffff0; if (tg3_asic_rev(tp) == ASIC_REV_5700 || tg3_asic_rev(tp) == ASIC_REV_5701) { /* Remove this if it causes problems for some boards. */ tp->dma_rwctrl |= DMA_RWCTRL_USE_MEM_READ_MULT; /* On 5700/5701 chips, we need to set this bit. * Otherwise the chip will issue cacheline transactions * to streamable DMA memory with not all the byte * enables turned on. This is an error on several * RISC PCI controllers, in particular sparc64. * * On 5703/5704 chips, this bit has been reassigned * a different meaning. In particular, it is used * on those chips to enable a PCI-X workaround. */ tp->dma_rwctrl |= DMA_RWCTRL_ASSERT_ALL_BE; } tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); #if 0 /* Unneeded, already done by tg3_get_invariants. */ tg3_switch_clocks(tp); #endif if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701) goto out; /* It is best to perform DMA test with maximum write burst size * to expose the 5700/5701 write DMA bug. */ saved_dma_rwctrl = tp->dma_rwctrl; tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK; tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); while (1) { u32 *p = buf, i; for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) p[i] = i; /* Send the buffer to the chip. */ ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, 1); if (ret) { dev_err(&tp->pdev->dev, "%s: Buffer write failed. err = %d\n", __func__, ret); break; } #if 0 /* validate data reached card RAM correctly. */ for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) { u32 val; tg3_read_mem(tp, 0x2100 + (i*4), &val); if (le32_to_cpu(val) != p[i]) { dev_err(&tp->pdev->dev, "%s: Buffer corrupted on device! " "(%d != %d)\n", __func__, val, i); /* ret = -ENODEV here? */ } p[i] = 0; } #endif /* Now read it back. */ ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, 0); if (ret) { dev_err(&tp->pdev->dev, "%s: Buffer read failed. " "err = %d\n", __func__, ret); break; } /* Verify it. */ for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) { if (p[i] == i) continue; if ((tp->dma_rwctrl & DMA_RWCTRL_WRITE_BNDRY_MASK) != DMA_RWCTRL_WRITE_BNDRY_16) { tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK; tp->dma_rwctrl |= DMA_RWCTRL_WRITE_BNDRY_16; tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); break; } else { dev_err(&tp->pdev->dev, "%s: Buffer corrupted on read back! " "(%d != %d)\n", __func__, p[i], i); ret = -ENODEV; goto out; } } if (i == (TEST_BUFFER_SIZE / sizeof(u32))) { /* Success. */ ret = 0; break; } } if ((tp->dma_rwctrl & DMA_RWCTRL_WRITE_BNDRY_MASK) != DMA_RWCTRL_WRITE_BNDRY_16) { /* DMA test passed without adjusting DMA boundary, * now look for chipsets that are known to expose the * DMA bug without failing the test. */ if (pci_dev_present(tg3_dma_wait_state_chipsets)) { tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK; tp->dma_rwctrl |= DMA_RWCTRL_WRITE_BNDRY_16; } else { /* Safe to use the calculated DMA boundary. */ tp->dma_rwctrl = saved_dma_rwctrl; } tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl); } out: dma_free_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE, buf, buf_dma); out_nofree: return ret; } static void tg3_init_bufmgr_config(struct tg3 *tp) { if (tg3_flag(tp, 57765_PLUS)) { tp->bufmgr_config.mbuf_read_dma_low_water = DEFAULT_MB_RDMA_LOW_WATER_5705; tp->bufmgr_config.mbuf_mac_rx_low_water = DEFAULT_MB_MACRX_LOW_WATER_57765; tp->bufmgr_config.mbuf_high_water = DEFAULT_MB_HIGH_WATER_57765; tp->bufmgr_config.mbuf_read_dma_low_water_jumbo = DEFAULT_MB_RDMA_LOW_WATER_5705; tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo = DEFAULT_MB_MACRX_LOW_WATER_JUMBO_57765; tp->bufmgr_config.mbuf_high_water_jumbo = DEFAULT_MB_HIGH_WATER_JUMBO_57765; } else if (tg3_flag(tp, 5705_PLUS)) { tp->bufmgr_config.mbuf_read_dma_low_water = DEFAULT_MB_RDMA_LOW_WATER_5705; tp->bufmgr_config.mbuf_mac_rx_low_water = DEFAULT_MB_MACRX_LOW_WATER_5705; tp->bufmgr_config.mbuf_high_water = DEFAULT_MB_HIGH_WATER_5705; if (tg3_asic_rev(tp) == ASIC_REV_5906) { tp->bufmgr_config.mbuf_mac_rx_low_water = DEFAULT_MB_MACRX_LOW_WATER_5906; tp->bufmgr_config.mbuf_high_water = DEFAULT_MB_HIGH_WATER_5906; } tp->bufmgr_config.mbuf_read_dma_low_water_jumbo = DEFAULT_MB_RDMA_LOW_WATER_JUMBO_5780; tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo = DEFAULT_MB_MACRX_LOW_WATER_JUMBO_5780; tp->bufmgr_config.mbuf_high_water_jumbo = DEFAULT_MB_HIGH_WATER_JUMBO_5780; } else { tp->bufmgr_config.mbuf_read_dma_low_water = DEFAULT_MB_RDMA_LOW_WATER; tp->bufmgr_config.mbuf_mac_rx_low_water = DEFAULT_MB_MACRX_LOW_WATER; tp->bufmgr_config.mbuf_high_water = DEFAULT_MB_HIGH_WATER; tp->bufmgr_config.mbuf_read_dma_low_water_jumbo = DEFAULT_MB_RDMA_LOW_WATER_JUMBO; tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo = DEFAULT_MB_MACRX_LOW_WATER_JUMBO; tp->bufmgr_config.mbuf_high_water_jumbo = DEFAULT_MB_HIGH_WATER_JUMBO; } tp->bufmgr_config.dma_low_water = DEFAULT_DMA_LOW_WATER; tp->bufmgr_config.dma_high_water = DEFAULT_DMA_HIGH_WATER; } static char *tg3_phy_string(struct tg3 *tp) { switch (tp->phy_id & TG3_PHY_ID_MASK) { case TG3_PHY_ID_BCM5400: return "5400"; case TG3_PHY_ID_BCM5401: return "5401"; case TG3_PHY_ID_BCM5411: return "5411"; case TG3_PHY_ID_BCM5701: return "5701"; case TG3_PHY_ID_BCM5703: return "5703"; case TG3_PHY_ID_BCM5704: return "5704"; case TG3_PHY_ID_BCM5705: return "5705"; case TG3_PHY_ID_BCM5750: return "5750"; case TG3_PHY_ID_BCM5752: return "5752"; case TG3_PHY_ID_BCM5714: return "5714"; case TG3_PHY_ID_BCM5780: return "5780"; case TG3_PHY_ID_BCM5755: return "5755"; case TG3_PHY_ID_BCM5787: return "5787"; case TG3_PHY_ID_BCM5784: return "5784"; case TG3_PHY_ID_BCM5756: return "5722/5756"; case TG3_PHY_ID_BCM5906: return "5906"; case TG3_PHY_ID_BCM5761: return "5761"; case TG3_PHY_ID_BCM5718C: return "5718C"; case TG3_PHY_ID_BCM5718S: return "5718S"; case TG3_PHY_ID_BCM57765: return "57765"; case TG3_PHY_ID_BCM5719C: return "5719C"; case TG3_PHY_ID_BCM5720C: return "5720C"; case TG3_PHY_ID_BCM5762: return "5762C"; case TG3_PHY_ID_BCM8002: return "8002/serdes"; case 0: return "serdes"; default: return "unknown"; } } static char *tg3_bus_string(struct tg3 *tp, char *str) { if (tg3_flag(tp, PCI_EXPRESS)) { strcpy(str, "PCI Express"); return str; } else if (tg3_flag(tp, PCIX_MODE)) { u32 clock_ctrl = tr32(TG3PCI_CLOCK_CTRL) & 0x1f; strcpy(str, "PCIX:"); if ((clock_ctrl == 7) || ((tr32(GRC_MISC_CFG) & GRC_MISC_CFG_BOARD_ID_MASK) == GRC_MISC_CFG_BOARD_ID_5704CIOBE)) strcat(str, "133MHz"); else if (clock_ctrl == 0) strcat(str, "33MHz"); else if (clock_ctrl == 2) strcat(str, "50MHz"); else if (clock_ctrl == 4) strcat(str, "66MHz"); else if (clock_ctrl == 6) strcat(str, "100MHz"); } else { strcpy(str, "PCI:"); if (tg3_flag(tp, PCI_HIGH_SPEED)) strcat(str, "66MHz"); else strcat(str, "33MHz"); } if (tg3_flag(tp, PCI_32BIT)) strcat(str, ":32-bit"); else strcat(str, ":64-bit"); return str; } static void tg3_init_coal(struct tg3 *tp) { struct ethtool_coalesce *ec = &tp->coal; memset(ec, 0, sizeof(*ec)); ec->cmd = ETHTOOL_GCOALESCE; ec->rx_coalesce_usecs = LOW_RXCOL_TICKS; ec->tx_coalesce_usecs = LOW_TXCOL_TICKS; ec->rx_max_coalesced_frames = LOW_RXMAX_FRAMES; ec->tx_max_coalesced_frames = LOW_TXMAX_FRAMES; ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT; ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT; ec->rx_max_coalesced_frames_irq = DEFAULT_RXCOAL_MAXF_INT; ec->tx_max_coalesced_frames_irq = DEFAULT_TXCOAL_MAXF_INT; ec->stats_block_coalesce_usecs = DEFAULT_STAT_COAL_TICKS; if (tp->coalesce_mode & (HOSTCC_MODE_CLRTICK_RXBD | HOSTCC_MODE_CLRTICK_TXBD)) { ec->rx_coalesce_usecs = LOW_RXCOL_TICKS_CLRTCKS; ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT_CLRTCKS; ec->tx_coalesce_usecs = LOW_TXCOL_TICKS_CLRTCKS; ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT_CLRTCKS; } if (tg3_flag(tp, 5705_PLUS)) { ec->rx_coalesce_usecs_irq = 0; ec->tx_coalesce_usecs_irq = 0; ec->stats_block_coalesce_usecs = 0; } } static int tg3_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *dev; struct tg3 *tp; int i, err, pm_cap; u32 sndmbx, rcvmbx, intmbx; char str[40]; u64 dma_mask, persist_dma_mask; netdev_features_t features = 0; printk_once(KERN_INFO "%s\n", version); err = pci_enable_device(pdev); if (err) { dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n"); return err; } err = pci_request_regions(pdev, DRV_MODULE_NAME); if (err) { dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n"); goto err_out_disable_pdev; } pci_set_master(pdev); /* Find power-management capability. */ pm_cap = pci_find_capability(pdev, PCI_CAP_ID_PM); if (pm_cap == 0) { dev_err(&pdev->dev, "Cannot find Power Management capability, aborting\n"); err = -EIO; goto err_out_free_res; } err = pci_set_power_state(pdev, PCI_D0); if (err) { dev_err(&pdev->dev, "Transition to D0 failed, aborting\n"); goto err_out_free_res; } dev = alloc_etherdev_mq(sizeof(*tp), TG3_IRQ_MAX_VECS); if (!dev) { err = -ENOMEM; goto err_out_power_down; } SET_NETDEV_DEV(dev, &pdev->dev); tp = netdev_priv(dev); tp->pdev = pdev; tp->dev = dev; tp->pm_cap = pm_cap; tp->rx_mode = TG3_DEF_RX_MODE; tp->tx_mode = TG3_DEF_TX_MODE; tp->irq_sync = 1; if (tg3_debug > 0) tp->msg_enable = tg3_debug; else tp->msg_enable = TG3_DEF_MSG_ENABLE; if (pdev_is_ssb_gige_core(pdev)) { tg3_flag_set(tp, IS_SSB_CORE); if (ssb_gige_must_flush_posted_writes(pdev)) tg3_flag_set(tp, FLUSH_POSTED_WRITES); if (ssb_gige_one_dma_at_once(pdev)) tg3_flag_set(tp, ONE_DMA_AT_ONCE); if (ssb_gige_have_roboswitch(pdev)) tg3_flag_set(tp, ROBOSWITCH); if (ssb_gige_is_rgmii(pdev)) tg3_flag_set(tp, RGMII_MODE); } /* The word/byte swap controls here control register access byte * swapping. DMA data byte swapping is controlled in the GRC_MODE * setting below. */ tp->misc_host_ctrl = MISC_HOST_CTRL_MASK_PCI_INT | MISC_HOST_CTRL_WORD_SWAP | MISC_HOST_CTRL_INDIR_ACCESS | MISC_HOST_CTRL_PCISTATE_RW; /* The NONFRM (non-frame) byte/word swap controls take effect * on descriptor entries, anything which isn't packet data. * * The StrongARM chips on the board (one for tx, one for rx) * are running in big-endian mode. */ tp->grc_mode = (GRC_MODE_WSWAP_DATA | GRC_MODE_BSWAP_DATA | GRC_MODE_WSWAP_NONFRM_DATA); #ifdef __BIG_ENDIAN tp->grc_mode |= GRC_MODE_BSWAP_NONFRM_DATA; #endif spin_lock_init(&tp->lock); spin_lock_init(&tp->indirect_lock); INIT_WORK(&tp->reset_task, tg3_reset_task); tp->regs = pci_ioremap_bar(pdev, BAR_0); if (!tp->regs) { dev_err(&pdev->dev, "Cannot map device registers, aborting\n"); err = -ENOMEM; goto err_out_free_dev; } if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 || tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761E || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761SE || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5719 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5720 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5762 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5725 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5727) { tg3_flag_set(tp, ENABLE_APE); tp->aperegs = pci_ioremap_bar(pdev, BAR_2); if (!tp->aperegs) { dev_err(&pdev->dev, "Cannot map APE registers, aborting\n"); err = -ENOMEM; goto err_out_iounmap; } } tp->rx_pending = TG3_DEF_RX_RING_PENDING; tp->rx_jumbo_pending = TG3_DEF_RX_JUMBO_RING_PENDING; dev->ethtool_ops = &tg3_ethtool_ops; dev->watchdog_timeo = TG3_TX_TIMEOUT; dev->netdev_ops = &tg3_netdev_ops; dev->irq = pdev->irq; err = tg3_get_invariants(tp, ent); if (err) { dev_err(&pdev->dev, "Problem fetching invariants of chip, aborting\n"); goto err_out_apeunmap; } /* The EPB bridge inside 5714, 5715, and 5780 and any * device behind the EPB cannot support DMA addresses > 40-bit. * On 64-bit systems with IOMMU, use 40-bit dma_mask. * On 64-bit systems without IOMMU, use 64-bit dma_mask and * do DMA address check in tg3_start_xmit(). */ if (tg3_flag(tp, IS_5788)) persist_dma_mask = dma_mask = DMA_BIT_MASK(32); else if (tg3_flag(tp, 40BIT_DMA_BUG)) { persist_dma_mask = dma_mask = DMA_BIT_MASK(40); #ifdef CONFIG_HIGHMEM dma_mask = DMA_BIT_MASK(64); #endif } else persist_dma_mask = dma_mask = DMA_BIT_MASK(64); /* Configure DMA attributes. */ if (dma_mask > DMA_BIT_MASK(32)) { err = pci_set_dma_mask(pdev, dma_mask); if (!err) { features |= NETIF_F_HIGHDMA; err = pci_set_consistent_dma_mask(pdev, persist_dma_mask); if (err < 0) { dev_err(&pdev->dev, "Unable to obtain 64 bit " "DMA for consistent allocations\n"); goto err_out_apeunmap; } } } if (err || dma_mask == DMA_BIT_MASK(32)) { err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (err) { dev_err(&pdev->dev, "No usable DMA configuration, aborting\n"); goto err_out_apeunmap; } } tg3_init_bufmgr_config(tp); features |= NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX; /* 5700 B0 chips do not support checksumming correctly due * to hardware bugs. */ if (tg3_chip_rev_id(tp) != CHIPREV_ID_5700_B0) { features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_RXCSUM; if (tg3_flag(tp, 5755_PLUS)) features |= NETIF_F_IPV6_CSUM; } /* TSO is on by default on chips that support hardware TSO. * Firmware TSO on older chips gives lower performance, so it * is off by default, but can be enabled using ethtool. */ if ((tg3_flag(tp, HW_TSO_1) || tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) && (features & NETIF_F_IP_CSUM)) features |= NETIF_F_TSO; if (tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) { if (features & NETIF_F_IPV6_CSUM) features |= NETIF_F_TSO6; if (tg3_flag(tp, HW_TSO_3) || tg3_asic_rev(tp) == ASIC_REV_5761 || (tg3_asic_rev(tp) == ASIC_REV_5784 && tg3_chip_rev(tp) != CHIPREV_5784_AX) || tg3_asic_rev(tp) == ASIC_REV_5785 || tg3_asic_rev(tp) == ASIC_REV_57780) features |= NETIF_F_TSO_ECN; } dev->features |= features; dev->vlan_features |= features; /* * Add loopback capability only for a subset of devices that support * MAC-LOOPBACK. Eventually this need to be enhanced to allow INT-PHY * loopback for the remaining devices. */ if (tg3_asic_rev(tp) != ASIC_REV_5780 && !tg3_flag(tp, CPMU_PRESENT)) /* Add the loopback capability */ features |= NETIF_F_LOOPBACK; dev->hw_features |= features; if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A1 && !tg3_flag(tp, TSO_CAPABLE) && !(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH)) { tg3_flag_set(tp, MAX_RXPEND_64); tp->rx_pending = 63; } err = tg3_get_device_address(tp); if (err) { dev_err(&pdev->dev, "Could not obtain valid ethernet address, aborting\n"); goto err_out_apeunmap; } /* * Reset chip in case UNDI or EFI driver did not shutdown * DMA self test will enable WDMAC and we'll see (spurious) * pending DMA on the PCI bus at that point. */ if ((tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE) || (tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) { tw32(MEMARB_MODE, MEMARB_MODE_ENABLE); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); } err = tg3_test_dma(tp); if (err) { dev_err(&pdev->dev, "DMA engine test failed, aborting\n"); goto err_out_apeunmap; } intmbx = MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW; rcvmbx = MAILBOX_RCVRET_CON_IDX_0 + TG3_64BIT_REG_LOW; sndmbx = MAILBOX_SNDHOST_PROD_IDX_0 + TG3_64BIT_REG_LOW; for (i = 0; i < tp->irq_max; i++) { struct tg3_napi *tnapi = &tp->napi[i]; tnapi->tp = tp; tnapi->tx_pending = TG3_DEF_TX_RING_PENDING; tnapi->int_mbox = intmbx; if (i <= 4) intmbx += 0x8; else intmbx += 0x4; tnapi->consmbox = rcvmbx; tnapi->prodmbox = sndmbx; if (i) tnapi->coal_now = HOSTCC_MODE_COAL_VEC1_NOW << (i - 1); else tnapi->coal_now = HOSTCC_MODE_NOW; if (!tg3_flag(tp, SUPPORT_MSIX)) break; /* * If we support MSIX, we'll be using RSS. If we're using * RSS, the first vector only handles link interrupts and the * remaining vectors handle rx and tx interrupts. Reuse the * mailbox values for the next iteration. The values we setup * above are still useful for the single vectored mode. */ if (!i) continue; rcvmbx += 0x8; if (sndmbx & 0x4) sndmbx -= 0x4; else sndmbx += 0xc; } tg3_init_coal(tp); pci_set_drvdata(pdev, dev); if (tg3_asic_rev(tp) == ASIC_REV_5719 || tg3_asic_rev(tp) == ASIC_REV_5720 || tg3_asic_rev(tp) == ASIC_REV_5762) tg3_flag_set(tp, PTP_CAPABLE); if (tg3_flag(tp, 5717_PLUS)) { /* Resume a low-power mode */ tg3_frob_aux_power(tp, false); } tg3_timer_init(tp); tg3_carrier_off(tp); err = register_netdev(dev); if (err) { dev_err(&pdev->dev, "Cannot register net device, aborting\n"); goto err_out_apeunmap; } netdev_info(dev, "Tigon3 [partno(%s) rev %04x] (%s) MAC address %pM\n", tp->board_part_number, tg3_chip_rev_id(tp), tg3_bus_string(tp, str), dev->dev_addr); if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) { struct phy_device *phydev; phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]; netdev_info(dev, "attached PHY driver [%s] (mii_bus:phy_addr=%s)\n", phydev->drv->name, dev_name(&phydev->dev)); } else { char *ethtype; if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY) ethtype = "10/100Base-TX"; else if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES) ethtype = "1000Base-SX"; else ethtype = "10/100/1000Base-T"; netdev_info(dev, "attached PHY is %s (%s Ethernet) " "(WireSpeed[%d], EEE[%d])\n", tg3_phy_string(tp), ethtype, (tp->phy_flags & TG3_PHYFLG_NO_ETH_WIRE_SPEED) == 0, (tp->phy_flags & TG3_PHYFLG_EEE_CAP) != 0); } netdev_info(dev, "RXcsums[%d] LinkChgREG[%d] MIirq[%d] ASF[%d] TSOcap[%d]\n", (dev->features & NETIF_F_RXCSUM) != 0, tg3_flag(tp, USE_LINKCHG_REG) != 0, (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) != 0, tg3_flag(tp, ENABLE_ASF) != 0, tg3_flag(tp, TSO_CAPABLE) != 0); netdev_info(dev, "dma_rwctrl[%08x] dma_mask[%d-bit]\n", tp->dma_rwctrl, pdev->dma_mask == DMA_BIT_MASK(32) ? 32 : ((u64)pdev->dma_mask) == DMA_BIT_MASK(40) ? 40 : 64); pci_save_state(pdev); return 0; err_out_apeunmap: if (tp->aperegs) { iounmap(tp->aperegs); tp->aperegs = NULL; } err_out_iounmap: if (tp->regs) { iounmap(tp->regs); tp->regs = NULL; } err_out_free_dev: free_netdev(dev); err_out_power_down: pci_set_power_state(pdev, PCI_D3hot); err_out_free_res: pci_release_regions(pdev); err_out_disable_pdev: pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); return err; } static void tg3_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); if (dev) { struct tg3 *tp = netdev_priv(dev); release_firmware(tp->fw); tg3_reset_task_cancel(tp); if (tg3_flag(tp, USE_PHYLIB)) { tg3_phy_fini(tp); tg3_mdio_fini(tp); } unregister_netdev(dev); if (tp->aperegs) { iounmap(tp->aperegs); tp->aperegs = NULL; } if (tp->regs) { iounmap(tp->regs); tp->regs = NULL; } free_netdev(dev); pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } } #ifdef CONFIG_PM_SLEEP static int tg3_suspend(struct device *device) { struct pci_dev *pdev = to_pci_dev(device); struct net_device *dev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(dev); int err; if (!netif_running(dev)) return 0; tg3_reset_task_cancel(tp); tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_timer_stop(tp); tg3_full_lock(tp, 1); tg3_disable_ints(tp); tg3_full_unlock(tp); netif_device_detach(dev); tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 1); tg3_flag_clear(tp, INIT_COMPLETE); tg3_full_unlock(tp); err = tg3_power_down_prepare(tp); if (err) { int err2; tg3_full_lock(tp, 0); tg3_flag_set(tp, INIT_COMPLETE); err2 = tg3_restart_hw(tp, 1); if (err2) goto out; tg3_timer_start(tp); netif_device_attach(dev); tg3_netif_start(tp); out: tg3_full_unlock(tp); if (!err2) tg3_phy_start(tp); } return err; } static int tg3_resume(struct device *device) { struct pci_dev *pdev = to_pci_dev(device); struct net_device *dev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(dev); int err; if (!netif_running(dev)) return 0; netif_device_attach(dev); tg3_full_lock(tp, 0); tg3_flag_set(tp, INIT_COMPLETE); err = tg3_restart_hw(tp, 1); if (err) goto out; tg3_timer_start(tp); tg3_netif_start(tp); out: tg3_full_unlock(tp); if (!err) tg3_phy_start(tp); return err; } static SIMPLE_DEV_PM_OPS(tg3_pm_ops, tg3_suspend, tg3_resume); #define TG3_PM_OPS (&tg3_pm_ops) #else #define TG3_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ /** * tg3_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t tg3_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); pci_ers_result_t err = PCI_ERS_RESULT_NEED_RESET; netdev_info(netdev, "PCI I/O error detected\n"); rtnl_lock(); if (!netif_running(netdev)) goto done; tg3_phy_stop(tp); tg3_netif_stop(tp); tg3_timer_stop(tp); /* Want to make sure that the reset task doesn't run */ tg3_reset_task_cancel(tp); netif_device_detach(netdev); /* Clean up software state, even if MMIO is blocked */ tg3_full_lock(tp, 0); tg3_halt(tp, RESET_KIND_SHUTDOWN, 0); tg3_full_unlock(tp); done: if (state == pci_channel_io_perm_failure) err = PCI_ERS_RESULT_DISCONNECT; else pci_disable_device(pdev); rtnl_unlock(); return err; } /** * tg3_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. * At this point, the card has exprienced a hard reset, * followed by fixups by BIOS, and has its config space * set up identically to what it was at cold boot. */ static pci_ers_result_t tg3_io_slot_reset(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT; int err; rtnl_lock(); if (pci_enable_device(pdev)) { netdev_err(netdev, "Cannot re-enable PCI device after reset.\n"); goto done; } pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); if (!netif_running(netdev)) { rc = PCI_ERS_RESULT_RECOVERED; goto done; } err = tg3_power_up(tp); if (err) goto done; rc = PCI_ERS_RESULT_RECOVERED; done: rtnl_unlock(); return rc; } /** * tg3_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells * us that its OK to resume normal operation. */ static void tg3_io_resume(struct pci_dev *pdev) { struct net_device *netdev = pci_get_drvdata(pdev); struct tg3 *tp = netdev_priv(netdev); int err; rtnl_lock(); if (!netif_running(netdev)) goto done; tg3_full_lock(tp, 0); tg3_flag_set(tp, INIT_COMPLETE); err = tg3_restart_hw(tp, 1); if (err) { tg3_full_unlock(tp); netdev_err(netdev, "Cannot restart hardware after reset.\n"); goto done; } netif_device_attach(netdev); tg3_timer_start(tp); tg3_netif_start(tp); tg3_full_unlock(tp); tg3_phy_start(tp); done: rtnl_unlock(); } static const struct pci_error_handlers tg3_err_handler = { .error_detected = tg3_io_error_detected, .slot_reset = tg3_io_slot_reset, .resume = tg3_io_resume }; static struct pci_driver tg3_driver = { .name = DRV_MODULE_NAME, .id_table = tg3_pci_tbl, .probe = tg3_init_one, .remove = tg3_remove_one, .err_handler = &tg3_err_handler, .driver.pm = TG3_PM_OPS, }; static int __init tg3_init(void) { return pci_register_driver(&tg3_driver); } static void __exit tg3_cleanup(void) { pci_unregister_driver(&tg3_driver); } module_init(tg3_init); module_exit(tg3_cleanup);
./CrossVul/dataset_final_sorted/CWE-119/c/good_5610_0
crossvul-cpp_data_bad_2593_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2593_0
crossvul-cpp_data_good_345_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-119/c/good_345_1
crossvul-cpp_data_bad_4721_0
/* FUSE: Filesystem in Userspace Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu> This program can be distributed under the terms of the GNU GPL. See the file COPYING. */ #include "fuse_i.h" #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/module.h> #include <linux/compat.h> static const struct file_operations fuse_direct_io_file_operations; static int fuse_send_open(struct fuse_conn *fc, u64 nodeid, struct file *file, int opcode, struct fuse_open_out *outargp) { struct fuse_open_in inarg; struct fuse_req *req; int err; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.flags = file->f_flags & ~(O_CREAT | O_EXCL | O_NOCTTY); if (!fc->atomic_o_trunc) inarg.flags &= ~O_TRUNC; req->in.h.opcode = opcode; req->in.h.nodeid = nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->out.numargs = 1; req->out.args[0].size = sizeof(*outargp); req->out.args[0].value = outargp; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); return err; } struct fuse_file *fuse_file_alloc(struct fuse_conn *fc) { struct fuse_file *ff; ff = kmalloc(sizeof(struct fuse_file), GFP_KERNEL); if (unlikely(!ff)) return NULL; ff->fc = fc; ff->reserved_req = fuse_request_alloc(); if (unlikely(!ff->reserved_req)) { kfree(ff); return NULL; } INIT_LIST_HEAD(&ff->write_entry); atomic_set(&ff->count, 0); RB_CLEAR_NODE(&ff->polled_node); init_waitqueue_head(&ff->poll_wait); spin_lock(&fc->lock); ff->kh = ++fc->khctr; spin_unlock(&fc->lock); return ff; } void fuse_file_free(struct fuse_file *ff) { fuse_request_free(ff->reserved_req); kfree(ff); } struct fuse_file *fuse_file_get(struct fuse_file *ff) { atomic_inc(&ff->count); return ff; } static void fuse_release_end(struct fuse_conn *fc, struct fuse_req *req) { path_put(&req->misc.release.path); } static void fuse_file_put(struct fuse_file *ff) { if (atomic_dec_and_test(&ff->count)) { struct fuse_req *req = ff->reserved_req; req->end = fuse_release_end; fuse_request_send_background(ff->fc, req); kfree(ff); } } int fuse_do_open(struct fuse_conn *fc, u64 nodeid, struct file *file, bool isdir) { struct fuse_open_out outarg; struct fuse_file *ff; int err; int opcode = isdir ? FUSE_OPENDIR : FUSE_OPEN; ff = fuse_file_alloc(fc); if (!ff) return -ENOMEM; err = fuse_send_open(fc, nodeid, file, opcode, &outarg); if (err) { fuse_file_free(ff); return err; } if (isdir) outarg.open_flags &= ~FOPEN_DIRECT_IO; ff->fh = outarg.fh; ff->nodeid = nodeid; ff->open_flags = outarg.open_flags; file->private_data = fuse_file_get(ff); return 0; } EXPORT_SYMBOL_GPL(fuse_do_open); void fuse_finish_open(struct inode *inode, struct file *file) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = get_fuse_conn(inode); if (ff->open_flags & FOPEN_DIRECT_IO) file->f_op = &fuse_direct_io_file_operations; if (!(ff->open_flags & FOPEN_KEEP_CACHE)) invalidate_inode_pages2(inode->i_mapping); if (ff->open_flags & FOPEN_NONSEEKABLE) nonseekable_open(inode, file); if (fc->atomic_o_trunc && (file->f_flags & O_TRUNC)) { struct fuse_inode *fi = get_fuse_inode(inode); spin_lock(&fc->lock); fi->attr_version = ++fc->attr_version; i_size_write(inode, 0); spin_unlock(&fc->lock); fuse_invalidate_attr(inode); } } int fuse_open_common(struct inode *inode, struct file *file, bool isdir) { struct fuse_conn *fc = get_fuse_conn(inode); int err; /* VFS checks this, but only _after_ ->open() */ if (file->f_flags & O_DIRECT) return -EINVAL; err = generic_file_open(inode, file); if (err) return err; err = fuse_do_open(fc, get_node_id(inode), file, isdir); if (err) return err; fuse_finish_open(inode, file); return 0; } static void fuse_prepare_release(struct fuse_file *ff, int flags, int opcode) { struct fuse_conn *fc = ff->fc; struct fuse_req *req = ff->reserved_req; struct fuse_release_in *inarg = &req->misc.release.in; spin_lock(&fc->lock); list_del(&ff->write_entry); if (!RB_EMPTY_NODE(&ff->polled_node)) rb_erase(&ff->polled_node, &fc->polled_files); spin_unlock(&fc->lock); wake_up_interruptible_sync(&ff->poll_wait); inarg->fh = ff->fh; inarg->flags = flags; req->in.h.opcode = opcode; req->in.h.nodeid = ff->nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(struct fuse_release_in); req->in.args[0].value = inarg; } void fuse_release_common(struct file *file, int opcode) { struct fuse_file *ff; struct fuse_req *req; ff = file->private_data; if (unlikely(!ff)) return; req = ff->reserved_req; fuse_prepare_release(ff, file->f_flags, opcode); /* Hold vfsmount and dentry until release is finished */ path_get(&file->f_path); req->misc.release.path = file->f_path; /* * Normally this will send the RELEASE request, however if * some asynchronous READ or WRITE requests are outstanding, * the sending will be delayed. */ fuse_file_put(ff); } static int fuse_open(struct inode *inode, struct file *file) { return fuse_open_common(inode, file, false); } static int fuse_release(struct inode *inode, struct file *file) { fuse_release_common(file, FUSE_RELEASE); /* return value is ignored by VFS */ return 0; } void fuse_sync_release(struct fuse_file *ff, int flags) { WARN_ON(atomic_read(&ff->count) > 1); fuse_prepare_release(ff, flags, FUSE_RELEASE); ff->reserved_req->force = 1; fuse_request_send(ff->fc, ff->reserved_req); fuse_put_request(ff->fc, ff->reserved_req); kfree(ff); } EXPORT_SYMBOL_GPL(fuse_sync_release); /* * Scramble the ID space with XTEA, so that the value of the files_struct * pointer is not exposed to userspace. */ u64 fuse_lock_owner_id(struct fuse_conn *fc, fl_owner_t id) { u32 *k = fc->scramble_key; u64 v = (unsigned long) id; u32 v0 = v; u32 v1 = v >> 32; u32 sum = 0; int i; for (i = 0; i < 32; i++) { v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + k[sum & 3]); sum += 0x9E3779B9; v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + k[sum>>11 & 3]); } return (u64) v0 + ((u64) v1 << 32); } /* * Check if page is under writeback * * This is currently done by walking the list of writepage requests * for the inode, which can be pretty inefficient. */ static bool fuse_page_is_writeback(struct inode *inode, pgoff_t index) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_req *req; bool found = false; spin_lock(&fc->lock); list_for_each_entry(req, &fi->writepages, writepages_entry) { pgoff_t curr_index; BUG_ON(req->inode != inode); curr_index = req->misc.write.in.offset >> PAGE_CACHE_SHIFT; if (curr_index == index) { found = true; break; } } spin_unlock(&fc->lock); return found; } /* * Wait for page writeback to be completed. * * Since fuse doesn't rely on the VM writeback tracking, this has to * use some other means. */ static int fuse_wait_on_page_writeback(struct inode *inode, pgoff_t index) { struct fuse_inode *fi = get_fuse_inode(inode); wait_event(fi->page_waitq, !fuse_page_is_writeback(inode, index)); return 0; } static int fuse_flush(struct file *file, fl_owner_t id) { struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_file *ff = file->private_data; struct fuse_req *req; struct fuse_flush_in inarg; int err; if (is_bad_inode(inode)) return -EIO; if (fc->no_flush) return 0; req = fuse_get_req_nofail(fc, file); memset(&inarg, 0, sizeof(inarg)); inarg.fh = ff->fh; inarg.lock_owner = fuse_lock_owner_id(fc, id); req->in.h.opcode = FUSE_FLUSH; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->force = 1; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err == -ENOSYS) { fc->no_flush = 1; err = 0; } return err; } /* * Wait for all pending writepages on the inode to finish. * * This is currently done by blocking further writes with FUSE_NOWRITE * and waiting for all sent writes to complete. * * This must be called under i_mutex, otherwise the FUSE_NOWRITE usage * could conflict with truncation. */ static void fuse_sync_writes(struct inode *inode) { fuse_set_nowrite(inode); fuse_release_nowrite(inode); } int fuse_fsync_common(struct file *file, int datasync, int isdir) { struct inode *inode = file->f_mapping->host; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_file *ff = file->private_data; struct fuse_req *req; struct fuse_fsync_in inarg; int err; if (is_bad_inode(inode)) return -EIO; if ((!isdir && fc->no_fsync) || (isdir && fc->no_fsyncdir)) return 0; /* * Start writeback against all dirty pages of the inode, then * wait for all outstanding writes, before sending the FSYNC * request. */ err = write_inode_now(inode, 0); if (err) return err; fuse_sync_writes(inode); req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.fh = ff->fh; inarg.fsync_flags = datasync ? 1 : 0; req->in.h.opcode = isdir ? FUSE_FSYNCDIR : FUSE_FSYNC; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err == -ENOSYS) { if (isdir) fc->no_fsyncdir = 1; else fc->no_fsync = 1; err = 0; } return err; } static int fuse_fsync(struct file *file, int datasync) { return fuse_fsync_common(file, datasync, 0); } void fuse_read_fill(struct fuse_req *req, struct file *file, loff_t pos, size_t count, int opcode) { struct fuse_read_in *inarg = &req->misc.read.in; struct fuse_file *ff = file->private_data; inarg->fh = ff->fh; inarg->offset = pos; inarg->size = count; inarg->flags = file->f_flags; req->in.h.opcode = opcode; req->in.h.nodeid = ff->nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(struct fuse_read_in); req->in.args[0].value = inarg; req->out.argvar = 1; req->out.numargs = 1; req->out.args[0].size = count; } static size_t fuse_send_read(struct fuse_req *req, struct file *file, loff_t pos, size_t count, fl_owner_t owner) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; fuse_read_fill(req, file, pos, count, FUSE_READ); if (owner != NULL) { struct fuse_read_in *inarg = &req->misc.read.in; inarg->read_flags |= FUSE_READ_LOCKOWNER; inarg->lock_owner = fuse_lock_owner_id(fc, owner); } fuse_request_send(fc, req); return req->out.args[0].size; } static void fuse_read_update_size(struct inode *inode, loff_t size, u64 attr_ver) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); spin_lock(&fc->lock); if (attr_ver == fi->attr_version && size < inode->i_size) { fi->attr_version = ++fc->attr_version; i_size_write(inode, size); } spin_unlock(&fc->lock); } static int fuse_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; size_t num_read; loff_t pos = page_offset(page); size_t count = PAGE_CACHE_SIZE; u64 attr_ver; int err; err = -EIO; if (is_bad_inode(inode)) goto out; /* * Page writeback can extend beyond the liftime of the * page-cache page, so make sure we read a properly synced * page. */ fuse_wait_on_page_writeback(inode, page->index); req = fuse_get_req(fc); err = PTR_ERR(req); if (IS_ERR(req)) goto out; attr_ver = fuse_get_attr_version(fc); req->out.page_zeroing = 1; req->out.argpages = 1; req->num_pages = 1; req->pages[0] = page; num_read = fuse_send_read(req, file, pos, count, NULL); err = req->out.h.error; fuse_put_request(fc, req); if (!err) { /* * Short read means EOF. If file size is larger, truncate it */ if (num_read < count) fuse_read_update_size(inode, pos + num_read, attr_ver); SetPageUptodate(page); } fuse_invalidate_attr(inode); /* atime changed */ out: unlock_page(page); return err; } static void fuse_readpages_end(struct fuse_conn *fc, struct fuse_req *req) { int i; size_t count = req->misc.read.in.size; size_t num_read = req->out.args[0].size; struct address_space *mapping = NULL; for (i = 0; mapping == NULL && i < req->num_pages; i++) mapping = req->pages[i]->mapping; if (mapping) { struct inode *inode = mapping->host; /* * Short read means EOF. If file size is larger, truncate it */ if (!req->out.h.error && num_read < count) { loff_t pos; pos = page_offset(req->pages[0]) + num_read; fuse_read_update_size(inode, pos, req->misc.read.attr_ver); } fuse_invalidate_attr(inode); /* atime changed */ } for (i = 0; i < req->num_pages; i++) { struct page *page = req->pages[i]; if (!req->out.h.error) SetPageUptodate(page); else SetPageError(page); unlock_page(page); page_cache_release(page); } if (req->ff) fuse_file_put(req->ff); } static void fuse_send_readpages(struct fuse_req *req, struct file *file) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; loff_t pos = page_offset(req->pages[0]); size_t count = req->num_pages << PAGE_CACHE_SHIFT; req->out.argpages = 1; req->out.page_zeroing = 1; req->out.page_replace = 1; fuse_read_fill(req, file, pos, count, FUSE_READ); req->misc.read.attr_ver = fuse_get_attr_version(fc); if (fc->async_read) { req->ff = fuse_file_get(ff); req->end = fuse_readpages_end; fuse_request_send_background(fc, req); } else { fuse_request_send(fc, req); fuse_readpages_end(fc, req); fuse_put_request(fc, req); } } struct fuse_fill_data { struct fuse_req *req; struct file *file; struct inode *inode; }; static int fuse_readpages_fill(void *_data, struct page *page) { struct fuse_fill_data *data = _data; struct fuse_req *req = data->req; struct inode *inode = data->inode; struct fuse_conn *fc = get_fuse_conn(inode); fuse_wait_on_page_writeback(inode, page->index); if (req->num_pages && (req->num_pages == FUSE_MAX_PAGES_PER_REQ || (req->num_pages + 1) * PAGE_CACHE_SIZE > fc->max_read || req->pages[req->num_pages - 1]->index + 1 != page->index)) { fuse_send_readpages(req, data->file); data->req = req = fuse_get_req(fc); if (IS_ERR(req)) { unlock_page(page); return PTR_ERR(req); } } page_cache_get(page); req->pages[req->num_pages] = page; req->num_pages++; return 0; } static int fuse_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { struct inode *inode = mapping->host; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_fill_data data; int err; err = -EIO; if (is_bad_inode(inode)) goto out; data.file = file; data.inode = inode; data.req = fuse_get_req(fc); err = PTR_ERR(data.req); if (IS_ERR(data.req)) goto out; err = read_cache_pages(mapping, pages, fuse_readpages_fill, &data); if (!err) { if (data.req->num_pages) fuse_send_readpages(data.req, file); else fuse_put_request(fc, data.req); } out: return err; } static ssize_t fuse_file_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct inode *inode = iocb->ki_filp->f_mapping->host; if (pos + iov_length(iov, nr_segs) > i_size_read(inode)) { int err; /* * If trying to read past EOF, make sure the i_size * attribute is up-to-date. */ err = fuse_update_attributes(inode, NULL, iocb->ki_filp, NULL); if (err) return err; } return generic_file_aio_read(iocb, iov, nr_segs, pos); } static void fuse_write_fill(struct fuse_req *req, struct fuse_file *ff, loff_t pos, size_t count) { struct fuse_write_in *inarg = &req->misc.write.in; struct fuse_write_out *outarg = &req->misc.write.out; inarg->fh = ff->fh; inarg->offset = pos; inarg->size = count; req->in.h.opcode = FUSE_WRITE; req->in.h.nodeid = ff->nodeid; req->in.numargs = 2; if (ff->fc->minor < 9) req->in.args[0].size = FUSE_COMPAT_WRITE_IN_SIZE; else req->in.args[0].size = sizeof(struct fuse_write_in); req->in.args[0].value = inarg; req->in.args[1].size = count; req->out.numargs = 1; req->out.args[0].size = sizeof(struct fuse_write_out); req->out.args[0].value = outarg; } static size_t fuse_send_write(struct fuse_req *req, struct file *file, loff_t pos, size_t count, fl_owner_t owner) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; struct fuse_write_in *inarg = &req->misc.write.in; fuse_write_fill(req, ff, pos, count); inarg->flags = file->f_flags; if (owner != NULL) { inarg->write_flags |= FUSE_WRITE_LOCKOWNER; inarg->lock_owner = fuse_lock_owner_id(fc, owner); } fuse_request_send(fc, req); return req->misc.write.out.size; } static int fuse_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { pgoff_t index = pos >> PAGE_CACHE_SHIFT; *pagep = grab_cache_page_write_begin(mapping, index, flags); if (!*pagep) return -ENOMEM; return 0; } void fuse_write_update_size(struct inode *inode, loff_t pos) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); spin_lock(&fc->lock); fi->attr_version = ++fc->attr_version; if (pos > inode->i_size) i_size_write(inode, pos); spin_unlock(&fc->lock); } static int fuse_buffered_write(struct file *file, struct inode *inode, loff_t pos, unsigned count, struct page *page) { int err; size_t nres; struct fuse_conn *fc = get_fuse_conn(inode); unsigned offset = pos & (PAGE_CACHE_SIZE - 1); struct fuse_req *req; if (is_bad_inode(inode)) return -EIO; /* * Make sure writepages on the same page are not mixed up with * plain writes. */ fuse_wait_on_page_writeback(inode, page->index); req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); req->in.argpages = 1; req->num_pages = 1; req->pages[0] = page; req->page_offset = offset; nres = fuse_send_write(req, file, pos, count, NULL); err = req->out.h.error; fuse_put_request(fc, req); if (!err && !nres) err = -EIO; if (!err) { pos += nres; fuse_write_update_size(inode, pos); if (count == PAGE_CACHE_SIZE) SetPageUptodate(page); } fuse_invalidate_attr(inode); return err ? err : nres; } static int fuse_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { struct inode *inode = mapping->host; int res = 0; if (copied) res = fuse_buffered_write(file, inode, pos, copied, page); unlock_page(page); page_cache_release(page); return res; } static size_t fuse_send_write_pages(struct fuse_req *req, struct file *file, struct inode *inode, loff_t pos, size_t count) { size_t res; unsigned offset; unsigned i; for (i = 0; i < req->num_pages; i++) fuse_wait_on_page_writeback(inode, req->pages[i]->index); res = fuse_send_write(req, file, pos, count, NULL); offset = req->page_offset; count = res; for (i = 0; i < req->num_pages; i++) { struct page *page = req->pages[i]; if (!req->out.h.error && !offset && count >= PAGE_CACHE_SIZE) SetPageUptodate(page); if (count > PAGE_CACHE_SIZE - offset) count -= PAGE_CACHE_SIZE - offset; else count = 0; offset = 0; unlock_page(page); page_cache_release(page); } return res; } static ssize_t fuse_fill_write_pages(struct fuse_req *req, struct address_space *mapping, struct iov_iter *ii, loff_t pos) { struct fuse_conn *fc = get_fuse_conn(mapping->host); unsigned offset = pos & (PAGE_CACHE_SIZE - 1); size_t count = 0; int err; req->in.argpages = 1; req->page_offset = offset; do { size_t tmp; struct page *page; pgoff_t index = pos >> PAGE_CACHE_SHIFT; size_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset, iov_iter_count(ii)); bytes = min_t(size_t, bytes, fc->max_write - count); again: err = -EFAULT; if (iov_iter_fault_in_readable(ii, bytes)) break; err = -ENOMEM; page = grab_cache_page_write_begin(mapping, index, 0); if (!page) break; if (mapping_writably_mapped(mapping)) flush_dcache_page(page); pagefault_disable(); tmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes); pagefault_enable(); flush_dcache_page(page); if (!tmp) { unlock_page(page); page_cache_release(page); bytes = min(bytes, iov_iter_single_seg_count(ii)); goto again; } err = 0; req->pages[req->num_pages] = page; req->num_pages++; iov_iter_advance(ii, tmp); count += tmp; pos += tmp; offset += tmp; if (offset == PAGE_CACHE_SIZE) offset = 0; if (!fc->big_writes) break; } while (iov_iter_count(ii) && count < fc->max_write && req->num_pages < FUSE_MAX_PAGES_PER_REQ && offset == 0); return count > 0 ? count : err; } static ssize_t fuse_perform_write(struct file *file, struct address_space *mapping, struct iov_iter *ii, loff_t pos) { struct inode *inode = mapping->host; struct fuse_conn *fc = get_fuse_conn(inode); int err = 0; ssize_t res = 0; if (is_bad_inode(inode)) return -EIO; do { struct fuse_req *req; ssize_t count; req = fuse_get_req(fc); if (IS_ERR(req)) { err = PTR_ERR(req); break; } count = fuse_fill_write_pages(req, mapping, ii, pos); if (count <= 0) { err = count; } else { size_t num_written; num_written = fuse_send_write_pages(req, file, inode, pos, count); err = req->out.h.error; if (!err) { res += num_written; pos += num_written; /* break out of the loop on short write */ if (num_written != count) err = -EIO; } } fuse_put_request(fc, req); } while (!err && iov_iter_count(ii)); if (res > 0) fuse_write_update_size(inode, pos); fuse_invalidate_attr(inode); return res > 0 ? res : err; } static ssize_t fuse_file_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct file *file = iocb->ki_filp; struct address_space *mapping = file->f_mapping; size_t count = 0; ssize_t written = 0; struct inode *inode = mapping->host; ssize_t err; struct iov_iter i; WARN_ON(iocb->ki_pos != pos); err = generic_segment_checks(iov, &nr_segs, &count, VERIFY_READ); if (err) return err; mutex_lock(&inode->i_mutex); vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE); /* We can write back this queue in page reclaim */ current->backing_dev_info = mapping->backing_dev_info; err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode)); if (err) goto out; if (count == 0) goto out; err = file_remove_suid(file); if (err) goto out; file_update_time(file); iov_iter_init(&i, iov, nr_segs, count, 0); written = fuse_perform_write(file, mapping, &i, pos); if (written >= 0) iocb->ki_pos = pos + written; out: current->backing_dev_info = NULL; mutex_unlock(&inode->i_mutex); return written ? written : err; } static void fuse_release_user_pages(struct fuse_req *req, int write) { unsigned i; for (i = 0; i < req->num_pages; i++) { struct page *page = req->pages[i]; if (write) set_page_dirty_lock(page); put_page(page); } } static int fuse_get_user_pages(struct fuse_req *req, const char __user *buf, size_t *nbytesp, int write) { size_t nbytes = *nbytesp; unsigned long user_addr = (unsigned long) buf; unsigned offset = user_addr & ~PAGE_MASK; int npages; /* Special case for kernel I/O: can copy directly into the buffer */ if (segment_eq(get_fs(), KERNEL_DS)) { if (write) req->in.args[1].value = (void *) user_addr; else req->out.args[0].value = (void *) user_addr; return 0; } nbytes = min_t(size_t, nbytes, FUSE_MAX_PAGES_PER_REQ << PAGE_SHIFT); npages = (nbytes + offset + PAGE_SIZE - 1) >> PAGE_SHIFT; npages = clamp(npages, 1, FUSE_MAX_PAGES_PER_REQ); npages = get_user_pages_fast(user_addr, npages, !write, req->pages); if (npages < 0) return npages; req->num_pages = npages; req->page_offset = offset; if (write) req->in.argpages = 1; else req->out.argpages = 1; nbytes = (req->num_pages << PAGE_SHIFT) - req->page_offset; *nbytesp = min(*nbytesp, nbytes); return 0; } ssize_t fuse_direct_io(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int write) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; size_t nmax = write ? fc->max_write : fc->max_read; loff_t pos = *ppos; ssize_t res = 0; struct fuse_req *req; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); while (count) { size_t nres; fl_owner_t owner = current->files; size_t nbytes = min(count, nmax); int err = fuse_get_user_pages(req, buf, &nbytes, write); if (err) { res = err; break; } if (write) nres = fuse_send_write(req, file, pos, nbytes, owner); else nres = fuse_send_read(req, file, pos, nbytes, owner); fuse_release_user_pages(req, !write); if (req->out.h.error) { if (!res) res = req->out.h.error; break; } else if (nres > nbytes) { res = -EIO; break; } count -= nres; res += nres; pos += nres; buf += nres; if (nres != nbytes) break; if (count) { fuse_put_request(fc, req); req = fuse_get_req(fc); if (IS_ERR(req)) break; } } if (!IS_ERR(req)) fuse_put_request(fc, req); if (res > 0) *ppos = pos; return res; } EXPORT_SYMBOL_GPL(fuse_direct_io); static ssize_t fuse_direct_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { ssize_t res; struct inode *inode = file->f_path.dentry->d_inode; if (is_bad_inode(inode)) return -EIO; res = fuse_direct_io(file, buf, count, ppos, 0); fuse_invalidate_attr(inode); return res; } static ssize_t fuse_direct_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct inode *inode = file->f_path.dentry->d_inode; ssize_t res; if (is_bad_inode(inode)) return -EIO; /* Don't allow parallel writes to the same file */ mutex_lock(&inode->i_mutex); res = generic_write_checks(file, ppos, &count, 0); if (!res) { res = fuse_direct_io(file, buf, count, ppos, 1); if (res > 0) fuse_write_update_size(inode, *ppos); } mutex_unlock(&inode->i_mutex); fuse_invalidate_attr(inode); return res; } static void fuse_writepage_free(struct fuse_conn *fc, struct fuse_req *req) { __free_page(req->pages[0]); fuse_file_put(req->ff); } static void fuse_writepage_finish(struct fuse_conn *fc, struct fuse_req *req) { struct inode *inode = req->inode; struct fuse_inode *fi = get_fuse_inode(inode); struct backing_dev_info *bdi = inode->i_mapping->backing_dev_info; list_del(&req->writepages_entry); dec_bdi_stat(bdi, BDI_WRITEBACK); dec_zone_page_state(req->pages[0], NR_WRITEBACK_TEMP); bdi_writeout_inc(bdi); wake_up(&fi->page_waitq); } /* Called under fc->lock, may release and reacquire it */ static void fuse_send_writepage(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) __acquires(fc->lock) { struct fuse_inode *fi = get_fuse_inode(req->inode); loff_t size = i_size_read(req->inode); struct fuse_write_in *inarg = &req->misc.write.in; if (!fc->connected) goto out_free; if (inarg->offset + PAGE_CACHE_SIZE <= size) { inarg->size = PAGE_CACHE_SIZE; } else if (inarg->offset < size) { inarg->size = size & (PAGE_CACHE_SIZE - 1); } else { /* Got truncated off completely */ goto out_free; } req->in.args[1].size = inarg->size; fi->writectr++; fuse_request_send_background_locked(fc, req); return; out_free: fuse_writepage_finish(fc, req); spin_unlock(&fc->lock); fuse_writepage_free(fc, req); fuse_put_request(fc, req); spin_lock(&fc->lock); } /* * If fi->writectr is positive (no truncate or fsync going on) send * all queued writepage requests. * * Called with fc->lock */ void fuse_flush_writepages(struct inode *inode) __releases(fc->lock) __acquires(fc->lock) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_req *req; while (fi->writectr >= 0 && !list_empty(&fi->queued_writes)) { req = list_entry(fi->queued_writes.next, struct fuse_req, list); list_del_init(&req->list); fuse_send_writepage(fc, req); } } static void fuse_writepage_end(struct fuse_conn *fc, struct fuse_req *req) { struct inode *inode = req->inode; struct fuse_inode *fi = get_fuse_inode(inode); mapping_set_error(inode->i_mapping, req->out.h.error); spin_lock(&fc->lock); fi->writectr--; fuse_writepage_finish(fc, req); spin_unlock(&fc->lock); fuse_writepage_free(fc, req); } static int fuse_writepage_locked(struct page *page) { struct address_space *mapping = page->mapping; struct inode *inode = mapping->host; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_req *req; struct fuse_file *ff; struct page *tmp_page; set_page_writeback(page); req = fuse_request_alloc_nofs(); if (!req) goto err; tmp_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM); if (!tmp_page) goto err_free; spin_lock(&fc->lock); BUG_ON(list_empty(&fi->write_files)); ff = list_entry(fi->write_files.next, struct fuse_file, write_entry); req->ff = fuse_file_get(ff); spin_unlock(&fc->lock); fuse_write_fill(req, ff, page_offset(page), 0); copy_highpage(tmp_page, page); req->misc.write.in.write_flags |= FUSE_WRITE_CACHE; req->in.argpages = 1; req->num_pages = 1; req->pages[0] = tmp_page; req->page_offset = 0; req->end = fuse_writepage_end; req->inode = inode; inc_bdi_stat(mapping->backing_dev_info, BDI_WRITEBACK); inc_zone_page_state(tmp_page, NR_WRITEBACK_TEMP); end_page_writeback(page); spin_lock(&fc->lock); list_add(&req->writepages_entry, &fi->writepages); list_add_tail(&req->list, &fi->queued_writes); fuse_flush_writepages(inode); spin_unlock(&fc->lock); return 0; err_free: fuse_request_free(req); err: end_page_writeback(page); return -ENOMEM; } static int fuse_writepage(struct page *page, struct writeback_control *wbc) { int err; err = fuse_writepage_locked(page); unlock_page(page); return err; } static int fuse_launder_page(struct page *page) { int err = 0; if (clear_page_dirty_for_io(page)) { struct inode *inode = page->mapping->host; err = fuse_writepage_locked(page); if (!err) fuse_wait_on_page_writeback(inode, page->index); } return err; } /* * Write back dirty pages now, because there may not be any suitable * open files later */ static void fuse_vma_close(struct vm_area_struct *vma) { filemap_write_and_wait(vma->vm_file->f_mapping); } /* * Wait for writeback against this page to complete before allowing it * to be marked dirty again, and hence written back again, possibly * before the previous writepage completed. * * Block here, instead of in ->writepage(), so that the userspace fs * can only block processes actually operating on the filesystem. * * Otherwise unprivileged userspace fs would be able to block * unrelated: * * - page migration * - sync(2) * - try_to_free_pages() with order > PAGE_ALLOC_COSTLY_ORDER */ static int fuse_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; /* * Don't use page->mapping as it may become NULL from a * concurrent truncate. */ struct inode *inode = vma->vm_file->f_mapping->host; fuse_wait_on_page_writeback(inode, page->index); return 0; } static const struct vm_operations_struct fuse_file_vm_ops = { .close = fuse_vma_close, .fault = filemap_fault, .page_mkwrite = fuse_page_mkwrite, }; static int fuse_file_mmap(struct file *file, struct vm_area_struct *vma) { if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE)) { struct inode *inode = file->f_dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_file *ff = file->private_data; /* * file may be written through mmap, so chain it onto the * inodes's write_file list */ spin_lock(&fc->lock); if (list_empty(&ff->write_entry)) list_add(&ff->write_entry, &fi->write_files); spin_unlock(&fc->lock); } file_accessed(file); vma->vm_ops = &fuse_file_vm_ops; return 0; } static int fuse_direct_mmap(struct file *file, struct vm_area_struct *vma) { /* Can't provide the coherency needed for MAP_SHARED */ if (vma->vm_flags & VM_MAYSHARE) return -ENODEV; invalidate_inode_pages2(file->f_mapping); return generic_file_mmap(file, vma); } static int convert_fuse_file_lock(const struct fuse_file_lock *ffl, struct file_lock *fl) { switch (ffl->type) { case F_UNLCK: break; case F_RDLCK: case F_WRLCK: if (ffl->start > OFFSET_MAX || ffl->end > OFFSET_MAX || ffl->end < ffl->start) return -EIO; fl->fl_start = ffl->start; fl->fl_end = ffl->end; fl->fl_pid = ffl->pid; break; default: return -EIO; } fl->fl_type = ffl->type; return 0; } static void fuse_lk_fill(struct fuse_req *req, struct file *file, const struct file_lock *fl, int opcode, pid_t pid, int flock) { struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_file *ff = file->private_data; struct fuse_lk_in *arg = &req->misc.lk_in; arg->fh = ff->fh; arg->owner = fuse_lock_owner_id(fc, fl->fl_owner); arg->lk.start = fl->fl_start; arg->lk.end = fl->fl_end; arg->lk.type = fl->fl_type; arg->lk.pid = pid; if (flock) arg->lk_flags |= FUSE_LK_FLOCK; req->in.h.opcode = opcode; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(*arg); req->in.args[0].value = arg; } static int fuse_getlk(struct file *file, struct file_lock *fl) { struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_lk_out outarg; int err; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); fuse_lk_fill(req, file, fl, FUSE_GETLK, 0, 0); req->out.numargs = 1; req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (!err) err = convert_fuse_file_lock(&outarg.lk, fl); return err; } static int fuse_setlk(struct file *file, struct file_lock *fl, int flock) { struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; int opcode = (fl->fl_flags & FL_SLEEP) ? FUSE_SETLKW : FUSE_SETLK; pid_t pid = fl->fl_type != F_UNLCK ? current->tgid : 0; int err; if (fl->fl_lmops && fl->fl_lmops->fl_grant) { /* NLM needs asynchronous locks, which we don't support yet */ return -ENOLCK; } /* Unlock on close is handled by the flush method */ if (fl->fl_flags & FL_CLOSE) return 0; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); fuse_lk_fill(req, file, fl, opcode, pid, flock); fuse_request_send(fc, req); err = req->out.h.error; /* locking is restartable */ if (err == -EINTR) err = -ERESTARTSYS; fuse_put_request(fc, req); return err; } static int fuse_file_lock(struct file *file, int cmd, struct file_lock *fl) { struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); int err; if (cmd == F_CANCELLK) { err = 0; } else if (cmd == F_GETLK) { if (fc->no_lock) { posix_test_lock(file, fl); err = 0; } else err = fuse_getlk(file, fl); } else { if (fc->no_lock) err = posix_lock_file(file, fl, NULL); else err = fuse_setlk(file, fl, 0); } return err; } static int fuse_file_flock(struct file *file, int cmd, struct file_lock *fl) { struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); int err; if (fc->no_lock) { err = flock_lock_file_wait(file, fl); } else { /* emulate flock with POSIX locks */ fl->fl_owner = (fl_owner_t) file; err = fuse_setlk(file, fl, 1); } return err; } static sector_t fuse_bmap(struct address_space *mapping, sector_t block) { struct inode *inode = mapping->host; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_bmap_in inarg; struct fuse_bmap_out outarg; int err; if (!inode->i_sb->s_bdev || fc->no_bmap) return 0; req = fuse_get_req(fc); if (IS_ERR(req)) return 0; memset(&inarg, 0, sizeof(inarg)); inarg.block = block; inarg.blocksize = inode->i_sb->s_blocksize; req->in.h.opcode = FUSE_BMAP; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->out.numargs = 1; req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err == -ENOSYS) fc->no_bmap = 1; return err ? 0 : outarg.block; } static loff_t fuse_file_llseek(struct file *file, loff_t offset, int origin) { loff_t retval; struct inode *inode = file->f_path.dentry->d_inode; mutex_lock(&inode->i_mutex); switch (origin) { case SEEK_END: retval = fuse_update_attributes(inode, NULL, file, NULL); if (retval) goto exit; offset += i_size_read(inode); break; case SEEK_CUR: offset += file->f_pos; } retval = -EINVAL; if (offset >= 0 && offset <= inode->i_sb->s_maxbytes) { if (offset != file->f_pos) { file->f_pos = offset; file->f_version = 0; } retval = offset; } exit: mutex_unlock(&inode->i_mutex); return retval; } static int fuse_ioctl_copy_user(struct page **pages, struct iovec *iov, unsigned int nr_segs, size_t bytes, bool to_user) { struct iov_iter ii; int page_idx = 0; if (!bytes) return 0; iov_iter_init(&ii, iov, nr_segs, bytes, 0); while (iov_iter_count(&ii)) { struct page *page = pages[page_idx++]; size_t todo = min_t(size_t, PAGE_SIZE, iov_iter_count(&ii)); void *kaddr; kaddr = kmap(page); while (todo) { char __user *uaddr = ii.iov->iov_base + ii.iov_offset; size_t iov_len = ii.iov->iov_len - ii.iov_offset; size_t copy = min(todo, iov_len); size_t left; if (!to_user) left = copy_from_user(kaddr, uaddr, copy); else left = copy_to_user(uaddr, kaddr, copy); if (unlikely(left)) return -EFAULT; iov_iter_advance(&ii, copy); todo -= copy; kaddr += copy; } kunmap(page); } return 0; } /* * CUSE servers compiled on 32bit broke on 64bit kernels because the * ABI was defined to be 'struct iovec' which is different on 32bit * and 64bit. Fortunately we can determine which structure the server * used from the size of the reply. */ static int fuse_copy_ioctl_iovec(struct iovec *dst, void *src, size_t transferred, unsigned count, bool is_compat) { #ifdef CONFIG_COMPAT if (count * sizeof(struct compat_iovec) == transferred) { struct compat_iovec *ciov = src; unsigned i; /* * With this interface a 32bit server cannot support * non-compat (i.e. ones coming from 64bit apps) ioctl * requests */ if (!is_compat) return -EINVAL; for (i = 0; i < count; i++) { dst[i].iov_base = compat_ptr(ciov[i].iov_base); dst[i].iov_len = ciov[i].iov_len; } return 0; } #endif if (count * sizeof(struct iovec) != transferred) return -EIO; memcpy(dst, src, transferred); return 0; } /* * For ioctls, there is no generic way to determine how much memory * needs to be read and/or written. Furthermore, ioctls are allowed * to dereference the passed pointer, so the parameter requires deep * copying but FUSE has no idea whatsoever about what to copy in or * out. * * This is solved by allowing FUSE server to retry ioctl with * necessary in/out iovecs. Let's assume the ioctl implementation * needs to read in the following structure. * * struct a { * char *buf; * size_t buflen; * } * * On the first callout to FUSE server, inarg->in_size and * inarg->out_size will be NULL; then, the server completes the ioctl * with FUSE_IOCTL_RETRY set in out->flags, out->in_iovs set to 1 and * the actual iov array to * * { { .iov_base = inarg.arg, .iov_len = sizeof(struct a) } } * * which tells FUSE to copy in the requested area and retry the ioctl. * On the second round, the server has access to the structure and * from that it can tell what to look for next, so on the invocation, * it sets FUSE_IOCTL_RETRY, out->in_iovs to 2 and iov array to * * { { .iov_base = inarg.arg, .iov_len = sizeof(struct a) }, * { .iov_base = a.buf, .iov_len = a.buflen } } * * FUSE will copy both struct a and the pointed buffer from the * process doing the ioctl and retry ioctl with both struct a and the * buffer. * * This time, FUSE server has everything it needs and completes ioctl * without FUSE_IOCTL_RETRY which finishes the ioctl call. * * Copying data out works the same way. * * Note that if FUSE_IOCTL_UNRESTRICTED is clear, the kernel * automatically initializes in and out iovs by decoding @cmd with * _IOC_* macros and the server is not allowed to request RETRY. This * limits ioctl data transfers to well-formed ioctls and is the forced * behavior for all FUSE servers. */ long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg, unsigned int flags) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; struct fuse_ioctl_in inarg = { .fh = ff->fh, .cmd = cmd, .arg = arg, .flags = flags }; struct fuse_ioctl_out outarg; struct fuse_req *req = NULL; struct page **pages = NULL; struct page *iov_page = NULL; struct iovec *in_iov = NULL, *out_iov = NULL; unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages; size_t in_size, out_size, transferred; int err; /* assume all the iovs returned by client always fits in a page */ BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE); err = -ENOMEM; pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL); iov_page = alloc_page(GFP_KERNEL); if (!pages || !iov_page) goto out; /* * If restricted, initialize IO parameters as encoded in @cmd. * RETRY from server is not allowed. */ if (!(flags & FUSE_IOCTL_UNRESTRICTED)) { struct iovec *iov = page_address(iov_page); iov->iov_base = (void __user *)arg; iov->iov_len = _IOC_SIZE(cmd); if (_IOC_DIR(cmd) & _IOC_WRITE) { in_iov = iov; in_iovs = 1; } if (_IOC_DIR(cmd) & _IOC_READ) { out_iov = iov; out_iovs = 1; } } retry: inarg.in_size = in_size = iov_length(in_iov, in_iovs); inarg.out_size = out_size = iov_length(out_iov, out_iovs); /* * Out data can be used either for actual out data or iovs, * make sure there always is at least one page. */ out_size = max_t(size_t, out_size, PAGE_SIZE); max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE); /* make sure there are enough buffer pages and init request with them */ err = -ENOMEM; if (max_pages > FUSE_MAX_PAGES_PER_REQ) goto out; while (num_pages < max_pages) { pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM); if (!pages[num_pages]) goto out; num_pages++; } req = fuse_get_req(fc); if (IS_ERR(req)) { err = PTR_ERR(req); req = NULL; goto out; } memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages); req->num_pages = num_pages; /* okay, let's send it to the client */ req->in.h.opcode = FUSE_IOCTL; req->in.h.nodeid = ff->nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; if (in_size) { req->in.numargs++; req->in.args[1].size = in_size; req->in.argpages = 1; err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size, false); if (err) goto out; } req->out.numargs = 2; req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; req->out.args[1].size = out_size; req->out.argpages = 1; req->out.argvar = 1; fuse_request_send(fc, req); err = req->out.h.error; transferred = req->out.args[1].size; fuse_put_request(fc, req); req = NULL; if (err) goto out; /* did it ask for retry? */ if (outarg.flags & FUSE_IOCTL_RETRY) { char *vaddr; /* no retry if in restricted mode */ err = -EIO; if (!(flags & FUSE_IOCTL_UNRESTRICTED)) goto out; in_iovs = outarg.in_iovs; out_iovs = outarg.out_iovs; /* * Make sure things are in boundary, separate checks * are to protect against overflow. */ err = -ENOMEM; if (in_iovs > FUSE_IOCTL_MAX_IOV || out_iovs > FUSE_IOCTL_MAX_IOV || in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV) goto out; vaddr = kmap_atomic(pages[0], KM_USER0); err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr, transferred, in_iovs + out_iovs, (flags & FUSE_IOCTL_COMPAT) != 0); kunmap_atomic(vaddr, KM_USER0); if (err) goto out; in_iov = page_address(iov_page); out_iov = in_iov + in_iovs; goto retry; } err = -EIO; if (transferred > inarg.out_size) goto out; err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true); out: if (req) fuse_put_request(fc, req); if (iov_page) __free_page(iov_page); while (num_pages) __free_page(pages[--num_pages]); kfree(pages); return err ? err : outarg.result; } EXPORT_SYMBOL_GPL(fuse_do_ioctl); static long fuse_file_ioctl_common(struct file *file, unsigned int cmd, unsigned long arg, unsigned int flags) { struct inode *inode = file->f_dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); if (!fuse_allow_task(fc, current)) return -EACCES; if (is_bad_inode(inode)) return -EIO; return fuse_do_ioctl(file, cmd, arg, flags); } static long fuse_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return fuse_file_ioctl_common(file, cmd, arg, 0); } static long fuse_file_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return fuse_file_ioctl_common(file, cmd, arg, FUSE_IOCTL_COMPAT); } /* * All files which have been polled are linked to RB tree * fuse_conn->polled_files which is indexed by kh. Walk the tree and * find the matching one. */ static struct rb_node **fuse_find_polled_node(struct fuse_conn *fc, u64 kh, struct rb_node **parent_out) { struct rb_node **link = &fc->polled_files.rb_node; struct rb_node *last = NULL; while (*link) { struct fuse_file *ff; last = *link; ff = rb_entry(last, struct fuse_file, polled_node); if (kh < ff->kh) link = &last->rb_left; else if (kh > ff->kh) link = &last->rb_right; else return link; } if (parent_out) *parent_out = last; return link; } /* * The file is about to be polled. Make sure it's on the polled_files * RB tree. Note that files once added to the polled_files tree are * not removed before the file is released. This is because a file * polled once is likely to be polled again. */ static void fuse_register_polled_file(struct fuse_conn *fc, struct fuse_file *ff) { spin_lock(&fc->lock); if (RB_EMPTY_NODE(&ff->polled_node)) { struct rb_node **link, *parent; link = fuse_find_polled_node(fc, ff->kh, &parent); BUG_ON(*link); rb_link_node(&ff->polled_node, parent, link); rb_insert_color(&ff->polled_node, &fc->polled_files); } spin_unlock(&fc->lock); } unsigned fuse_file_poll(struct file *file, poll_table *wait) { struct fuse_file *ff = file->private_data; struct fuse_conn *fc = ff->fc; struct fuse_poll_in inarg = { .fh = ff->fh, .kh = ff->kh }; struct fuse_poll_out outarg; struct fuse_req *req; int err; if (fc->no_poll) return DEFAULT_POLLMASK; poll_wait(file, &ff->poll_wait, wait); /* * Ask for notification iff there's someone waiting for it. * The client may ignore the flag and always notify. */ if (waitqueue_active(&ff->poll_wait)) { inarg.flags |= FUSE_POLL_SCHEDULE_NOTIFY; fuse_register_polled_file(fc, ff); } req = fuse_get_req(fc); if (IS_ERR(req)) return POLLERR; req->in.h.opcode = FUSE_POLL; req->in.h.nodeid = ff->nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->out.numargs = 1; req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (!err) return outarg.revents; if (err == -ENOSYS) { fc->no_poll = 1; return DEFAULT_POLLMASK; } return POLLERR; } EXPORT_SYMBOL_GPL(fuse_file_poll); /* * This is called from fuse_handle_notify() on FUSE_NOTIFY_POLL and * wakes up the poll waiters. */ int fuse_notify_poll_wakeup(struct fuse_conn *fc, struct fuse_notify_poll_wakeup_out *outarg) { u64 kh = outarg->kh; struct rb_node **link; spin_lock(&fc->lock); link = fuse_find_polled_node(fc, kh, NULL); if (*link) { struct fuse_file *ff; ff = rb_entry(*link, struct fuse_file, polled_node); wake_up_interruptible_sync(&ff->poll_wait); } spin_unlock(&fc->lock); return 0; } static const struct file_operations fuse_file_operations = { .llseek = fuse_file_llseek, .read = do_sync_read, .aio_read = fuse_file_aio_read, .write = do_sync_write, .aio_write = fuse_file_aio_write, .mmap = fuse_file_mmap, .open = fuse_open, .flush = fuse_flush, .release = fuse_release, .fsync = fuse_fsync, .lock = fuse_file_lock, .flock = fuse_file_flock, .splice_read = generic_file_splice_read, .unlocked_ioctl = fuse_file_ioctl, .compat_ioctl = fuse_file_compat_ioctl, .poll = fuse_file_poll, }; static const struct file_operations fuse_direct_io_file_operations = { .llseek = fuse_file_llseek, .read = fuse_direct_read, .write = fuse_direct_write, .mmap = fuse_direct_mmap, .open = fuse_open, .flush = fuse_flush, .release = fuse_release, .fsync = fuse_fsync, .lock = fuse_file_lock, .flock = fuse_file_flock, .unlocked_ioctl = fuse_file_ioctl, .compat_ioctl = fuse_file_compat_ioctl, .poll = fuse_file_poll, /* no splice_read */ }; static const struct address_space_operations fuse_file_aops = { .readpage = fuse_readpage, .writepage = fuse_writepage, .launder_page = fuse_launder_page, .write_begin = fuse_write_begin, .write_end = fuse_write_end, .readpages = fuse_readpages, .set_page_dirty = __set_page_dirty_nobuffers, .bmap = fuse_bmap, }; void fuse_init_file_inode(struct inode *inode) { inode->i_fop = &fuse_file_operations; inode->i_data.a_ops = &fuse_file_aops; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4721_0
crossvul-cpp_data_good_2209_0
/* * Copyright 2011-2013 Con Kolivas * Copyright 2010 Jeff Garzik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. See COPYING for more details. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <stdarg.h> #include <string.h> #include <jansson.h> #ifdef HAVE_LIBCURL #include <curl/curl.h> #endif #include <time.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #ifndef WIN32 #include <fcntl.h> # ifdef __linux__ # include <sys/prctl.h> # endif # include <sys/socket.h> # include <netinet/in.h> # include <netinet/tcp.h> # include <netdb.h> #else # include <windows.h> # include <winsock2.h> # include <ws2tcpip.h> # include <mmsystem.h> #endif #include "miner.h" #include "elist.h" #include "compat.h" #include "util.h" #include "pool.h" #define DEFAULT_SOCKWAIT 60 extern double opt_diff_mult; bool successful_connect = false; static void keep_sockalive(SOCKETTYPE fd) { const int tcp_one = 1; #ifndef WIN32 const int tcp_keepidle = 45; const int tcp_keepintvl = 30; int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, O_NONBLOCK | flags); #else u_long flags = 1; ioctlsocket(fd, FIONBIO, &flags); #endif setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one)); if (!opt_delaynet) #ifndef __linux setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&tcp_one, sizeof(tcp_one)); #else /* __linux */ setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one)); setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one)); setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle)); setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl)); #endif /* __linux__ */ #ifdef __APPLE_CC__ setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl)); #endif /* __APPLE_CC__ */ } struct tq_ent { void *data; struct list_head q_node; }; #ifdef HAVE_LIBCURL struct timeval nettime; struct data_buffer { void *buf; size_t len; }; struct upload_buffer { const void *buf; size_t len; }; struct header_info { char *lp_path; int rolltime; char *reason; char *stratum_url; bool hadrolltime; bool canroll; bool hadexpire; }; static void databuf_free(struct data_buffer *db) { if (!db) return; free(db->buf); memset(db, 0, sizeof(*db)); } static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb, void *user_data) { struct data_buffer *db = (struct data_buffer *)user_data; size_t len = size * nmemb; size_t oldlen, newlen; void *newmem; static const unsigned char zero = 0; oldlen = db->len; newlen = oldlen + len; newmem = realloc(db->buf, newlen + 1); if (!newmem) return 0; db->buf = newmem; db->len = newlen; memcpy((uint8_t*)db->buf + oldlen, ptr, len); memcpy((uint8_t*)db->buf + newlen, &zero, 1); /* null terminate */ return len; } static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb, void *user_data) { struct upload_buffer *ub = (struct upload_buffer *)user_data; unsigned int len = size * nmemb; if (len > ub->len) len = ub->len; if (len) { memcpy(ptr, ub->buf, len); ub->buf = (uint8_t*)ub->buf + len; ub->len -= len; } return len; } static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data) { struct header_info *hi = (struct header_info *)user_data; size_t remlen, slen, ptrlen = size * nmemb; char *rem, *val = NULL, *key = NULL; void *tmp; val = (char *)calloc(1, ptrlen); key = (char *)calloc(1, ptrlen); if (!key || !val) goto out; tmp = memchr(ptr, ':', ptrlen); if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */ goto out; slen = (uint8_t*)tmp - (uint8_t*)ptr; if ((slen + 1) == ptrlen) /* skip key w/ no value */ goto out; memcpy(key, ptr, slen); /* store & nul term key */ key[slen] = 0; rem = (char*)ptr + slen + 1; /* trim value's leading whitespace */ remlen = ptrlen - slen - 1; while ((remlen > 0) && (isspace(*rem))) { remlen--; rem++; } memcpy(val, rem, remlen); /* store value, trim trailing ws */ val[remlen] = 0; while ((*val) && (isspace(val[strlen(val) - 1]))) val[strlen(val) - 1] = 0; if (!*val) /* skip blank value */ goto out; if (opt_protocol) applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val); if (!strcasecmp("X-Roll-Ntime", key)) { hi->hadrolltime = true; if (!strncasecmp("N", val, 1)) applog(LOG_DEBUG, "X-Roll-Ntime: N found"); else { hi->canroll = true; /* Check to see if expire= is supported and if not, set * the rolltime to the default scantime */ if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) { sscanf(val + 7, "%d", &hi->rolltime); hi->hadexpire = true; } else hi->rolltime = opt_scantime; applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime); } } if (!strcasecmp("X-Long-Polling", key)) { hi->lp_path = val; /* steal memory reference */ val = NULL; } if (!strcasecmp("X-Reject-Reason", key)) { hi->reason = val; /* steal memory reference */ val = NULL; } if (!strcasecmp("X-Stratum", key)) { hi->stratum_url = val; val = NULL; } out: free(key); free(val); return ptrlen; } static void last_nettime(struct timeval *last) { rd_lock(&netacc_lock); last->tv_sec = nettime.tv_sec; last->tv_usec = nettime.tv_usec; rd_unlock(&netacc_lock); } static void set_nettime(void) { wr_lock(&netacc_lock); cgtime(&nettime); wr_unlock(&netacc_lock); } #if CURL_HAS_KEEPALIVE static void keep_curlalive(CURL *curl) { const long int keepalive = 1; curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive); curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, opt_tcp_keepalive); curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, opt_tcp_keepalive); } #else static void keep_curlalive(CURL *curl) { SOCKETTYPE sock; curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock); keep_sockalive(sock); } #endif static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type, __maybe_unused char *data, size_t size, void *userdata) { struct pool *pool = (struct pool *)userdata; switch(type) { case CURLINFO_HEADER_IN: case CURLINFO_DATA_IN: case CURLINFO_SSL_DATA_IN: pool->sgminer_pool_stats.net_bytes_received += size; break; case CURLINFO_HEADER_OUT: case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_OUT: pool->sgminer_pool_stats.net_bytes_sent += size; break; case CURLINFO_TEXT: default: break; } return 0; } json_t *json_rpc_call(CURL *curl, const char *url, const char *userpass, const char *rpc_req, bool probe, bool longpoll, int *rolltime, struct pool *pool, bool share) { long timeout = longpoll ? (60 * 60) : 60; struct data_buffer all_data = {NULL, 0}; struct header_info hi = {NULL, 0, NULL, NULL, false, false, false}; char len_hdr[64], user_agent_hdr[128]; char curl_err_str[CURL_ERROR_SIZE]; struct curl_slist *headers = NULL; struct upload_buffer upload_data; json_t *val, *err_val, *res_val; bool probing = false; double byte_count; json_error_t err; int rc; memset(&err, 0, sizeof(err)); /* it is assumed that 'curl' is freshly [re]initialized at this pt */ if (probe) probing = !pool->probed; curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb); curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); /* Shares are staggered already and delays in submission can be costly * so do not delay them */ if (!opt_delaynet || share) curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data); curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data); curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi); curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY); if (pool->rpc_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype); } else if (opt_socks_proxy) { curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy); curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4); } if (userpass) { curl_easy_setopt(curl, CURLOPT_USERPWD, userpass); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } if (longpoll) keep_curlalive(curl); curl_easy_setopt(curl, CURLOPT_POST, 1); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req); upload_data.buf = rpc_req; upload_data.len = strlen(rpc_req); sprintf(len_hdr, "Content-Length: %lu", (unsigned long) upload_data.len); sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING); headers = curl_slist_append(headers, "Content-type: application/json"); headers = curl_slist_append(headers, "X-Mining-Extensions: longpoll midstate rollntime submitold"); if (likely(global_hashrate)) { char ghashrate[255]; sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate); headers = curl_slist_append(headers, ghashrate); } headers = curl_slist_append(headers, len_hdr); headers = curl_slist_append(headers, user_agent_hdr); headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); if (opt_delaynet) { /* Don't delay share submission, but still track the nettime */ if (!share) { long long now_msecs, last_msecs; struct timeval now, last; cgtime(&now); last_nettime(&last); now_msecs = (long long)now.tv_sec * 1000; now_msecs += now.tv_usec / 1000; last_msecs = (long long)last.tv_sec * 1000; last_msecs += last.tv_usec / 1000; if (now_msecs > last_msecs && now_msecs - last_msecs < 250) { struct timespec rgtp; rgtp.tv_sec = 0; rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000; nanosleep(&rgtp, NULL); } } set_nettime(); } rc = curl_easy_perform(curl); if (rc) { applog(LOG_INFO, "HTTP request failed: %s", curl_err_str); goto err_out; } if (!all_data.buf) { applog(LOG_DEBUG, "Empty data received in json_rpc_call."); goto err_out; } pool->sgminer_pool_stats.times_sent++; if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK) pool->sgminer_pool_stats.bytes_sent += byte_count; pool->sgminer_pool_stats.times_received++; if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK) pool->sgminer_pool_stats.bytes_received += byte_count; if (probing) { pool->probed = true; /* If X-Long-Polling was found, activate long polling */ if (hi.lp_path) { if (pool->hdr_path != NULL) free(pool->hdr_path); pool->hdr_path = hi.lp_path; } else pool->hdr_path = NULL; if (hi.stratum_url) { pool->stratum_url = hi.stratum_url; hi.stratum_url = NULL; } } else { if (hi.lp_path) { free(hi.lp_path); hi.lp_path = NULL; } if (hi.stratum_url) { free(hi.stratum_url); hi.stratum_url = NULL; } } *rolltime = hi.rolltime; pool->sgminer_pool_stats.rolltime = hi.rolltime; pool->sgminer_pool_stats.hadrolltime = hi.hadrolltime; pool->sgminer_pool_stats.canroll = hi.canroll; pool->sgminer_pool_stats.hadexpire = hi.hadexpire; val = JSON_LOADS((const char *)all_data.buf, &err); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); if (opt_protocol) applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf)); goto err_out; } if (opt_protocol) { char *s = json_dumps(val, JSON_INDENT(3)); applog(LOG_DEBUG, "JSON protocol response:\n%s", s); free(s); } /* JSON-RPC valid response returns a non-null 'result', * and a null 'error'. */ res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val ||(err_val && !json_is_null(err_val))) { char *s; if (err_val) s = json_dumps(err_val, JSON_INDENT(3)); else s = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC call failed: %s", s); free(s); goto err_out; } if (hi.reason) { json_object_set_new(val, "reject-reason", json_string(hi.reason)); free(hi.reason); hi.reason = NULL; } successful_connect = true; databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); return val; err_out: databuf_free(&all_data); curl_slist_free_all(headers); curl_easy_reset(curl); if (!successful_connect) applog(LOG_DEBUG, "Failed to connect in json_rpc_call"); curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1); return NULL; } #define PROXY_HTTP CURLPROXY_HTTP #define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0 #define PROXY_SOCKS4 CURLPROXY_SOCKS4 #define PROXY_SOCKS5 CURLPROXY_SOCKS5 #define PROXY_SOCKS4A CURLPROXY_SOCKS4A #define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME #else /* HAVE_LIBCURL */ #define PROXY_HTTP 0 #define PROXY_HTTP_1_0 1 #define PROXY_SOCKS4 2 #define PROXY_SOCKS5 3 #define PROXY_SOCKS4A 4 #define PROXY_SOCKS5H 5 #endif /* HAVE_LIBCURL */ static struct { const char *name; proxytypes_t proxytype; } proxynames[] = { { "http:", PROXY_HTTP }, { "http0:", PROXY_HTTP_1_0 }, { "socks4:", PROXY_SOCKS4 }, { "socks5:", PROXY_SOCKS5 }, { "socks4a:", PROXY_SOCKS4A }, { "socks5h:", PROXY_SOCKS5H }, { NULL, (proxytypes_t)NULL } }; const char *proxytype(proxytypes_t proxytype) { int i; for (i = 0; proxynames[i].name; i++) if (proxynames[i].proxytype == proxytype) return proxynames[i].name; return "invalid"; } char *get_proxy(char *url, struct pool *pool) { pool->rpc_proxy = NULL; char *split; int plen, len, i; for (i = 0; proxynames[i].name; i++) { plen = strlen(proxynames[i].name); if (strncmp(url, proxynames[i].name, plen) == 0) { if (!(split = strchr(url, '|'))) return url; *split = '\0'; len = split - url; pool->rpc_proxy = (char *)malloc(1 + len - plen); if (!(pool->rpc_proxy)) quithere(1, "Failed to malloc rpc_proxy"); strcpy(pool->rpc_proxy, url + plen); extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port); pool->rpc_proxytype = proxynames[i].proxytype; url = split + 1; break; } } return url; } /* Adequate size s==len*2 + 1 must be alloced to use this variant */ void __bin2hex(char *s, const unsigned char *p, size_t len) { int i; static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; for (i = 0; i < (int)len; i++) { *s++ = hex[p[i] >> 4]; *s++ = hex[p[i] & 0xF]; } *s++ = '\0'; } /* Returns a malloced array string of a binary value of arbitrary length. The * array is rounded up to a 4 byte size to appease architectures that need * aligned array sizes */ char *bin2hex(const unsigned char *p, size_t len) { ssize_t slen; char *s; slen = len * 2 + 1; if (slen % 4) slen += 4 - (slen % 4); s = (char *)calloc(slen, 1); if (unlikely(!s)) quithere(1, "Failed to calloc"); __bin2hex(s, p, len); return s; } /* Does the reverse of bin2hex but does not allocate any ram */ static const int hex2bin_tbl[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; bool hex2bin(unsigned char *p, const char *hexstr, size_t len) { int nibble1, nibble2; unsigned char idx; bool ret = false; while (*hexstr && len) { if (unlikely(!hexstr[1])) { applog(LOG_ERR, "hex2bin str truncated"); return ret; } idx = *hexstr++; nibble1 = hex2bin_tbl[idx]; idx = *hexstr++; nibble2 = hex2bin_tbl[idx]; if (unlikely((nibble1 < 0) || (nibble2 < 0))) { applog(LOG_ERR, "hex2bin scan failed"); return ret; } *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2); --len; } if (likely(len == 0 && *hexstr == 0)) ret = true; return ret; } bool fulltest(const unsigned char *hash, const unsigned char *target) { uint32_t *hash32 = (uint32_t *)hash; uint32_t *target32 = (uint32_t *)target; bool rc = true; int i; for (i = 28 / 4; i >= 0; i--) { uint32_t h32tmp = le32toh(hash32[i]); uint32_t t32tmp = le32toh(target32[i]); if (h32tmp > t32tmp) { rc = false; break; } if (h32tmp < t32tmp) { rc = true; break; } } if (opt_debug) { unsigned char hash_swap[32], target_swap[32]; char *hash_str, *target_str; swab256(hash_swap, hash); swab256(target_swap, target); hash_str = bin2hex(hash_swap, 32); target_str = bin2hex(target_swap, 32); applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s", hash_str, target_str, rc ? "YES (hash <= target)" : "no (false positive; hash > target)"); free(hash_str); free(target_str); } return rc; } struct thread_q *tq_new(void) { struct thread_q *tq; tq = (struct thread_q *)calloc(1, sizeof(*tq)); if (!tq) return NULL; INIT_LIST_HEAD(&tq->q); pthread_mutex_init(&tq->mutex, NULL); pthread_cond_init(&tq->cond, NULL); return tq; } void tq_free(struct thread_q *tq) { struct tq_ent *ent, *iter; if (!tq) return; list_for_each_entry_safe(ent, iter, &tq->q, q_node) { list_del(&ent->q_node); free(ent); } pthread_cond_destroy(&tq->cond); pthread_mutex_destroy(&tq->mutex); memset(tq, 0, sizeof(*tq)); /* poison */ free(tq); } static void tq_freezethaw(struct thread_q *tq, bool frozen) { mutex_lock(&tq->mutex); tq->frozen = frozen; pthread_cond_signal(&tq->cond); mutex_unlock(&tq->mutex); } void tq_freeze(struct thread_q *tq) { tq_freezethaw(tq, true); } void tq_thaw(struct thread_q *tq) { tq_freezethaw(tq, false); } bool tq_push(struct thread_q *tq, void *data) { struct tq_ent *ent; bool rc = true; ent = (struct tq_ent *)calloc(1, sizeof(*ent)); if (!ent) return false; ent->data = data; INIT_LIST_HEAD(&ent->q_node); mutex_lock(&tq->mutex); if (!tq->frozen) { list_add_tail(&ent->q_node, &tq->q); } else { free(ent); rc = false; } pthread_cond_signal(&tq->cond); mutex_unlock(&tq->mutex); return rc; } void *tq_pop(struct thread_q *tq, const struct timespec *abstime) { struct tq_ent *ent; void *rval = NULL; int rc; mutex_lock(&tq->mutex); if (!list_empty(&tq->q)) goto pop; if (abstime) rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime); else rc = pthread_cond_wait(&tq->cond, &tq->mutex); if (rc) goto out; if (list_empty(&tq->q)) goto out; pop: ent = list_entry(tq->q.next, struct tq_ent*, q_node); rval = ent->data; list_del(&ent->q_node); free(ent); out: mutex_unlock(&tq->mutex); return rval; } int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg) { cgsem_init(&thr->sem); return pthread_create(&thr->pth, attr, start, arg); } void thr_info_cancel(struct thr_info *thr) { if (!thr) return; if (PTH(thr) != 0L) { pthread_cancel(thr->pth); PTH(thr) = 0L; } cgsem_destroy(&thr->sem); } void subtime(struct timeval *a, struct timeval *b) { timersub(a, b, b); } void addtime(struct timeval *a, struct timeval *b) { timeradd(a, b, b); } bool time_more(struct timeval *a, struct timeval *b) { return timercmp(a, b, >); } bool time_less(struct timeval *a, struct timeval *b) { return timercmp(a, b, <); } void copy_time(struct timeval *dest, const struct timeval *src) { memcpy(dest, src, sizeof(struct timeval)); } void timespec_to_val(struct timeval *val, const struct timespec *spec) { val->tv_sec = spec->tv_sec; val->tv_usec = spec->tv_nsec / 1000; } void timeval_to_spec(struct timespec *spec, const struct timeval *val) { spec->tv_sec = val->tv_sec; spec->tv_nsec = val->tv_usec * 1000; } void us_to_timeval(struct timeval *val, int64_t us) { lldiv_t tvdiv = lldiv(us, 1000000); val->tv_sec = tvdiv.quot; val->tv_usec = tvdiv.rem; } void us_to_timespec(struct timespec *spec, int64_t us) { lldiv_t tvdiv = lldiv(us, 1000000); spec->tv_sec = tvdiv.quot; spec->tv_nsec = tvdiv.rem * 1000; } void ms_to_timespec(struct timespec *spec, int64_t ms) { lldiv_t tvdiv = lldiv(ms, 1000); spec->tv_sec = tvdiv.quot; spec->tv_nsec = tvdiv.rem * 1000000; } void ms_to_timeval(struct timeval *val, int64_t ms) { lldiv_t tvdiv = lldiv(ms, 1000); val->tv_sec = tvdiv.quot; val->tv_usec = tvdiv.rem * 1000; } void timeraddspec(struct timespec *a, const struct timespec *b) { a->tv_sec += b->tv_sec; a->tv_nsec += b->tv_nsec; if (a->tv_nsec >= 1000000000) { a->tv_nsec -= 1000000000; a->tv_sec++; } } static int __maybe_unused timespec_to_ms(struct timespec *ts) { return ts->tv_sec * 1000 + ts->tv_nsec / 1000000; } /* Subtract b from a */ static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b) { a->tv_sec -= b->tv_sec; a->tv_nsec -= b->tv_nsec; if (a->tv_nsec < 0) { a->tv_nsec += 1000000000; a->tv_sec--; } } /* These are sgminer specific sleep functions that use an absolute nanosecond * resolution timer to avoid poor usleep accuracy and overruns. */ #ifdef WIN32 /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */ #define EPOCHFILETIME (116444736000000000LL) /* Return the system time as an lldiv_t in decimicroseconds. */ static void decius_time(lldiv_t *lidiv) { FILETIME ft; LARGE_INTEGER li; GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; li.QuadPart -= EPOCHFILETIME; /* SystemTime is in decimicroseconds so divide by an unusual number */ *lidiv = lldiv(li.QuadPart, 10000000); } /* This is a sgminer gettimeofday wrapper. Since we always call gettimeofday * with tz set to NULL, and windows' default resolution is only 15ms, this * gives us higher resolution times on windows. */ void cgtime(struct timeval *tv) { lldiv_t lidiv; decius_time(&lidiv); tv->tv_sec = lidiv.quot; tv->tv_usec = lidiv.rem / 10; } #else /* WIN32 */ void cgtime(struct timeval *tv) { gettimeofday(tv, NULL); } int cgtimer_to_ms(cgtimer_t *cgt) { return timespec_to_ms(cgt); } /* Subtracts b from a and stores it in res. */ void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res) { res->tv_sec = a->tv_sec - b->tv_sec; res->tv_nsec = a->tv_nsec - b->tv_nsec; if (res->tv_nsec < 0) { res->tv_nsec += 1000000000; res->tv_sec--; } } #endif /* WIN32 */ #ifdef CLOCK_MONOTONIC /* Essentially just linux */ void cgtimer_time(cgtimer_t *ts_start) { clock_gettime(CLOCK_MONOTONIC, ts_start); } static void nanosleep_abstime(struct timespec *ts_end) { int ret; do { ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL); } while (ret == EINTR); } /* Reentrant version of cgsleep functions allow start time to be set separately * from the beginning of the actual sleep, allowing scheduling delays to be * counted in the sleep. */ void cgsleep_ms_r(cgtimer_t *ts_start, int ms) { struct timespec ts_end; ms_to_timespec(&ts_end, ms); timeraddspec(&ts_end, ts_start); nanosleep_abstime(&ts_end); } void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { struct timespec ts_end; us_to_timespec(&ts_end, us); timeraddspec(&ts_end, ts_start); nanosleep_abstime(&ts_end); } #else /* CLOCK_MONOTONIC */ #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> void cgtimer_time(cgtimer_t *ts_start) { clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts_start->tv_sec = mts.tv_sec; ts_start->tv_nsec = mts.tv_nsec; } #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */ void cgtimer_time(cgtimer_t *ts_start) { struct timeval tv; cgtime(&tv); ts_start->tv_sec = tv->tv_sec; ts_start->tv_nsec = tv->tv_usec * 1000; } #endif /* __MACH__ */ #ifdef WIN32 /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t * typedef, allowing us to have sub-microsecond resolution for times, do simple * arithmetic for timer calculations, and use windows' own hTimers to get * accurate absolute timeouts. */ int cgtimer_to_ms(cgtimer_t *cgt) { return (int)(cgt->QuadPart / 10000LL); } /* Subtracts b from a and stores it in res. */ void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res) { res->QuadPart = a->QuadPart - b->QuadPart; } /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute * timeouts with hTimers. */ void cgtimer_time(cgtimer_t *ts_start) { FILETIME ft; GetSystemTimeAsFileTime(&ft); ts_start->LowPart = ft.dwLowDateTime; ts_start->HighPart = ft.dwHighDateTime; } static void liSleep(LARGE_INTEGER *li, int timeout) { HANDLE hTimer; DWORD ret; if (unlikely(timeout <= 0)) return; hTimer = CreateWaitableTimer(NULL, TRUE, NULL); if (unlikely(!hTimer)) quit(1, "Failed to create hTimer in liSleep"); ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0); if (unlikely(!ret)) quit(1, "Failed to SetWaitableTimer in liSleep"); /* We still use a timeout as a sanity check in case the system time * is changed while we're running */ ret = WaitForSingleObject(hTimer, timeout); if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT)) quit(1, "Failed to WaitForSingleObject in liSleep"); CloseHandle(hTimer); } void cgsleep_ms_r(cgtimer_t *ts_start, int ms) { LARGE_INTEGER li; li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL; liSleep(&li, ms); } void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { LARGE_INTEGER li; int ms; li.QuadPart = ts_start->QuadPart + us * 10LL; ms = us / 1000; if (!ms) ms = 1; liSleep(&li, ms); } #else /* WIN32 */ static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start) { struct timespec now; timeraddspec(ts_diff, ts_start); cgtimer_time(&now); timersubspec(ts_diff, &now); if (unlikely(ts_diff->tv_sec < 0)) return; nanosleep(ts_diff, NULL); } void cgsleep_ms_r(cgtimer_t *ts_start, int ms) { struct timespec ts_diff; ms_to_timespec(&ts_diff, ms); cgsleep_spec(&ts_diff, ts_start); } void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { struct timespec ts_diff; us_to_timespec(&ts_diff, us); cgsleep_spec(&ts_diff, ts_start); } #endif /* WIN32 */ #endif /* CLOCK_MONOTONIC */ void cgsleep_ms(int ms) { cgtimer_t ts_start; cgsleep_prepare_r(&ts_start); cgsleep_ms_r(&ts_start, ms); } void cgsleep_us(int64_t us) { cgtimer_t ts_start; cgsleep_prepare_r(&ts_start); cgsleep_us_r(&ts_start, us); } /* Returns the microseconds difference between end and start times as a double */ double us_tdiff(struct timeval *end, struct timeval *start) { /* Sanity check. We should only be using this for small differences so * limit the max to 60 seconds. */ if (unlikely(end->tv_sec - start->tv_sec > 60)) return 60000000; return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec); } /* Returns the milliseconds difference between end and start times */ int ms_tdiff(struct timeval *end, struct timeval *start) { /* Like us_tdiff, limit to 1 hour. */ if (unlikely(end->tv_sec - start->tv_sec > 3600)) return 3600000; return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000; } /* Returns the seconds difference between end and start times as a double */ double tdiff(struct timeval *end, struct timeval *start) { return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0; } bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; if (url_len >= sizeof(url_address)) { applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'", __func__, url_len, url_begin); url_len = sizeof(url_address) - 1; } sprintf(url_address, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; } enum send_ret { SEND_OK, SEND_SELECTFAIL, SEND_SENDFAIL, SEND_INACTIVE }; /* Send a single command across a socket, appending \n to it. This should all * be done under stratum lock except when first establishing the socket */ static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len) { SOCKETTYPE sock = pool->sock; ssize_t ssent = 0; strcat(s, "\n"); len++; while (len > 0 ) { struct timeval timeout = {1, 0}; ssize_t sent; fd_set wd; retry: FD_ZERO(&wd); FD_SET(sock, &wd); if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) { if (interrupted()) goto retry; return SEND_SELECTFAIL; } #ifdef __APPLE__ sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE); #elif WIN32 sent = send(pool->sock, s + ssent, len, 0); #else sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL); #endif if (sent < 0) { if (!sock_blocks()) return SEND_SENDFAIL; sent = 0; } ssent += sent; len -= sent; } pool->sgminer_pool_stats.times_sent++; pool->sgminer_pool_stats.bytes_sent += ssent; pool->sgminer_pool_stats.net_bytes_sent += ssent; return SEND_OK; } bool stratum_send(struct pool *pool, char *s, ssize_t len) { enum send_ret ret = SEND_INACTIVE; if (opt_protocol) applog(LOG_DEBUG, "SEND: %s", s); mutex_lock(&pool->stratum_lock); if (pool->stratum_active) ret = __stratum_send(pool, s, len); mutex_unlock(&pool->stratum_lock); /* This is to avoid doing applog under stratum_lock */ switch (ret) { default: case SEND_OK: break; case SEND_SELECTFAIL: applog(LOG_DEBUG, "Write select failed on %s sock", get_pool_name(pool)); suspend_stratum(pool); break; case SEND_SENDFAIL: applog(LOG_DEBUG, "Failed to send in stratum_send"); suspend_stratum(pool); break; case SEND_INACTIVE: applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active"); break; } return (ret == SEND_OK); } static bool socket_full(struct pool *pool, int wait) { SOCKETTYPE sock = pool->sock; struct timeval timeout; fd_set rd; if (unlikely(wait < 0)) wait = 0; FD_ZERO(&rd); FD_SET(sock, &rd); timeout.tv_usec = 0; timeout.tv_sec = wait; if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0) return true; return false; } /* Check to see if Santa's been good to you */ bool sock_full(struct pool *pool) { if (strlen(pool->sockbuf)) return true; return (socket_full(pool, 0)); } static void clear_sockbuf(struct pool *pool) { strcpy(pool->sockbuf, ""); } static void clear_sock(struct pool *pool) { ssize_t n; mutex_lock(&pool->stratum_lock); do { if (pool->sock) n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0); else n = 0; } while (n > 0); mutex_unlock(&pool->stratum_lock); clear_sockbuf(pool); } /* Make sure the pool sockbuf is large enough to cope with any coinbase size * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE * and zeroing the new memory */ static void recalloc_sock(struct pool *pool, size_t len) { size_t old, newlen; old = strlen(pool->sockbuf); newlen = old + len + 1; if (newlen < pool->sockbuf_size) return; newlen = newlen + (RBUFSIZE - (newlen % RBUFSIZE)); // Avoid potentially recursive locking // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new); pool->sockbuf = (char *)realloc(pool->sockbuf, newlen); if (!pool->sockbuf) quithere(1, "Failed to realloc pool sockbuf"); memset(pool->sockbuf + old, 0, newlen - old); pool->sockbuf_size = newlen; } /* Peeks at a socket to find the first end of line and then reads just that * from the socket and returns that as a malloced char */ char *recv_line(struct pool *pool) { char *tok, *sret = NULL; ssize_t len, buflen; int waited = 0; if (!strstr(pool->sockbuf, "\n")) { struct timeval rstart, now; cgtime(&rstart); if (!socket_full(pool, DEFAULT_SOCKWAIT)) { applog(LOG_DEBUG, "Timed out waiting for data on socket_full"); goto out; } do { char s[RBUFSIZE]; size_t slen; ssize_t n; memset(s, 0, RBUFSIZE); n = recv(pool->sock, s, RECVSIZE, 0); if (!n) { applog(LOG_DEBUG, "Socket closed waiting in recv_line"); suspend_stratum(pool); break; } cgtime(&now); waited = tdiff(&now, &rstart); if (n < 0) { if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) { applog(LOG_DEBUG, "Failed to recv sock in recv_line"); suspend_stratum(pool); break; } } else { slen = strlen(s); recalloc_sock(pool, slen); strcat(pool->sockbuf, s); } } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n")); } buflen = strlen(pool->sockbuf); tok = strtok(pool->sockbuf, "\n"); if (!tok) { applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line"); goto out; } sret = strdup(tok); len = strlen(sret); /* Copy what's left in the buffer after the \n, including the * terminating \0 */ if (buflen > len + 1) memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1); else strcpy(pool->sockbuf, ""); pool->sgminer_pool_stats.times_received++; pool->sgminer_pool_stats.bytes_received += len; pool->sgminer_pool_stats.net_bytes_received += len; out: if (!sret) clear_sock(pool); else if (opt_protocol) applog(LOG_DEBUG, "RECVD: %s", sret); return sret; } /* Extracts a string value from a json array with error checking. To be used * when the value of the string returned is only examined and not to be stored. * See json_array_string below */ static char *__json_array_string(json_t *val, unsigned int entry) { json_t *arr_entry; if (json_is_null(val)) return NULL; if (!json_is_array(val)) return NULL; if (entry > json_array_size(val)) return NULL; arr_entry = json_array_get(val, entry); if (!json_is_string(arr_entry)) return NULL; return (char *)json_string_value(arr_entry); } /* Creates a freshly malloced dup of __json_array_string */ static char *json_array_string(json_t *val, unsigned int entry) { char *buf = __json_array_string(val, entry); if (buf) return strdup(buf); return NULL; } static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000"; static bool parse_notify(struct pool *pool, json_t *val) { char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime, *header; size_t cb1_len, cb2_len, alloc_len; unsigned char *cb1, *cb2; bool clean, ret = false; int merkles, i; json_t *arr; arr = json_array_get(val, 4); if (!arr || !json_is_array(arr)) goto out; merkles = json_array_size(arr); job_id = json_array_string(val, 0); prev_hash = json_array_string(val, 1); coinbase1 = json_array_string(val, 2); coinbase2 = json_array_string(val, 3); bbversion = json_array_string(val, 5); nbit = json_array_string(val, 6); ntime = json_array_string(val, 7); clean = json_is_true(json_array_get(val, 8)); if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) { /* Annoying but we must not leak memory */ if (job_id) free(job_id); if (prev_hash) free(prev_hash); if (coinbase1) free(coinbase1); if (coinbase2) free(coinbase2); if (bbversion) free(bbversion); if (nbit) free(nbit); if (ntime) free(ntime); goto out; } cg_wlock(&pool->data_lock); free(pool->swork.job_id); free(pool->swork.prev_hash); free(pool->swork.bbversion); free(pool->swork.nbit); free(pool->swork.ntime); pool->swork.job_id = job_id; pool->swork.prev_hash = prev_hash; cb1_len = strlen(coinbase1) / 2; cb2_len = strlen(coinbase2) / 2; pool->swork.bbversion = bbversion; pool->swork.nbit = nbit; pool->swork.ntime = ntime; pool->swork.clean = clean; alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len; pool->nonce2_offset = cb1_len + pool->n1_len; for (i = 0; i < pool->swork.merkles; i++) free(pool->swork.merkle_bin[i]); if (merkles) { pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin, sizeof(char *) * merkles + 1); for (i = 0; i < merkles; i++) { char *merkle = json_array_string(arr, i); pool->swork.merkle_bin[i] = (unsigned char *)malloc(32); if (unlikely(!pool->swork.merkle_bin[i])) quit(1, "Failed to malloc pool swork merkle_bin"); hex2bin(pool->swork.merkle_bin[i], merkle, 32); free(merkle); } } pool->swork.merkles = merkles; if (clean) pool->nonce2 = 0; pool->merkle_offset = strlen(pool->swork.bbversion) + strlen(pool->swork.prev_hash); pool->swork.header_len = pool->merkle_offset + /* merkle_hash */ 32 + strlen(pool->swork.ntime) + strlen(pool->swork.nbit) + /* nonce */ 8 + /* workpadding */ 96; pool->merkle_offset /= 2; pool->swork.header_len = pool->swork.header_len * 2 + 1; align_len(&pool->swork.header_len); header = (char *)alloca(pool->swork.header_len); snprintf(header, pool->swork.header_len, "%s%s%s%s%s%s%s", pool->swork.bbversion, pool->swork.prev_hash, blank_merkel, pool->swork.ntime, pool->swork.nbit, "00000000", /* nonce */ workpadding); if (unlikely(!hex2bin(pool->header_bin, header, 128))) quit(1, "Failed to convert header to header_bin in parse_notify"); cb1 = (unsigned char *)calloc(cb1_len, 1); if (unlikely(!cb1)) quithere(1, "Failed to calloc cb1 in parse_notify"); hex2bin(cb1, coinbase1, cb1_len); cb2 = (unsigned char *)calloc(cb2_len, 1); if (unlikely(!cb2)) quithere(1, "Failed to calloc cb2 in parse_notify"); hex2bin(cb2, coinbase2, cb2_len); free(pool->coinbase); align_len(&alloc_len); pool->coinbase = (unsigned char *)calloc(alloc_len, 1); if (unlikely(!pool->coinbase)) quit(1, "Failed to calloc pool coinbase in parse_notify"); memcpy(pool->coinbase, cb1, cb1_len); memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len); memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len); cg_wunlock(&pool->data_lock); if (opt_protocol) { applog(LOG_DEBUG, "job_id: %s", job_id); applog(LOG_DEBUG, "prev_hash: %s", prev_hash); applog(LOG_DEBUG, "coinbase1: %s", coinbase1); applog(LOG_DEBUG, "coinbase2: %s", coinbase2); applog(LOG_DEBUG, "bbversion: %s", bbversion); applog(LOG_DEBUG, "nbit: %s", nbit); applog(LOG_DEBUG, "ntime: %s", ntime); applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no"); } free(coinbase1); free(coinbase2); free(cb1); free(cb2); /* A notify message is the closest stratum gets to a getwork */ pool->getwork_requested++; total_getworks++; ret = true; if (pool == current_pool()) opt_work_update = true; out: return ret; } static bool parse_diff(struct pool *pool, json_t *val) { double old_diff, diff; if (opt_diff_mult == 0.0) diff = json_number_value(json_array_get(val, 0)) * pool->algorithm.diff_multiplier1; else diff = json_number_value(json_array_get(val, 0)) * opt_diff_mult; if (diff == 0) return false; cg_wlock(&pool->data_lock); old_diff = pool->swork.diff; pool->swork.diff = diff; cg_wunlock(&pool->data_lock); if (old_diff != diff) { int idiff = diff; if ((double)idiff == diff) applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %d", get_pool_name(pool), idiff); else applog(pool == current_pool() ? LOG_NOTICE : LOG_DEBUG, "%s difficulty changed to %.3f", get_pool_name(pool), diff); } else applog(LOG_DEBUG, "%s difficulty set to %f", get_pool_name(pool), diff); return true; } static bool parse_extranonce(struct pool *pool, json_t *val) { char *nonce1; int n2size; nonce1 = json_array_string(val, 0); if (!nonce1) { return false; } n2size = json_integer_value(json_array_get(val, 1)); if (!n2size) { free(nonce1); return false; } cg_wlock(&pool->data_lock); pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; free(pool->nonce1bin); pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1); if (unlikely(!pool->nonce1bin)) quithere(1, "Failed to calloc pool->nonce1bin"); hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len); pool->n2size = n2size; cg_wunlock(&pool->data_lock); applog(LOG_NOTICE, "%s extranonce change requested", get_pool_name(pool)); return true; } static void __suspend_stratum(struct pool *pool) { clear_sockbuf(pool); pool->stratum_active = pool->stratum_notify = false; if (pool->sock) CLOSESOCKET(pool->sock); pool->sock = 0; } static bool parse_reconnect(struct pool *pool, json_t *val) { char *sockaddr_url, *stratum_port, *tmp; char *url, *port, address[256]; if (opt_disable_client_reconnect) { applog(LOG_WARNING, "Stratum client.reconnect forbidden, aborting."); return false; } memset(address, 0, 255); url = (char *)json_string_value(json_array_get(val, 0)); if (!url) url = pool->sockaddr_url; port = (char *)json_string_value(json_array_get(val, 1)); if (!port) port = pool->stratum_port; sprintf(address, "%s:%s", url, port); if (!extract_sockaddr(address, &sockaddr_url, &stratum_port)) return false; applog(LOG_NOTICE, "Reconnect requested from %s to %s", get_pool_name(pool), address); clear_pool_work(pool); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); tmp = pool->sockaddr_url; pool->sockaddr_url = sockaddr_url; pool->stratum_url = pool->sockaddr_url; free(tmp); tmp = pool->stratum_port; pool->stratum_port = stratum_port; free(tmp); mutex_unlock(&pool->stratum_lock); if (!restart_stratum(pool)) { pool_failed(pool); return false; } return true; } static bool send_version(struct pool *pool, json_t *val) { char s[RBUFSIZE]; int id = json_integer_value(json_object_get(val, "id")); if (!id) return false; sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id); if (!stratum_send(pool, s, strlen(s))) return false; return true; } static bool show_message(struct pool *pool, json_t *val) { char *msg; if (!json_is_array(val)) return false; msg = (char *)json_string_value(json_array_get(val, 0)); if (!msg) return false; applog(LOG_NOTICE, "%s message: %s", get_pool_name(pool), msg); return true; } bool parse_method(struct pool *pool, char *s) { json_t *val = NULL, *method, *err_val, *params; json_error_t err; bool ret = false; char *buf; if (!s) return ret; val = JSON_LOADS(s, &err); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); return ret; } method = json_object_get(val, "method"); if (!method) { json_decref(val); return ret; } err_val = json_object_get(val, "error"); params = json_object_get(val, "params"); if (err_val && !json_is_null(err_val)) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss); json_decref(val); free(ss); return ret; } buf = (char *)json_string_value(method); if (!buf) { json_decref(val); return ret; } if (!strncasecmp(buf, "mining.notify", 13)) { if (parse_notify(pool, params)) pool->stratum_notify = ret = true; else pool->stratum_notify = ret = false; json_decref(val); return ret; } if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) { ret = true; json_decref(val); return ret; } if (!strncasecmp(buf, "mining.set_extranonce", 21) && parse_extranonce(pool, params)) { ret = true; json_decref(val); return ret; } if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) { ret = true; json_decref(val); return ret; } if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) { ret = true; json_decref(val); return ret; } if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) { ret = true; json_decref(val); return ret; } json_decref(val); return ret; } bool subscribe_extranonce(struct pool *pool) { json_t *val = NULL, *res_val, *err_val; char s[RBUFSIZE], *sret = NULL; json_error_t err; bool ret = false; sprintf(s, "{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}", swork_id++); if (!stratum_send(pool, s, strlen(s))) return ret; /* Parse all data in the queue and anything left should be the response */ while (42) { if (!socket_full(pool, DEFAULT_SOCKWAIT / 30)) { applog(LOG_DEBUG, "Timed out waiting for response extranonce.subscribe"); /* some pool doesnt send anything, so this is normal */ ret = true; goto out; } sret = recv_line(pool); if (!sret) return ret; if (parse_method(pool, sret)) free(sret); else break; } val = JSON_LOADS(sret, &err); free(sret); res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) { ss = __json_array_string(err_val, 1); if (!ss) ss = (char *)json_string_value(err_val); if (ss && (strcmp(ss, "Method 'subscribe' not found for service 'mining.extranonce'") == 0)) { applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool)); ret = true; goto out; } if (ss && (strcmp(ss, "Unrecognized request provided") == 0)) { applog(LOG_INFO, "Cannot subscribe to mining.extranonce on %s", get_pool_name(pool)); ret = true; goto out; } ss = json_dumps(err_val, JSON_INDENT(3)); } else ss = strdup("(unknown reason)"); applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss); free(ss); goto out; } ret = true; applog(LOG_INFO, "Stratum extranonce subscribe for %s", get_pool_name(pool)); out: json_decref(val); return ret; } bool auth_stratum(struct pool *pool) { json_t *val = NULL, *res_val, *err_val; char s[RBUFSIZE], *sret = NULL; json_error_t err; bool ret = false; sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}", swork_id++, pool->rpc_user, pool->rpc_pass); if (!stratum_send(pool, s, strlen(s))) return ret; /* Parse all data in the queue and anything left should be auth */ while (42) { sret = recv_line(pool); if (!sret) return ret; if (parse_method(pool, sret)) free(sret); else break; } val = JSON_LOADS(sret, &err); free(sret); res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "%s JSON stratum auth failed: %s", get_pool_name(pool), ss); free(ss); suspend_stratum(pool); goto out; } ret = true; applog(LOG_INFO, "Stratum authorisation success for %s", get_pool_name(pool)); pool->probed = true; successful_connect = true; out: json_decref(val); return ret; } static int recv_byte(int sockd) { char c; if (recv(sockd, &c, 1, 0) != -1) return c; return -1; } static bool http_negotiate(struct pool *pool, int sockd, bool http0) { char buf[1024]; int i, len; if (http0) { snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n", pool->sockaddr_url, pool->stratum_port); } else { snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n", pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url, pool->stratum_port); } applog(LOG_DEBUG, "Sending proxy %s:%s - %s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf); send(sockd, buf, strlen(buf), 0); len = recv(sockd, buf, 12, 0); if (len <= 0) { applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } buf[len] = '\0'; applog(LOG_DEBUG, "Received from proxy %s:%s - %s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf); if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) { applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf); return false; } /* Ignore unwanted headers till we get desired response */ for (i = 0; i < 4; i++) { buf[i] = recv_byte(sockd); if (buf[i] == (char)-1) { applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } } while (strncmp(buf, "\r\n\r\n", 4)) { for (i = 0; i < 3; i++) buf[i] = buf[i + 1]; buf[3] = recv_byte(sockd); if (buf[3] == (char)-1) { applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } } applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return true; } static bool socks5_negotiate(struct pool *pool, int sockd) { unsigned char atyp, uclen; unsigned short port; char buf[515]; int i, len; buf[0] = 0x05; buf[1] = 0x01; buf[2] = 0x00; applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); send(sockd, buf, 3, 0); if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) { applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); return false; } buf[0] = 0x05; buf[1] = 0x01; buf[2] = 0x00; buf[3] = 0x03; len = (strlen(pool->sockaddr_url)); if (len > 255) len = 255; uclen = len; buf[4] = (uclen & 0xff); memcpy(buf + 5, pool->sockaddr_url, len); port = atoi(pool->stratum_port); buf[5 + len] = (port >> 8); buf[6 + len] = (port & 0xff); send(sockd, buf, (7 + len), 0); if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) { applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); return false; } recv_byte(sockd); atyp = recv_byte(sockd); if (atyp == 0x01) { for (i = 0; i < 4; i++) recv_byte(sockd); } else if (atyp == 0x03) { len = recv_byte(sockd); for (i = 0; i < len; i++) recv_byte(sockd); } else { applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port ); return false; } for (i = 0; i < 2; i++) recv_byte(sockd); applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return true; } static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a) { unsigned short port; in_addr_t inp; char buf[515]; int i, len; int ret; buf[0] = 0x04; buf[1] = 0x01; port = atoi(pool->stratum_port); buf[2] = port >> 8; buf[3] = port & 0xff; sprintf(&buf[8], "SGMINER"); /* See if we've been given an IP address directly to avoid needing to * resolve it. */ inp = inet_addr(pool->sockaddr_url); inp = ntohl(inp); if ((int)inp != -1) socks4a = false; else { /* Try to extract the IP address ourselves first */ struct addrinfo servinfobase, *servinfo, hints; servinfo = &servinfobase; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; /* IPV4 only */ ret = getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo); if (!ret) { applog(LOG_ERR, "getaddrinfo() in socks4_negotiate() returned %i: %s", ret, gai_strerror(ret)); struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr; inp = ntohl(saddr_in->sin_addr.s_addr); socks4a = false; freeaddrinfo(servinfo); } } if (!socks4a) { if ((int)inp == -1) { applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s", pool->sockaddr_url); return false; } buf[4] = (inp >> 24) & 0xFF; buf[5] = (inp >> 16) & 0xFF; buf[6] = (inp >> 8) & 0xFF; buf[7] = (inp >> 0) & 0xFF; send(sockd, buf, 16, 0); } else { /* This appears to not be working but hopefully most will be * able to resolve IP addresses themselves. */ buf[4] = 0; buf[5] = 0; buf[6] = 0; buf[7] = 1; len = strlen(pool->sockaddr_url); if (len > 255) len = 255; memcpy(&buf[16], pool->sockaddr_url, len); len += 16; buf[len++] = '\0'; send(sockd, buf, len, 0); } if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) { applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; } for (i = 0; i < 6; i++) recv_byte(sockd); return true; } static void noblock_socket(SOCKETTYPE fd) { #ifndef WIN32 int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, O_NONBLOCK | flags); #else u_long flags = 1; ioctlsocket(fd, FIONBIO, &flags); #endif } static void block_socket(SOCKETTYPE fd) { #ifndef WIN32 int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); #else u_long flags = 0; ioctlsocket(fd, FIONBIO, &flags); #endif } static bool sock_connecting(void) { #ifndef WIN32 return errno == EINPROGRESS; #else return WSAGetLastError() == WSAEWOULDBLOCK; #endif } static bool setup_stratum_socket(struct pool *pool) { struct addrinfo servinfobase, *servinfo, *hints, *p; char *sockaddr_url, *sockaddr_port; int sockd; int ret; mutex_lock(&pool->stratum_lock); pool->stratum_active = false; if (pool->sock) { /* FIXME: change to LOG_DEBUG if issue #88 resolved */ applog(LOG_INFO, "Closing %s socket", get_pool_name(pool)); CLOSESOCKET(pool->sock); } pool->sock = 0; mutex_unlock(&pool->stratum_lock); hints = &pool->stratum_hints; memset(hints, 0, sizeof(struct addrinfo)); hints->ai_family = AF_UNSPEC; hints->ai_socktype = SOCK_STREAM; servinfo = &servinfobase; if (!pool->rpc_proxy && opt_socks_proxy) { pool->rpc_proxy = opt_socks_proxy; extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port); pool->rpc_proxytype = PROXY_SOCKS5; } if (pool->rpc_proxy) { sockaddr_url = pool->sockaddr_proxy_url; sockaddr_port = pool->sockaddr_proxy_port; } else { sockaddr_url = pool->sockaddr_url; sockaddr_port = pool->stratum_port; } ret = getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo); if (ret) { applog(LOG_INFO, "getaddrinfo() in setup_stratum_socket() returned %i: %s", ret, gai_strerror(ret)); if (!pool->probed) { applog(LOG_WARNING, "Failed to resolve (wrong URL?) %s:%s", sockaddr_url, sockaddr_port); pool->probed = true; } else { applog(LOG_INFO, "Failed to getaddrinfo for %s:%s", sockaddr_url, sockaddr_port); } return false; } for (p = servinfo; p != NULL; p = p->ai_next) { sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sockd == -1) { applog(LOG_DEBUG, "Failed socket"); continue; } /* Iterate non blocking over entries returned by getaddrinfo * to cope with round robin DNS entries, finding the first one * we can connect to quickly. */ noblock_socket(sockd); if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) { struct timeval tv_timeout = {1, 0}; int selret; fd_set rw; if (!sock_connecting()) { CLOSESOCKET(sockd); applog(LOG_DEBUG, "Failed sock connect"); continue; } retry: FD_ZERO(&rw); FD_SET(sockd, &rw); selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout); if (selret > 0 && FD_ISSET(sockd, &rw)) { socklen_t len; int err, n; len = sizeof(err); n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (char *)&err, &len); if (!n && !err) { applog(LOG_DEBUG, "Succeeded delayed connect"); block_socket(sockd); break; } } if (selret < 0 && interrupted()) goto retry; CLOSESOCKET(sockd); applog(LOG_DEBUG, "Select timeout/failed connect"); continue; } applog(LOG_WARNING, "Succeeded immediate connect"); block_socket(sockd); break; } if (p == NULL) { applog(LOG_INFO, "Failed to connect to stratum on %s:%s", sockaddr_url, sockaddr_port); freeaddrinfo(servinfo); return false; } freeaddrinfo(servinfo); if (pool->rpc_proxy) { switch (pool->rpc_proxytype) { case PROXY_HTTP_1_0: if (!http_negotiate(pool, sockd, true)) return false; break; case PROXY_HTTP: if (!http_negotiate(pool, sockd, false)) return false; break; case PROXY_SOCKS5: case PROXY_SOCKS5H: if (!socks5_negotiate(pool, sockd)) return false; break; case PROXY_SOCKS4: if (!socks4_negotiate(pool, sockd, false)) return false; break; case PROXY_SOCKS4A: if (!socks4_negotiate(pool, sockd, true)) return false; break; default: applog(LOG_WARNING, "Unsupported proxy type for %s:%s", pool->sockaddr_proxy_url, pool->sockaddr_proxy_port); return false; break; } } if (!pool->sockbuf) { pool->sockbuf = (char *)calloc(RBUFSIZE, 1); if (!pool->sockbuf) quithere(1, "Failed to calloc pool sockbuf"); pool->sockbuf_size = RBUFSIZE; } pool->sock = sockd; keep_sockalive(sockd); return true; } static char *get_sessionid(json_t *val) { char *ret = NULL; json_t *arr_val; int arrsize, i; arr_val = json_array_get(val, 0); if (!arr_val || !json_is_array(arr_val)) goto out; arrsize = json_array_size(arr_val); for (i = 0; i < arrsize; i++) { json_t *arr = json_array_get(arr_val, i); char *notify; if (!arr | !json_is_array(arr)) break; notify = __json_array_string(arr, 0); if (!notify) continue; if (!strncasecmp(notify, "mining.notify", 13)) { ret = json_array_string(arr, 1); break; } } out: return ret; } void suspend_stratum(struct pool *pool) { applog(LOG_INFO, "Closing socket for stratum %s", get_pool_name(pool)); mutex_lock(&pool->stratum_lock); __suspend_stratum(pool); mutex_unlock(&pool->stratum_lock); } bool initiate_stratum(struct pool *pool) { bool ret = false, recvd = false, noresume = false, sockd = false; char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid; json_t *val = NULL, *res_val, *err_val; json_error_t err; int n2size; resend: if (!setup_stratum_socket(pool)) { /* FIXME: change to LOG_DEBUG when issue #88 resolved */ applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool)); sockd = false; goto out; } sockd = true; if (recvd) { /* Get rid of any crap lying around if we're resending */ clear_sock(pool); sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++); } else { if (pool->sessionid) sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid); else sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++); } if (__stratum_send(pool, s, strlen(s)) != SEND_OK) { applog(LOG_DEBUG, "Failed to send s in initiate_stratum"); goto out; } if (!socket_full(pool, DEFAULT_SOCKWAIT)) { applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum"); goto out; } sret = recv_line(pool); if (!sret) goto out; recvd = true; val = JSON_LOADS(sret, &err); free(sret); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_null(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC decode failed: %s", ss); free(ss); goto out; } sessionid = get_sessionid(res_val); if (!sessionid) applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum"); nonce1 = json_array_string(res_val, 1); if (!nonce1) { applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum"); free(sessionid); goto out; } n2size = json_integer_value(json_array_get(res_val, 2)); if (n2size < 1) { applog(LOG_INFO, "Failed to get n2size in initiate_stratum"); free(sessionid); free(nonce1); goto out; } cg_wlock(&pool->data_lock); pool->sessionid = sessionid; pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; free(pool->nonce1bin); pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1); if (unlikely(!pool->nonce1bin)) quithere(1, "Failed to calloc pool->nonce1bin"); hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len); pool->n2size = n2size; cg_wunlock(&pool->data_lock); if (sessionid) applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid); ret = true; out: if (ret) { if (!pool->stratum_url) pool->stratum_url = pool->sockaddr_url; pool->stratum_active = true; pool->swork.diff = 1; if (opt_protocol) { applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d", get_pool_name(pool), pool->nonce1, pool->n2size); } } else { if (recvd && !noresume) { /* Reset the sessionid used for stratum resuming in case the pool * does not support it, or does not know how to respond to the * presence of the sessionid parameter. */ cg_wlock(&pool->data_lock); free(pool->sessionid); free(pool->nonce1); pool->sessionid = pool->nonce1 = NULL; cg_wunlock(&pool->data_lock); applog(LOG_DEBUG, "Failed to resume stratum, trying afresh"); noresume = true; json_decref(val); goto resend; } applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool)); if (sockd) { applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool)); suspend_stratum(pool); } } json_decref(val); return ret; } bool restart_stratum(struct pool *pool) { applog(LOG_DEBUG, "Restarting stratum on pool %s", get_pool_name(pool)); if (pool->stratum_active) suspend_stratum(pool); if (!initiate_stratum(pool)) return false; if (pool->extranonce_subscribe && !subscribe_extranonce(pool)) return false; if (!auth_stratum(pool)) return false; return true; } void dev_error(struct cgpu_info *dev, enum dev_reason reason) { dev->device_last_not_well = time(NULL); dev->device_not_well_reason = reason; switch (reason) { case REASON_THREAD_FAIL_INIT: dev->thread_fail_init_count++; break; case REASON_THREAD_ZERO_HASH: dev->thread_zero_hash_count++; break; case REASON_THREAD_FAIL_QUEUE: dev->thread_fail_queue_count++; break; case REASON_DEV_SICK_IDLE_60: dev->dev_sick_idle_60_count++; break; case REASON_DEV_DEAD_IDLE_600: dev->dev_dead_idle_600_count++; break; case REASON_DEV_NOSTART: dev->dev_nostart_count++; break; case REASON_DEV_OVER_HEAT: dev->dev_over_heat_count++; break; case REASON_DEV_THERMAL_CUTOFF: dev->dev_thermal_cutoff_count++; break; case REASON_DEV_COMMS_ERROR: dev->dev_comms_error_count++; break; case REASON_DEV_THROTTLE: dev->dev_throttle_count++; break; } } /* Realloc an existing string to fit an extra string s, appending s to it. */ void *realloc_strcat(char *ptr, char *s) { size_t old = strlen(ptr), len = strlen(s); char *ret; if (!len) return ptr; len += old + 1; align_len(&len); ret = (char *)malloc(len); if (unlikely(!ret)) quithere(1, "Failed to malloc"); sprintf(ret, "%s%s", ptr, s); free(ptr); return ret; } void RenameThread(const char* name) { char buf[16]; snprintf(buf, sizeof(buf), "cg@%s", name); #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) prctl(PR_SET_NAME, buf, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__)) pthread_set_name_np(pthread_self(), buf); #elif defined(MAC_OSX) pthread_setname_np(buf); #else // Prevent warnings (void)buf; #endif } /* sgminer specific wrappers for true unnamed semaphore usage on platforms * that support them and for apple which does not. We use a single byte across * a pipe to emulate semaphore behaviour there. */ #ifdef __APPLE__ void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line) { int flags, fd, i; if (pipe(cgsem->pipefd) == -1) quitfrom(1, file, func, line, "Failed pipe errno=%d", errno); /* Make the pipes FD_CLOEXEC to allow them to close should we call * execv on restart. */ for (i = 0; i < 2; i++) { fd = cgsem->pipefd[i]; flags = fcntl(fd, F_GETFD, 0); flags |= FD_CLOEXEC; if (fcntl(fd, F_SETFD, flags) == -1) quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno); } } void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line) { const char buf = 1; int ret; retry: ret = write(cgsem->pipefd[1], &buf, 1); if (unlikely(ret == 0)) applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line); else if (unlikely(ret < 0 && interrupted)) goto retry; } void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line) { char buf; int ret; retry: ret = read(cgsem->pipefd[0], &buf, 1); if (unlikely(ret == 0)) applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line); else if (unlikely(ret < 0 && interrupted)) goto retry; } void cgsem_destroy(cgsem_t *cgsem) { close(cgsem->pipefd[1]); close(cgsem->pipefd[0]); } /* This is similar to sem_timedwait but takes a millisecond value */ int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line) { struct timeval timeout; int ret, fd; fd_set rd; char buf; retry: fd = cgsem->pipefd[0]; FD_ZERO(&rd); FD_SET(fd, &rd); ms_to_timeval(&timeout, ms); ret = select(fd + 1, &rd, NULL, NULL, &timeout); if (ret > 0) { ret = read(fd, &buf, 1); return 0; } if (likely(!ret)) return ETIMEDOUT; if (interrupted()) goto retry; quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem); /* We don't reach here */ return 0; } /* Reset semaphore count back to zero */ void cgsem_reset(cgsem_t *cgsem) { int ret, fd; fd_set rd; char buf; fd = cgsem->pipefd[0]; FD_ZERO(&rd); FD_SET(fd, &rd); do { struct timeval timeout = {0, 0}; ret = select(fd + 1, &rd, NULL, NULL, &timeout); if (ret > 0) ret = read(fd, &buf, 1); else if (unlikely(ret < 0 && interrupted())) ret = 1; } while (ret > 0); } #else void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line) { int ret; if ((ret = sem_init(cgsem, 0, 0))) quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno); } void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line) { if (unlikely(sem_post(cgsem))) quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem); } void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line) { retry: if (unlikely(sem_wait(cgsem))) { if (interrupted()) goto retry; quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem); } } int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line) { struct timespec abs_timeout, ts_now; struct timeval tv_now; int ret; cgtime(&tv_now); timeval_to_spec(&ts_now, &tv_now); ms_to_timespec(&abs_timeout, ms); retry: timeraddspec(&abs_timeout, &ts_now); ret = sem_timedwait(cgsem, &abs_timeout); if (ret) { if (likely(sock_timeout())) return ETIMEDOUT; if (interrupted()) goto retry; quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem); } return 0; } void cgsem_reset(cgsem_t *cgsem) { int ret; do { ret = sem_trywait(cgsem); if (unlikely(ret < 0 && interrupted())) ret = 0; } while (!ret); } void cgsem_destroy(cgsem_t *cgsem) { sem_destroy(cgsem); } #endif /* Provide a completion_timeout helper function for unreliable functions that * may die due to driver issues etc that time out if the function fails and * can then reliably return. */ struct cg_completion { cgsem_t cgsem; void (*fn)(void *fnarg); void *fnarg; }; void *completion_thread(void *arg) { struct cg_completion *cgc = (struct cg_completion *)arg; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); cgc->fn(cgc->fnarg); cgsem_post(&cgc->cgsem); return NULL; } bool cg_completion_timeout(void *fn, void *fnarg, int timeout) { struct cg_completion *cgc; pthread_t pthread; bool ret = false; cgc = (struct cg_completion *)malloc(sizeof(struct cg_completion)); if (unlikely(!cgc)) return ret; cgsem_init(&cgc->cgsem); #ifdef _MSC_VER cgc->fn = (void(__cdecl *)(void *))fn; #else cgc->fn = fn; #endif cgc->fnarg = fnarg; pthread_create(&pthread, NULL, completion_thread, (void *)cgc); ret = cgsem_mswait(&cgc->cgsem, timeout); if (ret) pthread_cancel(pthread); pthread_join(pthread, NULL); free(cgc); return !ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2209_0
crossvul-cpp_data_good_5658_0
/* Copyright (c) 2003, Michael Bretterklieber <michael@bretterklieber.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This code cannot simply be copied and put under the GNU Public License or any other GPL-like (LGPL, GPL2) License. $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_network.h" #include "ext/standard/info.h" #include "php_radius.h" #include "radlib.h" #include "radlib_private.h" #ifndef PHP_WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif void _radius_close(zend_rsrc_list_entry *rsrc TSRMLS_DC); /* If you declare any globals in php_radius.h uncomment this: ZEND_DECLARE_MODULE_GLOBALS(radius) */ /* True global resources - no need for thread safety here */ static int le_radius; /* {{{ radius_functions[] * * Every user visible function must have an entry in radius_functions[]. */ zend_function_entry radius_functions[] = { PHP_FE(radius_auth_open, NULL) PHP_FE(radius_acct_open, NULL) PHP_FE(radius_close, NULL) PHP_FE(radius_strerror, NULL) PHP_FE(radius_config, NULL) PHP_FE(radius_add_server, NULL) PHP_FE(radius_create_request, NULL) PHP_FE(radius_put_string, NULL) PHP_FE(radius_put_int, NULL) PHP_FE(radius_put_attr, NULL) PHP_FE(radius_put_addr, NULL) PHP_FE(radius_put_vendor_string, NULL) PHP_FE(radius_put_vendor_int, NULL) PHP_FE(radius_put_vendor_attr, NULL) PHP_FE(radius_put_vendor_addr, NULL) PHP_FE(radius_send_request, NULL) PHP_FE(radius_get_attr, NULL) PHP_FE(radius_get_vendor_attr, NULL) PHP_FE(radius_cvt_addr, NULL) PHP_FE(radius_cvt_int, NULL) PHP_FE(radius_cvt_string, NULL) PHP_FE(radius_request_authenticator, NULL) PHP_FE(radius_server_secret, NULL) PHP_FE(radius_demangle, NULL) PHP_FE(radius_demangle_mppe_key, NULL) {NULL, NULL, NULL} /* Must be the last line in radius_functions[] */ }; /* }}} */ /* {{{ radius_module_entry */ zend_module_entry radius_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "radius", radius_functions, PHP_MINIT(radius), PHP_MSHUTDOWN(radius), NULL, NULL, PHP_MINFO(radius), #if ZEND_MODULE_API_NO >= 20010901 PHP_RADIUS_VERSION, #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_RADIUS ZEND_GET_MODULE(radius) #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(radius) { le_radius = zend_register_list_destructors_ex(_radius_close, NULL, "rad_handle", module_number); #include "radius_init_const.h" REGISTER_LONG_CONSTANT("RADIUS_MPPE_KEY_LEN", MPPE_KEY_LEN, CONST_PERSISTENT); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(radius) { return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(radius) { php_info_print_table_start(); php_info_print_table_header(2, "radius support", "enabled"); php_info_print_table_row(2, "version", PHP_RADIUS_VERSION); php_info_print_table_end(); } /* }}} */ /* {{{ proto ressource radius_auth_open(string arg) */ PHP_FUNCTION(radius_auth_open) { radius_descriptor *raddesc; raddesc = emalloc(sizeof(radius_descriptor)); raddesc->radh = rad_auth_open(); if (raddesc->radh != NULL) { ZEND_REGISTER_RESOURCE(return_value, raddesc, le_radius); raddesc->id = Z_LVAL_P(return_value); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto ressource radius_acct_open(string arg) */ PHP_FUNCTION(radius_acct_open) { radius_descriptor *raddesc; raddesc = emalloc(sizeof(radius_descriptor)); raddesc->radh = rad_acct_open(); if (raddesc->radh != NULL) { ZEND_REGISTER_RESOURCE(return_value, raddesc, le_radius); raddesc->id = Z_LVAL_P(return_value); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool radius_close(radh) */ PHP_FUNCTION(radius_close) { radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_radh) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); zend_list_delete(raddesc->id); RETURN_TRUE; } /* }}} */ /* {{{ proto string radius_strerror(radh) */ PHP_FUNCTION(radius_strerror) { char *msg; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_radh) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); msg = (char *)rad_strerror(raddesc->radh); RETURN_STRINGL(msg, strlen(msg), 1); } /* }}} */ /* {{{ proto bool radius_config(desc, configfile) */ PHP_FUNCTION(radius_config) { char *filename; int filename_len; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_radh, &filename, &filename_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_config(raddesc->radh, filename) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_add_server(desc, hostname, port, secret, timeout, maxtries) */ PHP_FUNCTION(radius_add_server) { char *hostname, *secret; int hostname_len, secret_len; long port, timeout, maxtries; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rslsll", &z_radh, &hostname, &hostname_len, &port, &secret, &secret_len, &timeout, &maxtries) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_add_server(raddesc->radh, hostname, port, secret, timeout, maxtries) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_create_request(desc, code) */ PHP_FUNCTION(radius_create_request) { long code; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &z_radh, &code) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_create_request(raddesc->radh, code) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_string(desc, type, str) */ PHP_FUNCTION(radius_put_string) { char *str; int str_len; long type; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rls", &z_radh, &type, &str, &str_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_put_string(raddesc->radh, type, str) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_int(desc, type, int) */ PHP_FUNCTION(radius_put_int) { long type, val; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &z_radh, &type, &val) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_put_int(raddesc->radh, type, val) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_attr(desc, type, data) */ PHP_FUNCTION(radius_put_attr) { long type; int len; char *data; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rls", &z_radh, &type, &data, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_put_attr(raddesc->radh, type, data, len) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_addr(desc, type, addr) */ PHP_FUNCTION(radius_put_addr) { int addrlen; long type; char *addr; radius_descriptor *raddesc; zval *z_radh; struct in_addr intern_addr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rls", &z_radh, &type, &addr, &addrlen) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (inet_aton(addr, &intern_addr) == 0) { zend_error(E_ERROR, "Error converting Address"); RETURN_FALSE; } if (rad_put_addr(raddesc->radh, type, intern_addr) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_vendor_string(desc, vendor, type, str) */ PHP_FUNCTION(radius_put_vendor_string) { char *str; int str_len; long type, vendor; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlls", &z_radh, &vendor, &type, &str, &str_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_put_vendor_string(raddesc->radh, vendor, type, str) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_vendor_int(desc, vendor, type, int) */ PHP_FUNCTION(radius_put_vendor_int) { long type, vendor, val; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &z_radh, &vendor, &type, &val) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_put_vendor_int(raddesc->radh, vendor, type, val) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_vendor_attr(desc, vendor, type, data) */ PHP_FUNCTION(radius_put_vendor_attr) { long type, vendor; int len; char *data; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlls", &z_radh, &vendor, &type, &data, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (rad_put_vendor_attr(raddesc->radh, vendor, type, data, len) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_put_vendor_addr(desc, vendor, type, addr) */ PHP_FUNCTION(radius_put_vendor_addr) { long type, vendor; int addrlen; char *addr; radius_descriptor *raddesc; zval *z_radh; struct in_addr intern_addr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlls", &z_radh, &vendor, &type, &addr, &addrlen) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); if (inet_aton(addr, &intern_addr) == 0) { zend_error(E_ERROR, "Error converting Address"); RETURN_FALSE; } if (rad_put_vendor_addr(raddesc->radh, vendor, type, intern_addr) == -1) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool radius_send_request(desc) */ PHP_FUNCTION(radius_send_request) { radius_descriptor *raddesc; zval *z_radh; int res; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_radh) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); res = rad_send_request(raddesc->radh); if (res == -1) { RETURN_FALSE; } else { RETURN_LONG(res); } } /* }}} */ /* {{{ proto string radius_get_attr(desc) */ PHP_FUNCTION(radius_get_attr) { radius_descriptor *raddesc; int res; const void *data; size_t len; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_radh) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); res = rad_get_attr(raddesc->radh, &data, &len); if (res == -1) { RETURN_FALSE; } else { if (res > 0) { array_init(return_value); add_assoc_long(return_value, "attr", res); add_assoc_stringl(return_value, "data", (char *) data, len, 1); return; } RETURN_LONG(res); } } /* }}} */ /* {{{ proto string radius_get_vendor_attr(data) */ PHP_FUNCTION(radius_get_vendor_attr) { const void *data, *raw; int len; u_int32_t vendor; unsigned char type; size_t data_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &raw, &len) == FAILURE) { return; } if (rad_get_vendor_attr(&vendor, &type, &data, &data_len, raw, len) == -1) { RETURN_FALSE; } else { array_init(return_value); add_assoc_long(return_value, "attr", type); add_assoc_long(return_value, "vendor", vendor); add_assoc_stringl(return_value, "data", (char *) data, data_len, 1); return; } } /* }}} */ /* {{{ proto string radius_cvt_addr(data) */ PHP_FUNCTION(radius_cvt_addr) { const void *data; char *addr_dot; int len; struct in_addr addr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &len) == FAILURE) { return; } addr = rad_cvt_addr(data); addr_dot = inet_ntoa(addr); RETURN_STRINGL(addr_dot, strlen(addr_dot), 1); } /* }}} */ /* {{{ proto int radius_cvt_int(data) */ PHP_FUNCTION(radius_cvt_int) { const void *data; int len, val; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &len) == FAILURE) { return; } val = rad_cvt_int(data); RETURN_LONG(val); } /* }}} */ /* {{{ proto string radius_cvt_string(data) */ PHP_FUNCTION(radius_cvt_string) { const void *data; char *val; int len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &len) == FAILURE) { return; } val = rad_cvt_string(data, len); if (val == NULL) RETURN_FALSE; RETVAL_STRINGL(val, strlen(val), 1); free(val); return; } /* }}} */ /* {{{ proto string radius_request_authenticator(radh) */ PHP_FUNCTION(radius_request_authenticator) { radius_descriptor *raddesc; ssize_t res; char buf[LEN_AUTH]; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_radh) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); res = rad_request_authenticator(raddesc->radh, buf, sizeof buf); if (res == -1) { RETURN_FALSE; } else { RETURN_STRINGL(buf, res, 1); } } /* }}} */ /* {{{ proto string radius_server_secret(radh) */ PHP_FUNCTION(radius_server_secret) { char *secret; radius_descriptor *raddesc; zval *z_radh; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_radh) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); secret = (char *)rad_server_secret(raddesc->radh); if (secret) { RETURN_STRINGL(secret, strlen(secret), 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto string radius_demangle(radh, mangled) */ PHP_FUNCTION(radius_demangle) { radius_descriptor *raddesc; zval *z_radh; const void *mangled; unsigned char *buf; int len, res; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_radh, &mangled, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); buf = emalloc(len); res = rad_demangle(raddesc->radh, mangled, len, buf); if (res == -1) { efree(buf); RETURN_FALSE; } else { RETVAL_STRINGL((char *) buf, len, 1); efree(buf); return; } } /* }}} */ /* {{{ proto string radius_demangle_mppe_key(radh, mangled) */ PHP_FUNCTION(radius_demangle_mppe_key) { radius_descriptor *raddesc; zval *z_radh; const void *mangled; unsigned char *buf; size_t dlen; int len, res; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_radh, &mangled, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius); buf = emalloc(len); res = rad_demangle_mppe_key(raddesc->radh, mangled, len, buf, &dlen); if (res == -1) { efree(buf); RETURN_FALSE; } else { RETVAL_STRINGL((char *) buf, dlen, 1); efree(buf); return; } } /* }}} */ /* {{{ _radius_close() */ void _radius_close(zend_rsrc_list_entry *rsrc TSRMLS_DC) { radius_descriptor *raddesc = (radius_descriptor *)rsrc->ptr; rad_close(raddesc->radh); efree(raddesc); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=8 ts=8 fdm=marker * vim<600: noet sw=8 ts=8 */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5658_0
crossvul-cpp_data_good_1543_0
/* Kjetil Matheussen 2006. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // Only necessary with old 2.6 kernel (before jan 2006 or thereabout). // 2.4 and newer 2.6 works fine. #define TIMERCHECKS 0 #include <stdio.h> #include <unistd.h> #include <errno.h> #include <stdarg.h> #include <sys/types.h> #include <pthread.h> #include <pwd.h> #include <sched.h> #include <sys/mman.h> #include <syslog.h> #include <glibtop.h> #include <glibtop/proclist.h> #include <glibtop/procstate.h> #if LIBGTOP_MAJOR_VERSION<2 # include <glibtop/xmalloc.h> #endif #include <glibtop/procuid.h> #include <glibtop/proctime.h> #if LIBGTOP_MAJOR_VERSION<2 typedef u_int64_t ui64; #else typedef guint64 ui64; #endif #define OPTARGS_BEGIN(das_usage) {int lokke;const char *usage=das_usage;for(lokke=1;lokke<argc;lokke++){char *a=argv[lokke];if(!strcmp("--help",a)||!strcmp("-h",a)){printf(usage);return 0; #define OPTARG(name,name2) }}else if(!strcmp(name,a)||!strcmp(name2,a)){{ #define OPTARG_GETINT() atoi(argv[++lokke]) #define OPTARG_GETFLOAT() atof(argv[++lokke]) #define OPTARG_GETSTRING() argv[++lokke] #define OPTARG_LAST() }}else if(lokke==argc-1){lokke--;{ #define OPTARGS_ELSE() }else if(1){ #define OPTARGS_END }else{fprintf(stderr,usage);return(-1);}}} static int increasetime=1; // Seconds between each time the SCHED_OTHER thread is increasing the counter. static int checktime=4; // Seconds between each time the SCHED_FIFO thread checks that the counter is increased. static int waittime=8; // Seconds the SCHED_FIFO thread waits before setting the processes back to SCHED_FIFO. struct das_proclist{ pid_t pid; int policy; //SCHED_OTHER, SCHED_FIFO, SHED_RR int priority; ui64 start_time; // Creation time of the process. }; struct proclistlist{ struct das_proclist *proclist; int length; }; static int verbose=0; int counter=0; // Make non-static in case the c compiler does a whole-program optimization. :-) #if TIMERCHECKS static int checkirq=0; #endif static int xmessage_found=1; static void print_error(FILE *where,char *fmt, ...) { char temp[10000]; va_list ap; va_start(ap, fmt);{ vsnprintf (temp, 9998, fmt, ap); }va_end(ap); syslog(LOG_INFO,temp); if(where!=NULL) fprintf(where,"Das_Watchdog: %s\n",temp); } static ui64 get_pid_start_time(pid_t pid){ glibtop_proc_time buf={0}; glibtop_get_proc_time(&buf,pid); return buf.start_time; } static int get_pid_priority(pid_t pid){ struct sched_param par; sched_getparam(pid,&par); return par.sched_priority; } static int set_pid_priority(pid_t pid,int policy,int priority,char *message,char *name){ struct sched_param par={0}; par.sched_priority=priority; if((sched_setscheduler(pid,policy,&par)!=0)){ print_error(stderr,message,pid,name,strerror(errno)); return 0; } return 1; } struct das_proclist *get_proclist(int *num_procs){ int lokke=0; glibtop_proclist proclist_def={0}; pid_t *proclist=glibtop_get_proclist(&proclist_def,GLIBTOP_KERN_PROC_ALL,0); //|GLIBTOP_EXCLUDE_SYSTEM,0); struct das_proclist *ret=calloc(sizeof(struct das_proclist),proclist_def.number); *num_procs=proclist_def.number; for(lokke=0;lokke<proclist_def.number;lokke++){ pid_t pid=proclist[lokke]; ret[lokke].pid=pid; ret[lokke].policy=sched_getscheduler(pid); ret[lokke].priority=get_pid_priority(pid); ret[lokke].start_time=get_pid_start_time(pid); } #if LIBGTOP_MAJOR_VERSION<2 glibtop_free(proclist); #else g_free(proclist); #endif return ret; } struct proclistlist *pll_create(void){ struct proclistlist *pll=calloc(1,sizeof(struct proclistlist)); pll->proclist=get_proclist(&pll->length); return pll; } static void pll_delete(struct proclistlist *pll){ free(pll->proclist); free(pll); } static pid_t name2pid(char *name){ pid_t pid=-1; int lokke; int num_procs=0; struct das_proclist *proclist=get_proclist(&num_procs); for(lokke=0;lokke<num_procs;lokke++){ glibtop_proc_state state; glibtop_get_proc_state(&state,proclist[lokke].pid); if(!strcmp(state.cmd,name)){ pid=proclist[lokke].pid; break; } } free(proclist); return pid; } static int is_a_member(int val,int *vals,int num_vals){ int lokke; for(lokke=0;lokke<num_vals;lokke++) if(val==vals[lokke]) return 1; return 0; } // Returns a list of users that might be the one owning the proper .Xauthority file. static int *get_userlist(struct proclistlist *pll, int *num_users){ int *ret=calloc(sizeof(int),pll->length); int lokke; *num_users=0; for(lokke=0;lokke<pll->length;lokke++){ glibtop_proc_uid uid; glibtop_get_proc_uid(&uid,pll->proclist[lokke].pid); if( ! is_a_member(uid.uid,ret,*num_users)){ // ??? ret[*num_users]=uid.uid; (*num_users)++; } } return ret; } static int gettimerpid(char *name,int cpu){ pid_t pid; char temp[500]; if(name==NULL) name=&temp[0]; sprintf(name,"softirq-timer/%d",cpu); pid=name2pid(name); if(pid==-1){ sprintf(name,"ksoftirqd/%d",cpu); pid=name2pid(name); } return pid; } #if TIMERCHECKS static int checksoftirq2(int force,int cpu){ char name[500]; pid_t pid=gettimerpid(&name[0],cpu); if(pid==-1) return 0; { int policy=sched_getscheduler(pid); int priority=get_pid_priority(pid); if(priority<sched_get_priority_max(SCHED_FIFO) || policy==SCHED_OTHER ) { if(force){ print_error(stdout,"Forcing %s to SCHED_FIFO priority %d",name,sched_get_priority_max(SCHED_FIFO)); set_pid_priority(pid,SCHED_FIFO,sched_get_priority_max(SCHED_FIFO),"Could not set %d (\"%s\") to SCHED_FIFO (%s).\n\n",name); return checksoftirq2(0,cpu); } if(priority<sched_get_priority_max(SCHED_FIFO)) print_error(stderr, "\n\nWarning. The priority of the \"%s\" process is only %d, and not %d. Unless you are using the High Res Timer,\n" "the watchdog will probably not work. If you are using the High Res Timer, please continue doing so and ignore this message.\n", name, priority, sched_get_priority_max(SCHED_FIFO) ); if(policy==SCHED_OTHER) print_error(stderr, "\n\nWarning The \"%s\" process is running SCHED_OTHER. Unless you are using the High Res Timer,\n" "the watchdog will probably not work, and the timing on your machine is probably horrible.\n", name ); if(checkirq){ print_error(stdout,"\n\nUnless you are using the High Res Timer, you need to add the \"--force\" flag to run das_watchdog reliably.\n"); print_error(stdout,"(Things might change though, so it could work despite all warnings above. To test the watchdog, run the \"test_rt\" program.)\n\n"); } return -1; } //printf("name: -%s-\n",state.cmd); return 1; } } static int checksoftirq(int force){ int cpu=0; for(;;){ switch(checksoftirq2(force,cpu)){ case -1: return -1; case 1: cpu++; break; case 0: default: return 0; } } return 0; } #endif static char *get_pid_environ_val(pid_t pid,char *val){ int temp_size = 500; char *temp = malloc(temp_size); int i=0; int foundit=0; FILE *fp; sprintf(temp,"/proc/%d/environ",pid); fp=fopen(temp,"r"); if(fp==NULL) return NULL; for(;;){ if (i >= temp_size) { temp_size *= 2; temp = realloc(temp, temp_size); } temp[i]=fgetc(fp); if(foundit==1 && (temp[i]==0 || temp[i]=='\0' || temp[i]==EOF)){ char *ret; temp[i]=0; ret=malloc(strlen(temp)+10); sprintf(ret,"%s",temp); fclose(fp); return ret; } switch(temp[i]){ case EOF: fclose(fp); return NULL; case '=': temp[i]=0; if(!strcmp(temp,val)){ foundit=1; } i=0; break; case '\0': i=0; break; default: i++; } } } // Returns 1 in case a message was sent. static int send_xmessage(char *xa_filename,char *message){ if(access(xa_filename,R_OK)==0){ setenv("XAUTHORITY",xa_filename,1); if(verbose) print_error(stdout,"Trying xauth file \"%s\"",xa_filename); if(system(message)==0) return 1; } return 0; } // Returns 1 in case a message was sent. static int send_xmessage_using_XAUTHORITY(struct proclistlist *pll,int lokke,char *message){ if(lokke==pll->length) return 0; { char *xa_filename=get_pid_environ_val(pll->proclist[lokke].pid,"XAUTHORITY"); if(xa_filename!=NULL){ if(send_xmessage(xa_filename,message)==1){ free(xa_filename); return 1; } } free(xa_filename); } return send_xmessage_using_XAUTHORITY(pll,lokke+1,message); } int send_xmessage_using_uids(struct proclistlist *pll, char *message){ int num_users; int lokke; int *uids=get_userlist(pll,&num_users); for(lokke=0;lokke<num_users;lokke++){ char xauthpath[5000]; struct passwd *pass=getpwuid(uids[lokke]); sprintf(xauthpath,"%s/.Xauthority",pass->pw_dir); if(send_xmessage(xauthpath,message)==1){ free(uids); return 1; } } free(uids); return 0; } static void xmessage_fork(struct proclistlist *pll){ char message[5000]; set_pid_priority(0,SCHED_FIFO,sched_get_priority_min(SCHED_FIFO),"Unable to set SCHED_FIFO for %d (\"%s\"). (%s)", "the xmessage fork"); setenv("DISPLAY",":0.0",1); if( ! xmessage_found) sprintf(message,"xmessage \"WARNING! das_watchdog pauses realtime operations for %d seconds.\"",waittime); else sprintf(message,"%s \"WARNING! das_watchdog pauses realtime operations for %d seconds.\"",WHICH_XMESSAGE,waittime); if(send_xmessage_using_uids(pll,message)==0){ set_pid_priority(0,SCHED_OTHER,0,"Unable to set SCHED_OTHER for %d (\"%s\"). (%s)", "the xmessage fork"); // send_xmessage_using_XAUTHRITY is too heavy to run in realtime. send_xmessage_using_XAUTHORITY(pll,0,message); } pll_delete(pll); } // The SCHED_OTHER thread. static void *counter_func(void *arg){ { set_pid_priority(0,SCHED_FIFO,sched_get_priority_min(SCHED_FIFO),"Unable to set SCHED_FIFO for %d (\"%s\"). (%s)", "the counter_func"); } for(;;){ counter++; if(verbose) print_error(stderr,"counter set to %d",counter); sleep(increasetime); } return NULL; } int main(int argc,char **argv){ pid_t mypid=getpid(); pthread_t counter_thread={0}; int num_cpus=0; int *timerpids; #if TIMERCHECKS int force=0; #endif int testing=0; // Get timer pids { // Find number of timer processes. while(gettimerpid(NULL,num_cpus)!=-1) num_cpus++; timerpids=malloc(sizeof(int)*num_cpus); { int cpu=0; for(cpu=0;cpu<num_cpus;cpu++) timerpids[cpu]=gettimerpid(NULL,cpu); } } // Options. OPTARGS_BEGIN("Usage: das_watchdog [--force] [--verbose] [--checkirq] [--increasetime n] [--checktime n] [--waittime n]\n" " [ -f] [ -v] [ -c] [ -it n] [ -ct n] [ -wt n]\n" "\n" "Additional arguments:\n" "[--version] or [-ve] -> Prints out version.\n" "[--test] or [-te] -> Run a test to see if xmessage is working.\n") { OPTARG("--verbose","-v") verbose=1; #if TIMERCHECKS OPTARG("--force","-f") force=1; OPTARG("--checkirq","-c") checkirq=1; return(checksoftirq(0)); #endif OPTARG("--increasetime","-it") increasetime=OPTARG_GETINT(); OPTARG("--checktime","-ct") checktime=OPTARG_GETINT(); OPTARG("--waittime","-wt") waittime=OPTARG_GETINT(); OPTARG("--test","-te") testing=1; verbose=1; OPTARG("--version","-ve") printf("Das Version die Uhr Hund %s nach sein bist.\n",VERSION);exit(0); }OPTARGS_END; // Logging to /var/log/messages { openlog("das_watchdog", 0, LOG_DAEMON); syslog(LOG_INFO, "started"); } // Check various. { #if TIMERCHECKS if(force && checksoftirq(force)<0) return -2; checksoftirq(force); #endif if(getuid()!=0){ print_error(stdout,"Warning, you are not running as root. das_watchdog should be run as an init-script at startup, and not as a normal user.\n"); } if(access(WHICH_XMESSAGE,X_OK)!=0){ print_error(stderr,"Warning, \"xmessage\" is not found or is not an executable. I will try to use the $PATH instead. Hopefully that'll work,"); print_error(stderr,"but you might not receive messages to the screen in case das_watchdog has to take action."); xmessage_found=0; } } // Set priority if(1) { if( ! set_pid_priority(0,SCHED_FIFO,sched_get_priority_max(SCHED_FIFO), "Unable to set SCHED_FIFO realtime priority for %d (\"%s\"). (%s). Exiting.", "Der Gewinde nach die Uhr Hund")) return 0; if(mlockall(MCL_CURRENT|MCL_FUTURE)==-1) print_error(stderr,"Could not call mlockalll(MCL_CURRENT|MCL_FUTURE) (%s)",strerror(errno)); } // Start child thread. { pthread_create(&counter_thread,NULL,counter_func,NULL); } // Main loop. (We are never supposed to exit from this one.) for(;;){ int lastcounter=counter; sleep(checktime); if(verbose) print_error(stderr," counter read to be %d (lastcounter=%d)",counter,lastcounter); if(lastcounter==counter || testing==1){ int changedsched=0; struct proclistlist *pll=pll_create(); int lokke; if(verbose) print_error(stdout,"Die Uhr Hund stossen sein!"); for(lokke=0;lokke<pll->length;lokke++){ if(pll->proclist[lokke].policy!=SCHED_OTHER && pll->proclist[lokke].pid!=mypid && (!is_a_member(pll->proclist[lokke].pid,timerpids,num_cpus)) ) { struct sched_param par={0}; par.sched_priority=0; if(verbose) print_error(stdout,"Setting pid %d temporarily to SCHED_OTHER.",pll->proclist[lokke].pid); if(set_pid_priority(pll->proclist[lokke].pid,SCHED_OTHER,0,"Could not set pid %d (\"%s\") to SCHED_OTHER (%s).\n","no name")) changedsched++; } } if(changedsched>0 || testing==1){ print_error(NULL,"realtime operations paused for %d seconds.",waittime); if(fork()==0){ xmessage_fork(pll); return 0; } sleep(waittime); for(lokke=0;lokke<pll->length;lokke++){ if(pll->proclist[lokke].policy != SCHED_OTHER && pll->proclist[lokke].pid != mypid && (!is_a_member(pll->proclist[lokke].pid,timerpids,num_cpus)) && pll->proclist[lokke].start_time == get_pid_start_time(pll->proclist[lokke].pid) ) { if(get_pid_priority(pll->proclist[lokke].pid) != 0 || sched_getscheduler(pll->proclist[lokke].pid) != SCHED_OTHER){ print_error(stderr, "Seems like someone else has changed priority and/or scheduling policy for %d in the mean time. I'm not going to do anything.", pll->proclist[lokke].pid); }else{ struct sched_param par={0}; par.sched_priority=pll->proclist[lokke].priority; if(verbose) print_error(stdout,"Setting pid %d back to realtime priority.",pll->proclist[lokke].pid); set_pid_priority(pll->proclist[lokke].pid,pll->proclist[lokke].policy,pll->proclist[lokke].priority,"Could not set pid %d (\"%s\") to SCHED_FIFO/SCHED_RR (%s).\n\n", "no name"); } } } } pll_delete(pll); } if(testing==1) break; } return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1543_0
crossvul-cpp_data_bad_341_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_0
crossvul-cpp_data_good_5342_0
/* * Copyright (C) 2015 Vabishchevich Nikolay <vabnick@gmail.com> * * This file is part of libass. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "config.h" #include "ass_compat.h" #include <math.h> #include <stdbool.h> #include "ass_utils.h" #include "ass_bitmap.h" /* * Cascade Blur Algorithm * * The main idea is simple: to approximate gaussian blur with large radius * you can downscale, then apply filter with small pattern, then upscale back. * * To achieve desired precision down/upscaling should be done with sufficiently smooth kernel. * Experiment shows that downscaling of factor 2 with kernel [1, 5, 10, 10, 5, 1] and * corresponding upscaling are enough for 8-bit precision. * * For central filter here is used generic 9-tap filter with one of 3 different patterns * combined with one of optional prefilters with fixed kernels. Kernel coefficients * of the main filter are obtained from solution of least squares problem * for Fourier transform of resulting kernel. */ #define STRIPE_WIDTH (1 << (C_ALIGN_ORDER - 1)) #define STRIPE_MASK (STRIPE_WIDTH - 1) static int16_t zero_line[STRIPE_WIDTH]; static int16_t dither_line[2 * STRIPE_WIDTH] = { #if STRIPE_WIDTH > 8 8, 40, 8, 40, 8, 40, 8, 40, 8, 40, 8, 40, 8, 40, 8, 40, 56, 24, 56, 24, 56, 24, 56, 24, 56, 24, 56, 24, 56, 24, 56, 24, #else 8, 40, 8, 40, 8, 40, 8, 40, 56, 24, 56, 24, 56, 24, 56, 24, #endif }; inline static const int16_t *get_line(const int16_t *ptr, uintptr_t offs, uintptr_t size) { return offs < size ? ptr + offs : zero_line; } inline static void copy_line(int16_t *buf, const int16_t *ptr, uintptr_t offs, uintptr_t size) { ptr = get_line(ptr, offs, size); for (int k = 0; k < STRIPE_WIDTH; ++k) buf[k] = ptr[k]; } /* * Unpack/Pack Functions * * Convert between regular 8-bit bitmap and internal format. * Internal image is stored as set of vertical stripes of size [STRIPE_WIDTH x height]. * Each pixel is represented as 16-bit integer in range of [0-0x4000]. */ void ass_stripe_unpack_c(int16_t *dst, const uint8_t *src, ptrdiff_t src_stride, uintptr_t width, uintptr_t height) { for (uintptr_t y = 0; y < height; ++y) { int16_t *ptr = dst; for (uintptr_t x = 0; x < width; x += STRIPE_WIDTH) { for (int k = 0; k < STRIPE_WIDTH; ++k) ptr[k] = (uint16_t)(((src[x + k] << 7) | (src[x + k] >> 1)) + 1) >> 1; //ptr[k] = (0x4000 * src[x + k] + 127) / 255; ptr += STRIPE_WIDTH * height; } dst += STRIPE_WIDTH; src += src_stride; } } void ass_stripe_pack_c(uint8_t *dst, ptrdiff_t dst_stride, const int16_t *src, uintptr_t width, uintptr_t height) { for (uintptr_t x = 0; x < width; x += STRIPE_WIDTH) { uint8_t *ptr = dst; for (uintptr_t y = 0; y < height; ++y) { const int16_t *dither = dither_line + (y & 1) * STRIPE_WIDTH; for (int k = 0; k < STRIPE_WIDTH; ++k) ptr[k] = (uint16_t)(src[k] - (src[k] >> 8) + dither[k]) >> 6; //ptr[k] = (255 * src[k] + 0x1FFF) / 0x4000; ptr += dst_stride; src += STRIPE_WIDTH; } dst += STRIPE_WIDTH; } uintptr_t left = dst_stride - ((width + STRIPE_MASK) & ~STRIPE_MASK); for (uintptr_t y = 0; y < height; ++y) { for (uintptr_t x = 0; x < left; ++x) dst[x] = 0; dst += dst_stride; } } /* * Contract Filters * * Contract image by factor 2 with kernel [1, 5, 10, 10, 5, 1]. */ static inline int16_t shrink_func(int16_t p1p, int16_t p1n, int16_t z0p, int16_t z0n, int16_t n1p, int16_t n1n) { /* return (1 * p1p + 5 * p1n + 10 * z0p + 10 * z0n + 5 * n1p + 1 * n1n + 16) >> 5; */ int32_t r = (p1p + p1n + n1p + n1n) >> 1; r = (r + z0p + z0n) >> 1; r = (r + p1n + n1p) >> 1; return (r + z0p + z0n + 2) >> 2; } void ass_shrink_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_width = (src_width + 5) >> 1; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; int16_t buf[3 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr + 0 * STRIPE_WIDTH, src, offs + 0 * step, size); copy_line(ptr + 1 * STRIPE_WIDTH, src, offs + 1 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = shrink_func(ptr[2 * k - 4], ptr[2 * k - 3], ptr[2 * k - 2], ptr[2 * k - 1], ptr[2 * k + 0], ptr[2 * k + 1]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } offs += step; } } void ass_shrink_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_height = (src_height + 5) >> 1; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p1p = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *p1n = get_line(src, offs - 3 * STRIPE_WIDTH, step); const int16_t *z0p = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *z0n = get_line(src, offs - 1 * STRIPE_WIDTH, step); const int16_t *n1p = get_line(src, offs - 0 * STRIPE_WIDTH, step); const int16_t *n1n = get_line(src, offs + 1 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = shrink_func(p1p[k], p1n[k], z0p[k], z0n[k], n1p[k], n1n[k]); dst += STRIPE_WIDTH; offs += 2 * STRIPE_WIDTH; } src += step; } } /* * Expand Filters * * Expand image by factor 2 with kernel [5, 10, 1], [1, 10, 5]. */ static inline void expand_func(int16_t *rp, int16_t *rn, int16_t p1, int16_t z0, int16_t n1) { /* *rp = (5 * p1 + 10 * z0 + 1 * n1 + 8) >> 4; *rn = (1 * p1 + 10 * z0 + 5 * n1 + 8) >> 4; */ uint16_t r = (uint16_t)(((uint16_t)(p1 + n1) >> 1) + z0) >> 1; *rp = (uint16_t)(((uint16_t)(r + p1) >> 1) + z0 + 1) >> 1; *rn = (uint16_t)(((uint16_t)(r + n1) >> 1) + z0 + 1) >> 1; } void ass_expand_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_width = 2 * src_width + 4; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; for (uintptr_t x = STRIPE_WIDTH; x < dst_width; x += 2 * STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH / 2; ++k) expand_func(&dst[2 * k], &dst[2 * k + 1], ptr[k - 2], ptr[k - 1], ptr[k]); int16_t *next = dst + step - STRIPE_WIDTH; for (int k = STRIPE_WIDTH / 2; k < STRIPE_WIDTH; ++k) expand_func(&next[2 * k], &next[2 * k + 1], ptr[k - 2], ptr[k - 1], ptr[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } dst += step; } if ((dst_width - 1) & STRIPE_WIDTH) return; for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH / 2; ++k) expand_func(&dst[2 * k], &dst[2 * k + 1], ptr[k - 2], ptr[k - 1], ptr[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } void ass_expand_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_height = 2 * src_height + 4; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; y += 2) { const int16_t *p1 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 1 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) expand_func(&dst[k], &dst[k + STRIPE_WIDTH], p1[k], z0[k], n1[k]); dst += 2 * STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } /* * First Supplementary Filters * * Perform 1D convolution with kernel [1, 2, 1]. */ static inline int16_t pre_blur1_func(int16_t p1, int16_t z0, int16_t n1) { /* return (1 * p1 + 2 * z0 + 1 * n1 + 2) >> 2; */ return (uint16_t)(((uint16_t)(p1 + n1) >> 1) + z0 + 1) >> 1; } void ass_pre_blur1_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_width = src_width + 2; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = pre_blur1_func(ptr[k - 2], ptr[k - 1], ptr[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } } void ass_pre_blur1_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_height = src_height + 2; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p1 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 1 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = pre_blur1_func(p1[k], z0[k], n1[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } /* * Second Supplementary Filters * * Perform 1D convolution with kernel [1, 4, 6, 4, 1]. */ static inline int16_t pre_blur2_func(int16_t p2, int16_t p1, int16_t z0, int16_t n1, int16_t n2) { /* return (1 * p2 + 4 * p1 + 6 * z0 + 4 * n1 + 1 * n2 + 8) >> 4; */ uint16_t r1 = ((uint16_t)(((uint16_t)(p2 + n2) >> 1) + z0) >> 1) + z0; uint16_t r2 = p1 + n1; uint16_t r = ((uint16_t)(r1 + r2) >> 1) | (0x8000 & r1 & r2); return (uint16_t)(r + 1) >> 1; } void ass_pre_blur2_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_width = src_width + 4; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = pre_blur2_func(ptr[k - 4], ptr[k - 3], ptr[k - 2], ptr[k - 1], ptr[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } } void ass_pre_blur2_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_height = src_height + 4; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p2 = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *p1 = get_line(src, offs - 3 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 1 * STRIPE_WIDTH, step); const int16_t *n2 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = pre_blur2_func(p2[k], p1[k], z0[k], n1[k], n2[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } /* * Third Supplementary Filters * * Perform 1D convolution with kernel [1, 6, 15, 20, 15, 6, 1]. */ static inline int16_t pre_blur3_func(int16_t p3, int16_t p2, int16_t p1, int16_t z0, int16_t n1, int16_t n2, int16_t n3) { /* return (1 * p3 + 6 * p2 + 15 * p1 + 20 * z0 + 15 * n1 + 6 * n2 + 1 * n3 + 32) >> 6; */ return (20 * (uint16_t)z0 + 15 * (uint16_t)(p1 + n1) + 6 * (uint16_t)(p2 + n2) + 1 * (uint16_t)(p3 + n3) + 32) >> 6; } void ass_pre_blur3_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_width = src_width + 6; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = pre_blur3_func(ptr[k - 6], ptr[k - 5], ptr[k - 4], ptr[k - 3], ptr[k - 2], ptr[k - 1], ptr[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } } void ass_pre_blur3_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height) { uintptr_t dst_height = src_height + 6; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p3 = get_line(src, offs - 6 * STRIPE_WIDTH, step); const int16_t *p2 = get_line(src, offs - 5 * STRIPE_WIDTH, step); const int16_t *p1 = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 3 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *n2 = get_line(src, offs - 1 * STRIPE_WIDTH, step); const int16_t *n3 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = pre_blur3_func(p3[k], p2[k], p1[k], z0[k], n1[k], n2[k], n3[k]); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } /* * Main 9-tap Parametric Filters * * Perform 1D convolution with kernel * [c3, c2, c1, c0, d, c0, c1, c2, c3] or * [c3, 0, c2, c1, c0, d, c0, c1, c2, 0, c3] or * [c3, 0, c2, 0, c1, c0, d, c0, c1, 0, c2, 0, c3] accordingly. * * cN = param[N], d = 1 - 2 * (c0 + c1 + c2 + c3). */ static inline int16_t blur_func(int16_t p4, int16_t p3, int16_t p2, int16_t p1, int16_t z0, int16_t n1, int16_t n2, int16_t n3, int16_t n4, const int16_t c[]) { p1 -= z0; p2 -= z0; p3 -= z0; p4 -= z0; n1 -= z0; n2 -= z0; n3 -= z0; n4 -= z0; return (((p1 + n1) * c[0] + (p2 + n2) * c[1] + (p3 + n3) * c[2] + (p4 + n4) * c[3] + 0x8000) >> 16) + z0; } void ass_blur1234_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_width = src_width + 8; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(ptr[k - 8], ptr[k - 7], ptr[k - 6], ptr[k - 5], ptr[k - 4], ptr[k - 3], ptr[k - 2], ptr[k - 1], ptr[k - 0], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } } void ass_blur1234_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_height = src_height + 8; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p4 = get_line(src, offs - 8 * STRIPE_WIDTH, step); const int16_t *p3 = get_line(src, offs - 7 * STRIPE_WIDTH, step); const int16_t *p2 = get_line(src, offs - 6 * STRIPE_WIDTH, step); const int16_t *p1 = get_line(src, offs - 5 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 3 * STRIPE_WIDTH, step); const int16_t *n2 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *n3 = get_line(src, offs - 1 * STRIPE_WIDTH, step); const int16_t *n4 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(p4[k], p3[k], p2[k], p1[k], z0[k], n1[k], n2[k], n3[k], n4[k], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } void ass_blur1235_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_width = src_width + 10; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; #if STRIPE_WIDTH < 10 int16_t buf[3 * STRIPE_WIDTH]; int16_t *ptr = buf + 2 * STRIPE_WIDTH; #else int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; #endif for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { #if STRIPE_WIDTH < 10 copy_line(ptr - 2 * STRIPE_WIDTH, src, offs - 2 * step, size); #endif copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(ptr[k - 10], ptr[k - 8], ptr[k - 7], ptr[k - 6], ptr[k - 5], ptr[k - 4], ptr[k - 3], ptr[k - 2], ptr[k - 0], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } } void ass_blur1235_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_height = src_height + 10; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p4 = get_line(src, offs - 10 * STRIPE_WIDTH, step); const int16_t *p3 = get_line(src, offs - 8 * STRIPE_WIDTH, step); const int16_t *p2 = get_line(src, offs - 7 * STRIPE_WIDTH, step); const int16_t *p1 = get_line(src, offs - 6 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 5 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *n2 = get_line(src, offs - 3 * STRIPE_WIDTH, step); const int16_t *n3 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *n4 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(p4[k], p3[k], p2[k], p1[k], z0[k], n1[k], n2[k], n3[k], n4[k], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } void ass_blur1246_horz_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_width = src_width + 12; uintptr_t size = ((src_width + STRIPE_MASK) & ~STRIPE_MASK) * src_height; uintptr_t step = STRIPE_WIDTH * src_height; uintptr_t offs = 0; #if STRIPE_WIDTH < 12 int16_t buf[3 * STRIPE_WIDTH]; int16_t *ptr = buf + 2 * STRIPE_WIDTH; #else int16_t buf[2 * STRIPE_WIDTH]; int16_t *ptr = buf + STRIPE_WIDTH; #endif for (uintptr_t x = 0; x < dst_width; x += STRIPE_WIDTH) { for (uintptr_t y = 0; y < src_height; ++y) { #if STRIPE_WIDTH < 12 copy_line(ptr - 2 * STRIPE_WIDTH, src, offs - 2 * step, size); #endif copy_line(ptr - 1 * STRIPE_WIDTH, src, offs - 1 * step, size); copy_line(ptr - 0 * STRIPE_WIDTH, src, offs - 0 * step, size); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(ptr[k - 12], ptr[k - 10], ptr[k - 8], ptr[k - 7], ptr[k - 6], ptr[k - 5], ptr[k - 4], ptr[k - 2], ptr[k - 0], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } } } void ass_blur1246_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_height = src_height + 12; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p4 = get_line(src, offs - 12 * STRIPE_WIDTH, step); const int16_t *p3 = get_line(src, offs - 10 * STRIPE_WIDTH, step); const int16_t *p2 = get_line(src, offs - 8 * STRIPE_WIDTH, step); const int16_t *p1 = get_line(src, offs - 7 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 6 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 5 * STRIPE_WIDTH, step); const int16_t *n2 = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *n3 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *n4 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(p4[k], p3[k], p2[k], p1[k], z0[k], n1[k], n2[k], n3[k], n4[k], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } static void calc_gauss(double *res, int n, double r2) { double alpha = 0.5 / r2; double mul = exp(-alpha), mul2 = mul * mul; double cur = sqrt(alpha / M_PI); res[0] = cur; cur *= mul; res[1] = cur; for (int i = 2; i <= n; ++i) { mul *= mul2; cur *= mul; res[i] = cur; } } static void coeff_blur121(double *coeff, int n) { double prev = coeff[1]; for (int i = 0; i <= n; ++i) { double res = (prev + 2 * coeff[i] + coeff[i + 1]) / 4; prev = coeff[i]; coeff[i] = res; } } static void coeff_filter(double *coeff, int n, const double kernel[4]) { double prev1 = coeff[1], prev2 = coeff[2], prev3 = coeff[3]; for (int i = 0; i <= n; ++i) { double res = coeff[i + 0] * kernel[0] + (prev1 + coeff[i + 1]) * kernel[1] + (prev2 + coeff[i + 2]) * kernel[2] + (prev3 + coeff[i + 3]) * kernel[3]; prev3 = prev2; prev2 = prev1; prev1 = coeff[i]; coeff[i] = res; } } static void calc_matrix(double mat[4][4], const double *mat_freq, const int *index) { for (int i = 0; i < 4; ++i) { mat[i][i] = mat_freq[2 * index[i]] + 3 * mat_freq[0] - 4 * mat_freq[index[i]]; for (int j = i + 1; j < 4; ++j) mat[i][j] = mat[j][i] = mat_freq[index[i] + index[j]] + mat_freq[index[j] - index[i]] + 2 * (mat_freq[0] - mat_freq[index[i]] - mat_freq[index[j]]); } // invert transpose for (int k = 0; k < 4; ++k) { int ip = k, jp = k; // pivot double z = 1 / mat[ip][jp]; mat[ip][jp] = 1; for (int i = 0; i < 4; ++i) { if (i == ip) continue; double mul = mat[i][jp] * z; mat[i][jp] = 0; for (int j = 0; j < 4; ++j) mat[i][j] -= mat[ip][j] * mul; } for (int j = 0; j < 4; ++j) mat[ip][j] *= z; } } /** * \brief Solve least squares problem for kernel of the main filter * \param mu out: output coefficients * \param index in: filter tap positions * \param prefilter in: supplementary filter type * \param r2 in: desired standard deviation squared * \param mul in: scale multiplier */ static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[14]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } } typedef struct { int level, prefilter, filter; int16_t coeff[4]; } BlurMethod; static void find_best_method(BlurMethod *blur, double r2) { static const int index[][4] = { { 1, 2, 3, 4 }, { 1, 2, 3, 5 }, { 1, 2, 4, 6 }, }; double mu[5]; if (r2 < 1.9) { blur->level = blur->prefilter = blur->filter = 0; if (r2 < 0.5) { mu[2] = 0.085 * r2 * r2 * r2; mu[1] = 0.5 * r2 - 4 * mu[2]; mu[3] = mu[4] = 0; } else { calc_gauss(mu, 4, r2); } } else { double mul = 1; if (r2 < 6.693) { blur->level = 0; if (r2 < 2.8) blur->prefilter = 1; else if (r2 < 4.4) blur->prefilter = 2; else blur->prefilter = 3; blur->filter = blur->prefilter - 1; } else { frexp((r2 + 0.7) / 26.5, &blur->level); blur->level = (blur->level + 3) >> 1; mul = pow(0.25, blur->level); r2 *= mul; if (r2 < 3.15 - 1.5 * mul) blur->prefilter = 0; else if (r2 < 5.3 - 5.2 * mul) blur->prefilter = 1; else blur->prefilter = 2; blur->filter = blur->prefilter; } calc_coeff(mu + 1, index[blur->filter], blur->prefilter, r2, mul); } for (int i = 1; i <= 4; ++i) blur->coeff[i - 1] = (int)(0x10000 * mu[i] + 0.5); } /** * \brief Perform approximate gaussian blur * \param r2 in: desired standard deviation squared */ bool ass_gaussian_blur(const BitmapEngine *engine, Bitmap *bm, double r2) { BlurMethod blur; find_best_method(&blur, r2); int w = bm->w, h = bm->h; int offset = ((2 * (blur.prefilter + blur.filter) + 17) << blur.level) - 5; int end_w = ((w + offset) & ~((1 << blur.level) - 1)) - 4; int end_h = ((h + offset) & ~((1 << blur.level) - 1)) - 4; const int stripe_width = 1 << (engine->align_order - 1); int size = end_h * ((end_w + stripe_width - 1) & ~(stripe_width - 1)); int16_t *tmp = ass_aligned_alloc(2 * stripe_width, 4 * size, false); if (!tmp) return false; engine->stripe_unpack(tmp, bm->buffer, bm->stride, w, h); int16_t *buf[2] = {tmp, tmp + size}; int index = 0; for (int i = 0; i < blur.level; ++i) { engine->shrink_vert(buf[index ^ 1], buf[index], w, h); h = (h + 5) >> 1; index ^= 1; } for (int i = 0; i < blur.level; ++i) { engine->shrink_horz(buf[index ^ 1], buf[index], w, h); w = (w + 5) >> 1; index ^= 1; } if (blur.prefilter) { engine->pre_blur_horz[blur.prefilter - 1](buf[index ^ 1], buf[index], w, h); w += 2 * blur.prefilter; index ^= 1; } engine->main_blur_horz[blur.filter](buf[index ^ 1], buf[index], w, h, blur.coeff); w += 2 * blur.filter + 8; index ^= 1; for (int i = 0; i < blur.level; ++i) { engine->expand_horz(buf[index ^ 1], buf[index], w, h); w = 2 * w + 4; index ^= 1; } if (blur.prefilter) { engine->pre_blur_vert[blur.prefilter - 1](buf[index ^ 1], buf[index], w, h); h += 2 * blur.prefilter; index ^= 1; } engine->main_blur_vert[blur.filter](buf[index ^ 1], buf[index], w, h, blur.coeff); h += 2 * blur.filter + 8; index ^= 1; for (int i = 0; i < blur.level; ++i) { engine->expand_vert(buf[index ^ 1], buf[index], w, h); h = 2 * h + 4; index ^= 1; } assert(w == end_w && h == end_h); if (!realloc_bitmap(engine, bm, w, h)) { ass_aligned_free(tmp); return false; } offset = ((blur.prefilter + blur.filter + 8) << blur.level) - 4; bm->left -= offset; bm->top -= offset; engine->stripe_pack(bm->buffer, bm->stride, buf[index], w, h); ass_aligned_free(tmp); return true; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5342_0
crossvul-cpp_data_bad_525_2
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / FFMPEG module * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "ffmpeg_in.h" #ifndef DISABLE_FFMPEG_DEMUX /*default buffer is 200 ms per channel*/ #define FFD_DATA_BUFFER 800 //#define FFMPEG_DEMUX_ENABLE_MPEG2TS //#if defined(__DARWIN__) || defined(__APPLE__) #if !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__SYMBIAN32__) #include <errno.h> #endif /** * New versions of ffmpeg do not declare AVERROR_NOMEM, AVERROR_IO, AVERROR_NOFMT */ #ifndef AVERROR_NOMEM #define AVERROR_NOMEM AVERROR(ENOMEM) #endif /* AVERROR_NOMEM */ #ifndef AVERROR_IO #define AVERROR_IO AVERROR(EIO) #endif /* AVERROR_IO */ #ifndef AVERROR_NOFMT #define AVERROR_NOFMT AVERROR(EINVAL) #endif /* AVERROR_NOFMT */ #if ((LIBAVFORMAT_VERSION_MAJOR == 54) && (LIBAVFORMAT_VERSION_MINOR >= 20)) || (LIBAVFORMAT_VERSION_MAJOR > 54) #define av_find_stream_info(__c) avformat_find_stream_info(__c, NULL) #define USE_AVFORMAT_OPEN_INPUT 1 #endif #if defined(GPAC_ANDROID) && (LIBAVFORMAT_VERSION_MAJOR <= 52) #ifndef FF_API_CLOSE_INPUT_FILE #define FF_API_CLOSE_INPUT_FILE 1 #endif #endif static u32 FFDemux_Run(void *par) { AVPacket pkt; s64 seek_to; GF_NetworkCommand com; GF_NetworkCommand map; GF_SLHeader slh; FFDemux *ffd = (FFDemux *) par; memset(&map, 0, sizeof(GF_NetworkCommand)); map.command_type = GF_NET_CHAN_MAP_TIME; memset(&com, 0, sizeof(GF_NetworkCommand)); com.command_type = GF_NET_BUFFER_QUERY; memset(&slh, 0, sizeof(GF_SLHeader)); slh.compositionTimeStampFlag = slh.decodingTimeStampFlag = 1; while (ffd->is_running) { //nothing connected, wait if (!ffd->video_ch && !ffd->audio_ch) { gf_sleep(100); continue; } if ((ffd->seek_time>=0) && ffd->seekable) { seek_to = (s64) (AV_TIME_BASE*ffd->seek_time); av_seek_frame(ffd->ctx, -1, seek_to, AVSEEK_FLAG_BACKWARD); ffd->seek_time = -1; } pkt.stream_index = -1; /*EOF*/ if (av_read_frame(ffd->ctx, &pkt) <0) break; if (pkt.pts == AV_NOPTS_VALUE) pkt.pts = pkt.dts; if (!pkt.dts) pkt.dts = pkt.pts; slh.compositionTimeStamp = pkt.pts; slh.decodingTimeStamp = pkt.dts; gf_mx_p(ffd->mx); /*blindly send audio as soon as video is init*/ if (ffd->audio_ch && (pkt.stream_index == ffd->audio_st) ) { slh.compositionTimeStamp *= ffd->audio_tscale.num; slh.decodingTimeStamp *= ffd->audio_tscale.num; gf_service_send_packet(ffd->service, ffd->audio_ch, (char *) pkt.data, pkt.size, &slh, GF_OK); } else if (ffd->video_ch && (pkt.stream_index == ffd->video_st)) { slh.compositionTimeStamp *= ffd->video_tscale.num; slh.decodingTimeStamp *= ffd->video_tscale.num; slh.randomAccessPointFlag = pkt.flags&AV_PKT_FLAG_KEY ? 1 : 0; gf_service_send_packet(ffd->service, ffd->video_ch, (char *) pkt.data, pkt.size, &slh, GF_OK); } gf_mx_v(ffd->mx); av_free_packet(&pkt); /*sleep untill the buffer occupancy is too low - note that this work because all streams in this demuxer are synchronized*/ while (ffd->audio_run || ffd->video_run) { gf_service_command(ffd->service, &com, GF_OK); if (com.buffer.occupancy < com.buffer.max) break; gf_sleep(1); } if (!ffd->audio_run && !ffd->video_run) break; } /*signal EOS*/ if (ffd->audio_ch) gf_service_send_packet(ffd->service, ffd->audio_ch, NULL, 0, NULL, GF_EOS); if (ffd->video_ch) gf_service_send_packet(ffd->service, ffd->video_ch, NULL, 0, NULL, GF_EOS); ffd->is_running = 2; return 0; } static const char * FFD_MIME_TYPES[] = { "video/x-mpeg", "mpg mpeg mp2 mpa mpe mpv2", "MPEG 1/2 Movies", "video/x-mpeg-systems", "mpg mpeg mp2 mpa mpe mpv2", "MPEG 1/2 Movies", "audio/basic", "snd au", "Basic Audio", "audio/x-wav", "wav", "WAV Audio", "audio/vnd.wave", "wav", "WAV Audio", "video/x-ms-asf", "asf wma wmv asx asr", "WindowsMedia Movies", "video/x-ms-wmv", "asf wma wmv asx asr", "WindowsMedia Movies", "video/x-msvideo", "avi", "AVI Movies", "video/x-ms-video", "avi", "AVI Movies", "video/avi", "avi", "AVI Movies", "video/vnd.avi", "avi", "AVI Movies", "video/H263", "h263 263", "H263 Video", "video/H264", "h264 264", "H264 Video", "video/MPEG4", "cmp", "MPEG-4 Video", /* We let ffmpeg handle mov because some QT files with uncompressed or adpcm audio use 1 audio sample per MP4 sample which is a killer for our MP4 lib, whereas ffmpeg handles these as complete audio chunks moreover ffmpeg handles cmov, we don't */ "video/quicktime", "mov qt", "QuickTime Movies", /* Supported by latest versions of FFMPEG */ "video/webm", "webm", "Google WebM Movies", "audio/webm", "webm", "Google WebM Music", #ifdef FFMPEG_DEMUX_ENABLE_MPEG2TS "video/mp2t", "ts", "MPEG 2 TS", #endif NULL }; static u32 FFD_RegisterMimeTypes(const GF_InputService *plug) { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) gf_service_register_mime(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2]); return i/3; } static int open_file(AVFormatContext ** ic_ptr, const char * filename, AVInputFormat * fmt, void *ops) { #ifdef USE_PRE_0_7 return av_open_input_file(ic_ptr, filename, fmt, 0, NULL); #else return avformat_open_input(ic_ptr, filename, fmt, (AVDictionary**)ops); #endif } void ffd_parse_options(FFDemux *ffd, const char *url) { #ifdef USE_AVFORMAT_OPEN_INPUT int res; char *frag = (char*) strchr(url, '#'); if (frag) frag = frag+1; if (ffd->options) return; while (frag) { char *mid, *sep = strchr(frag, ':'); if (sep) sep[0] = 0; mid = strchr(frag, '='); if (mid) { mid[0] = 0; res = av_dict_set(&ffd->options, frag, mid+1, 0); if (res<0) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] Failed to set option %s:%s\n", frag, mid+1) ); } mid[0] = '='; } if (!sep) break; sep[0] = ':'; frag = sep+1; } #endif } static Bool FFD_CanHandleURL(GF_InputService *plug, const char *url) { Bool has_audio, has_video; s32 i; AVFormatContext *ctx; AVOutputFormat *fmt_out; Bool ret = GF_FALSE; char *ext, szName[1000], szExt[20]; const char *szExtList; FFDemux *ffd; if (!plug || !url) return GF_FALSE; /*disable RTP/RTSP from ffmpeg*/ if (!strnicmp(url, "rtsp://", 7)) return GF_FALSE; if (!strnicmp(url, "rtspu://", 8)) return GF_FALSE; if (!strnicmp(url, "rtp://", 6)) return GF_FALSE; if (!strnicmp(url, "plato://", 8)) return GF_FALSE; if (!strnicmp(url, "udp://", 6)) return GF_FALSE; if (!strnicmp(url, "tcp://", 6)) return GF_FALSE; if (!strnicmp(url, "data:", 5)) return GF_FALSE; ffd = (FFDemux*)plug->priv; strcpy(szName, url); ext = strrchr(szName, '#'); if (ext) ext[0] = 0; ext = strrchr(szName, '?'); if (ext) ext[0] = 0; ext = strrchr(szName, '.'); if (ext && strlen(ext) > 19) ext = NULL; if (ext && strlen(ext) > 1) { strcpy(szExt, &ext[1]); strlwr(szExt); #ifndef FFMPEG_DEMUX_ENABLE_MPEG2TS if (strstr("ts m2t mts dmb trp", szExt) ) return GF_FALSE; #endif /*note we forbid ffmpeg to handle files we support*/ if (!strcmp(szExt, "mp4") || !strcmp(szExt, "mpg4") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m21") || !strcmp(szExt, "m4v") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m4s") || !strcmp(szExt, "3gs") || !strcmp(szExt, "3gp") || !strcmp(szExt, "3gpp") || !strcmp(szExt, "3gp2") || !strcmp(szExt, "3g2") || !strcmp(szExt, "mp3") || !strcmp(szExt, "ac3") || !strcmp(szExt, "amr") || !strcmp(szExt, "bt") || !strcmp(szExt, "wrl") || !strcmp(szExt, "x3dv") || !strcmp(szExt, "xmt") || !strcmp(szExt, "xmta") || !strcmp(szExt, "x3d") || !strcmp(szExt, "jpg") || !strcmp(szExt, "jpeg") || !strcmp(szExt, "png") ) return GF_FALSE; /*check any default stuff that should work with ffmpeg*/ { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) { if (gf_service_check_mime_register(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2], ext)) return GF_TRUE; } } } ffd_parse_options(ffd, url); ctx = NULL; if (open_file(&ctx, szName, NULL, ffd->options ? &ffd->options : NULL)<0) { AVInputFormat *av_in = NULL; /*some extensions not supported by ffmpeg*/ if (ext && !strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v"); if (open_file(&ctx, szName, av_in, ffd->options ? &ffd->options : NULL)<0) { return GF_FALSE; } } if (!ctx) goto exit; if (av_find_stream_info(ctx) <0) goto exit; /*figure out if we can use codecs or not*/ has_video = has_audio = GF_FALSE; for(i = 0; i < (s32)ctx->nb_streams; i++) { AVCodecContext *enc = ctx->streams[i]->codec; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: if (!has_audio) has_audio = GF_TRUE; break; case AVMEDIA_TYPE_VIDEO: if (!has_video) has_video= GF_TRUE; break; default: break; } } if (!has_audio && !has_video) goto exit; ret = GF_TRUE; #if ((LIBAVFORMAT_VERSION_MAJOR == 52) && (LIBAVFORMAT_VERSION_MINOR <= 47)) || (LIBAVFORMAT_VERSION_MAJOR < 52) fmt_out = guess_stream_format(NULL, url, NULL); #else fmt_out = av_guess_format(NULL, url, NULL); #endif if (fmt_out) gf_service_register_mime(plug, fmt_out->mime_type, fmt_out->extensions, fmt_out->name); else { ext = strrchr(szName, '.'); if (ext) { strcpy(szExt, &ext[1]); strlwr(szExt); szExtList = gf_modules_get_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg"); if (!szExtList) { gf_service_register_mime(plug, "application/x-ffmpeg", szExt, "Other Movies (FFMPEG)"); } else if (!strstr(szExtList, szExt)) { u32 len; char *buf; len = (u32) (strlen(szExtList) + strlen(szExt) + 10); buf = (char*)gf_malloc(sizeof(char)*len); sprintf(buf, "\"%s ", szExt); strcat(buf, &szExtList[1]); gf_modules_set_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg", buf); gf_free(buf); } } } exit: #if FF_API_CLOSE_INPUT_FILE if (ctx) av_close_input_file(ctx); #else if (ctx) avformat_close_input(&ctx); #endif return ret; } static GF_ESD *FFD_GetESDescriptor(FFDemux *ffd, Bool for_audio) { GF_BitStream *bs; Bool dont_use_sl; GF_ESD *esd = (GF_ESD *) gf_odf_desc_esd_new(0); esd->ESID = 1 + (for_audio ? ffd->audio_st : ffd->video_st); esd->decoderConfig->streamType = for_audio ? GF_STREAM_AUDIO : GF_STREAM_VISUAL; esd->decoderConfig->avgBitrate = esd->decoderConfig->maxBitrate = 0; /*remap std object types - depending on input formats, FFMPEG may not have separate DSI from initial frame. In this case we have no choice but using FFMPEG decoders*/ if (for_audio) { AVCodecContext *dec = ffd->ctx->streams[ffd->audio_st]->codec; esd->slConfig->timestampResolution = ffd->audio_tscale.den; switch (dec->codec_id) { case CODEC_ID_MP2: esd->decoderConfig->objectTypeIndication = GPAC_OTI_AUDIO_MPEG1; break; case CODEC_ID_MP3: esd->decoderConfig->objectTypeIndication = GPAC_OTI_AUDIO_MPEG2_PART3; break; case CODEC_ID_AAC: if (!dec->extradata_size) goto opaque_audio; esd->decoderConfig->objectTypeIndication = GPAC_OTI_AUDIO_AAC_MPEG4; esd->decoderConfig->decoderSpecificInfo->dataLength = dec->extradata_size; esd->decoderConfig->decoderSpecificInfo->data = (char*)gf_malloc(sizeof(char)*dec->extradata_size); memcpy(esd->decoderConfig->decoderSpecificInfo->data, dec->extradata, sizeof(char)*dec->extradata_size); break; default: opaque_audio: esd->decoderConfig->objectTypeIndication = GPAC_OTI_MEDIA_FFMPEG; bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); gf_bs_write_u32(bs, dec->codec_id); gf_bs_write_u32(bs, dec->sample_rate); gf_bs_write_u16(bs, dec->channels); gf_bs_write_u16(bs, dec->frame_size); gf_bs_write_u8(bs, 16); gf_bs_write_u8(bs, 0); /*ffmpeg specific*/ gf_bs_write_u16(bs, dec->block_align); gf_bs_write_u32(bs, dec->bit_rate); gf_bs_write_u32(bs, dec->codec_tag); if (dec->extradata_size) { gf_bs_write_data(bs, (char *) dec->extradata, dec->extradata_size); } gf_bs_get_content(bs, (char **) &esd->decoderConfig->decoderSpecificInfo->data, &esd->decoderConfig->decoderSpecificInfo->dataLength); gf_bs_del(bs); break; } dont_use_sl = ffd->unreliable_audio_timing; } else { AVCodecContext *dec = ffd->ctx->streams[ffd->video_st]->codec; esd->slConfig->timestampResolution = ffd->video_tscale.den; switch (dec->codec_id) { case CODEC_ID_MPEG4: /*there is a bug in fragmentation of raw H264 in ffmpeg, the NALU startcode (0x00000001) is split across two frames - we therefore force internal ffmpeg codec ID to avoid NALU size recompute at the decoder level*/ // case CODEC_ID_H264: /*if dsi not detected force use ffmpeg*/ if (!dec->extradata_size) goto opaque_video; /*otherwise use any MPEG-4 Visual*/ esd->decoderConfig->objectTypeIndication = (dec->codec_id==CODEC_ID_H264) ? GPAC_OTI_VIDEO_AVC : GPAC_OTI_VIDEO_MPEG4_PART2; esd->decoderConfig->decoderSpecificInfo->dataLength = dec->extradata_size; esd->decoderConfig->decoderSpecificInfo->data = (char*)gf_malloc(sizeof(char)*dec->extradata_size); memcpy(esd->decoderConfig->decoderSpecificInfo->data, dec->extradata, sizeof(char)*dec->extradata_size); break; case CODEC_ID_MPEG1VIDEO: esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MPEG1; break; case CODEC_ID_MPEG2VIDEO: esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MPEG2_MAIN; break; case CODEC_ID_H263: esd->decoderConfig->objectTypeIndication = GPAC_OTI_MEDIA_GENERIC; bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); gf_bs_write_u32(bs, GF_4CC('s', '2', '6', '3') ); gf_bs_write_u16(bs, dec->width); gf_bs_write_u16(bs, dec->height); gf_bs_get_content(bs, (char **) &esd->decoderConfig->decoderSpecificInfo->data, &esd->decoderConfig->decoderSpecificInfo->dataLength); gf_bs_del(bs); break; default: opaque_video: esd->decoderConfig->objectTypeIndication = GPAC_OTI_MEDIA_FFMPEG; bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); gf_bs_write_u32(bs, dec->codec_id); gf_bs_write_u16(bs, dec->width); gf_bs_write_u16(bs, dec->height); /*ffmpeg specific*/ gf_bs_write_u32(bs, dec->bit_rate); gf_bs_write_u32(bs, dec->codec_tag); gf_bs_write_u32(bs, dec->pix_fmt); if (dec->extradata_size) { gf_bs_write_data(bs, (char *) dec->extradata, dec->extradata_size); } gf_bs_get_content(bs, (char **) &esd->decoderConfig->decoderSpecificInfo->data, &esd->decoderConfig->decoderSpecificInfo->dataLength); gf_bs_del(bs); break; } dont_use_sl = GF_FALSE; } if (dont_use_sl) { esd->slConfig->predefined = SLPredef_SkipSL; } else { /*only send full AUs*/ esd->slConfig->useAccessUnitStartFlag = esd->slConfig->useAccessUnitEndFlag = 0; if (for_audio) { esd->slConfig->hasRandomAccessUnitsOnlyFlag = 1; } else { esd->slConfig->useRandomAccessPointFlag = 1; } esd->slConfig->useTimestampsFlag = 1; } return esd; } static void FFD_SetupObjects(FFDemux *ffd) { GF_ESD *esd; GF_ObjectDescriptor *od; u32 audio_esid = 0; if ((ffd->audio_st>=0) && (ffd->service_type != 1)) { od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG); esd = FFD_GetESDescriptor(ffd, GF_TRUE); od->objectDescriptorID = esd->ESID; audio_esid = esd->ESID; gf_list_add(od->ESDescriptors, esd); gf_service_declare_media(ffd->service, (GF_Descriptor*)od, (ffd->video_st>=0) ? GF_TRUE : GF_FALSE); } if ((ffd->video_st>=0) && (ffd->service_type != 2)) { od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG); esd = FFD_GetESDescriptor(ffd, GF_FALSE); od->objectDescriptorID = esd->ESID; esd->OCRESID = audio_esid; gf_list_add(od->ESDescriptors, esd); gf_service_declare_media(ffd->service, (GF_Descriptor*)od, GF_FALSE); } } #ifdef USE_PRE_0_7 static int ff_url_read(void *h, unsigned char *buf, int size) { u32 retry = 10; u32 read; int full_size; FFDemux *ffd = (FFDemux *)h; full_size = 0; if (ffd->buffer_used) { if (ffd->buffer_used >= (u32) size) { ffd->buffer_used-=size; memcpy(ffd->buffer, ffd->buffer+size, sizeof(char)*ffd->buffer_used); #ifdef FFMPEG_DUMP_REMOTE if (ffd->outdbg) gf_fwrite(buf, size, 1, ffd->outdbg); #endif return size; } full_size += ffd->buffer_used; buf += ffd->buffer_used; size -= ffd->buffer_used; ffd->buffer_used = 0; } while (size) { GF_Err e = gf_dm_sess_fetch_data(ffd->dnload, buf, size, &read); if (e==GF_EOS) break; /*we're sync!!*/ if (e==GF_IP_NETWORK_EMPTY) { if (!retry) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] timeout fetching bytes from network\n") ); return -1; } retry --; gf_sleep(100); continue; } if (e) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] error fetching bytes from network: %s\n", gf_error_to_string(e) ) ); return -1; } full_size += read; if (read==size) break; size -= read; buf += read; } #ifdef FFMPEG_DUMP_REMOTE if (ffd->outdbg) gf_fwrite(ffd->buffer, full_size, 1, ffd->outdbg); #endif return full_size ? (int) full_size : -1; } #endif /*USE_PRE_0_7*/ static GF_Err FFD_ConnectService(GF_InputService *plug, GF_ClientService *serv, const char *url) { GF_Err e; s64 last_aud_pts; u32 i; s32 res; Bool is_local; const char *sOpt; char *ext, szName[1024]; FFDemux *ffd = (FFDemux*)plug->priv; AVInputFormat *av_in = NULL; char szExt[20]; if (ffd->ctx) return GF_SERVICE_ERROR; assert( url && strlen(url) < 1024); strcpy(szName, url); ext = strrchr(szName, '#'); ffd->service_type = 0; ffd->service = serv; if (ext) { if (!stricmp(&ext[1], "video")) ffd->service_type = 1; else if (!stricmp(&ext[1], "audio")) ffd->service_type = 2; ext[0] = 0; } ffd_parse_options(ffd, url); /*some extensions not supported by ffmpeg, overload input format*/ ext = strrchr(szName, '.'); strcpy(szExt, ext ? ext+1 : ""); strlwr(szExt); if (!strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v"); is_local = (strnicmp(url, "file://", 7) && strstr(url, "://")) ? GF_FALSE : GF_TRUE; GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG] opening file %s - local %d - av_in %08x\n", url, is_local, av_in)); if (!is_local) { AVProbeData pd; /*setup wraper for FFMPEG I/O*/ ffd->buffer_size = 8192; sOpt = gf_modules_get_option((GF_BaseInterface *)plug, "FFMPEG", "IOBufferSize"); if (sOpt) ffd->buffer_size = atoi(sOpt); ffd->buffer = (char*)gf_malloc(sizeof(char)*ffd->buffer_size); #ifdef FFMPEG_DUMP_REMOTE ffd->outdbg = gf_fopen("ffdeb.raw", "wb"); #endif #ifdef USE_PRE_0_7 init_put_byte(&ffd->io, ffd->buffer, ffd->buffer_size, 0, ffd, ff_url_read, NULL, NULL); ffd->io.is_streamed = 1; #else ffd->io.seekable = 1; #endif ffd->dnload = gf_service_download_new(ffd->service, url, GF_NETIO_SESSION_NOT_THREADED | GF_NETIO_SESSION_NOT_CACHED, NULL, ffd); if (!ffd->dnload) return GF_URL_ERROR; while (1) { u32 read; e = gf_dm_sess_fetch_data(ffd->dnload, ffd->buffer + ffd->buffer_used, ffd->buffer_size - ffd->buffer_used, &read); if (e==GF_EOS) break; /*we're sync!!*/ if (e==GF_IP_NETWORK_EMPTY) continue; if (e) goto err_exit; ffd->buffer_used += read; if (ffd->buffer_used == ffd->buffer_size) break; } if (e==GF_EOS) { const char *cache_file = gf_dm_sess_get_cache_name(ffd->dnload); res = open_file(&ffd->ctx, cache_file, av_in, ffd->options ? &ffd->options : NULL); } else { pd.filename = szName; pd.buf_size = ffd->buffer_used; pd.buf = (u8 *) ffd->buffer; av_in = av_probe_input_format(&pd, 1); if (!av_in) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] error probing file %s - probe start with %c %c %c %c\n", url, ffd->buffer[0], ffd->buffer[1], ffd->buffer[2], ffd->buffer[3])); return GF_NOT_SUPPORTED; } /*setup downloader*/ av_in->flags |= AVFMT_NOFILE; #ifdef USE_AVFORMAT_OPEN_INPUT /*commit ffmpeg 603b8bc2a109978c8499b06d2556f1433306eca7*/ res = avformat_open_input(&ffd->ctx, szName, av_in, NULL); #else res = av_open_input_stream(&ffd->ctx, &ffd->io, szName, av_in, NULL); #endif } } else { res = open_file(&ffd->ctx, szName, av_in, ffd->options ? &ffd->options : NULL); } switch (res) { #ifndef _WIN32_WCE case 0: e = GF_OK; break; case AVERROR_IO: e = GF_URL_ERROR; goto err_exit; case AVERROR_INVALIDDATA: e = GF_NON_COMPLIANT_BITSTREAM; goto err_exit; case AVERROR_NOMEM: e = GF_OUT_OF_MEM; goto err_exit; case AVERROR_NOFMT: e = GF_NOT_SUPPORTED; goto err_exit; #endif default: e = GF_SERVICE_ERROR; goto err_exit; } GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG] looking for streams in %s - %d streams - type %s\n", ffd->ctx->filename, ffd->ctx->nb_streams, ffd->ctx->iformat->name)); #ifdef USE_AVFORMAT_OPEN_INPUT res = avformat_find_stream_info(ffd->ctx, ffd->options ? &ffd->options : NULL); #else res = av_find_stream_info(ffd->ctx); #endif if (res <0) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] cannot locate streams - error %d\n", res)); e = GF_NOT_SUPPORTED; goto err_exit; } GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG] file %s opened - %d streams\n", url, ffd->ctx->nb_streams)); /*figure out if we can use codecs or not*/ ffd->audio_st = ffd->video_st = -1; for (i = 0; i < ffd->ctx->nb_streams; i++) { AVCodecContext *enc = ffd->ctx->streams[i]->codec; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: if ((ffd->audio_st<0) && (ffd->service_type!=1)) { ffd->audio_st = i; ffd->audio_tscale = ffd->ctx->streams[i]->time_base; } break; case AVMEDIA_TYPE_VIDEO: if ((ffd->video_st<0) && (ffd->service_type!=2)) { ffd->video_st = i; ffd->video_tscale = ffd->ctx->streams[i]->time_base; } break; default: break; } } if ((ffd->service_type==1) && (ffd->video_st<0)) goto err_exit; if ((ffd->service_type==2) && (ffd->audio_st<0)) goto err_exit; if ((ffd->video_st<0) && (ffd->audio_st<0)) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] No supported streams in file\n")); goto err_exit; } sOpt = gf_modules_get_option((GF_BaseInterface *)plug, "FFMPEG", "DataBufferMS"); ffd->data_buffer_ms = 0; if (sOpt) ffd->data_buffer_ms = atoi(sOpt); if (!ffd->data_buffer_ms) ffd->data_buffer_ms = FFD_DATA_BUFFER; /*build seek*/ if (is_local) { /*check we do have increasing pts. If not we can't rely on pts, we must skip SL we assume video pts is always present*/ if (ffd->audio_st>=0) { last_aud_pts = 0; for (i=0; i<20; i++) { AVPacket pkt; pkt.stream_index = -1; if (av_read_frame(ffd->ctx, &pkt) <0) break; if (pkt.pts == AV_NOPTS_VALUE) pkt.pts = pkt.dts; if (pkt.stream_index==ffd->audio_st) last_aud_pts = pkt.pts; } if (last_aud_pts*ffd->audio_tscale.den<10*ffd->audio_tscale.num) ffd->unreliable_audio_timing = GF_TRUE; } ffd->seekable = (av_seek_frame(ffd->ctx, -1, 0, AVSEEK_FLAG_BACKWARD)<0) ? GF_FALSE : GF_TRUE; if (!ffd->seekable) { #if FF_API_CLOSE_INPUT_FILE av_close_input_file(ffd->ctx); #else avformat_close_input(&ffd->ctx); #endif ffd->ctx = NULL; open_file(&ffd->ctx, szName, av_in, ffd->options ? &ffd->options : NULL); av_find_stream_info(ffd->ctx); } } /*let's go*/ gf_service_connect_ack(serv, NULL, GF_OK); /*if (!ffd->service_type)*/ FFD_SetupObjects(ffd); ffd->service_type = 0; return GF_OK; err_exit: GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[FFMPEG] Error opening file %s: %s\n", url, gf_error_to_string(e))); #if FF_API_CLOSE_INPUT_FILE if (ffd->ctx) av_close_input_file(ffd->ctx); #else if (ffd->ctx) avformat_close_input(&ffd->ctx); #endif ffd->ctx = NULL; gf_service_connect_ack(serv, NULL, e); return e; } static GF_Descriptor *FFD_GetServiceDesc(GF_InputService *plug, u32 expect_type, const char *sub_url) { GF_ObjectDescriptor *od; GF_ESD *esd; FFDemux *ffd = (FFDemux*)plug->priv; if (!ffd->ctx) return NULL; if (expect_type==GF_MEDIA_OBJECT_UNDEF) { if (ffd->video_st>=0) expect_type=GF_MEDIA_OBJECT_VIDEO; else if (ffd->audio_st>=0) expect_type=GF_MEDIA_OBJECT_AUDIO; } /*since we don't handle multitrack in ffmpeg, we don't need to check sub_url, only use expected type*/ if (expect_type==GF_MEDIA_OBJECT_AUDIO) { if (ffd->audio_st<0) return NULL; od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG); od->objectDescriptorID = 1; esd = FFD_GetESDescriptor(ffd, GF_TRUE); /*if session join, setup sync*/ if (ffd->video_ch) esd->OCRESID = ffd->video_st+1; gf_list_add(od->ESDescriptors, esd); ffd->service_type = 2; return (GF_Descriptor *) od; } if (expect_type==GF_MEDIA_OBJECT_VIDEO) { if (ffd->video_st<0) return NULL; od = (GF_ObjectDescriptor *) gf_odf_desc_new(GF_ODF_OD_TAG); od->objectDescriptorID = 1; esd = FFD_GetESDescriptor(ffd, GF_FALSE); /*if session join, setup sync*/ if (ffd->audio_ch) esd->OCRESID = ffd->audio_st+1; gf_list_add(od->ESDescriptors, esd); ffd->service_type = 1; return (GF_Descriptor *) od; } return NULL; } static GF_Err FFD_CloseService(GF_InputService *plug) { FFDemux *ffd = (FFDemux*)plug->priv; ffd->is_running = 0; #if FF_API_CLOSE_INPUT_FILE if (ffd->ctx) av_close_input_file(ffd->ctx); #else if (ffd->ctx) avformat_close_input(&ffd->ctx); #endif ffd->ctx = NULL; ffd->audio_ch = ffd->video_ch = NULL; ffd->audio_run = ffd->video_run = GF_FALSE; if (ffd->dnload) { if (ffd->is_running) { while (!ffd->is_running) gf_sleep(1); ffd->is_running = 0; } gf_service_download_del(ffd->dnload); ffd->dnload = NULL; } if (ffd->buffer) gf_free(ffd->buffer); ffd->buffer = NULL; gf_service_disconnect_ack(ffd->service, NULL, GF_OK); #ifdef FFMPEG_DUMP_REMOTE if (ffd->outdbg) gf_fclose(ffd->outdbg); #endif return GF_OK; } static GF_Err FFD_ConnectChannel(GF_InputService *plug, LPNETCHANNEL channel, const char *url, Bool upstream) { GF_Err e; u32 ESID; FFDemux *ffd = (FFDemux*)plug->priv; e = GF_STREAM_NOT_FOUND; if (upstream) { e = GF_ISOM_INVALID_FILE; goto exit; } if (!strstr(url, "ES_ID=")) { e = GF_NOT_SUPPORTED; goto exit; } sscanf(url, "ES_ID=%u", &ESID); if ((s32) ESID == 1 + ffd->audio_st) { if (ffd->audio_ch) { e = GF_SERVICE_ERROR; goto exit; } ffd->audio_ch = channel; e = GF_OK; } else if ((s32) ESID == 1 + ffd->video_st) { if (ffd->video_ch) { e = GF_SERVICE_ERROR; goto exit; } ffd->video_ch = channel; e = GF_OK; } exit: gf_service_connect_ack(ffd->service, channel, e); return GF_OK; } static GF_Err FFD_DisconnectChannel(GF_InputService *plug, LPNETCHANNEL channel) { GF_Err e; FFDemux *ffd = (FFDemux*)plug->priv; e = GF_STREAM_NOT_FOUND; if (ffd->audio_ch == channel) { e = GF_OK; ffd->audio_ch = NULL; ffd->audio_run = GF_FALSE; } else if (ffd->video_ch == channel) { e = GF_OK; ffd->video_ch = NULL; ffd->video_run = GF_FALSE; } gf_service_disconnect_ack(ffd->service, channel, e); return GF_OK; } static GF_Err FFD_ServiceCommand(GF_InputService *plug, GF_NetworkCommand *com) { FFDemux *ffd = (FFDemux*)plug->priv; if (com->command_type==GF_NET_SERVICE_HAS_AUDIO) { if (ffd->audio_st>=0) return GF_OK; return GF_NOT_SUPPORTED; } if (!com->base.on_channel) return GF_NOT_SUPPORTED; switch (com->command_type) { /*only BIFS/OD work in pull mode (cf ffmpeg_in.h)*/ case GF_NET_CHAN_SET_PULL: return GF_NOT_SUPPORTED; case GF_NET_CHAN_INTERACTIVE: return ffd->seekable ? GF_OK : GF_NOT_SUPPORTED; case GF_NET_CHAN_BUFFER: return GF_OK; case GF_NET_CHAN_DURATION: if (ffd->ctx->duration == AV_NOPTS_VALUE) com->duration.duration = -1; else com->duration.duration = (Double) ffd->ctx->duration / AV_TIME_BASE; return GF_OK; /*fetch start time*/ case GF_NET_CHAN_PLAY: if (com->play.speed<0) return GF_NOT_SUPPORTED; gf_mx_p(ffd->mx); ffd->seek_time = (com->play.start_range>=0) ? com->play.start_range : 0; if (ffd->audio_ch==com->base.on_channel) ffd->audio_run = GF_TRUE; else if (ffd->video_ch==com->base.on_channel) ffd->video_run = GF_TRUE; /*play on media stream, start thread*/ if ((ffd->audio_ch==com->base.on_channel) || (ffd->video_ch==com->base.on_channel)) { if (ffd->is_running!=1) { ffd->is_running = 1; gf_th_run(ffd->thread, FFDemux_Run, ffd); } } gf_mx_v(ffd->mx); return GF_OK; case GF_NET_CHAN_STOP: if (ffd->audio_ch==com->base.on_channel) ffd->audio_run = GF_FALSE; else if (ffd->video_ch==com->base.on_channel) ffd->video_run = GF_FALSE; return GF_OK; /*note we don't handle PAUSE/RESUME/SET_SPEED, this is automatically handled by the demuxing thread through buffer occupancy queries*/ default: return GF_OK; } return GF_OK; } static Bool FFD_CanHandleURLInService(GF_InputService *plug, const char *url) { char szURL[2048], *sep; FFDemux *ffd; const char *this_url; if (!plug || !url) return GF_FALSE; ffd = (FFDemux *)plug->priv; this_url = gf_service_get_url(ffd->service); if (!this_url) return GF_FALSE; strcpy(szURL, this_url); sep = strrchr(szURL, '#'); if (sep) sep[0] = 0; if ((url[0] != '#') && strnicmp(szURL, url, sizeof(char)*strlen(szURL))) return GF_FALSE; sep = strrchr(url, '#'); if (sep && !stricmp(sep, "#video") && (ffd->video_st>=0)) return GF_TRUE; if (sep && !stricmp(sep, "#audio") && (ffd->audio_st>=0)) return GF_TRUE; return GF_FALSE; } void *New_FFMPEG_Demux() { GF_InputService *ffd; FFDemux *priv; GF_SAFEALLOC(ffd, GF_InputService); if (!ffd) return NULL; GF_SAFEALLOC(priv, FFDemux); if (!priv) { gf_free(ffd); return NULL; } GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] Registering all ffmpeg plugins...\n") ); /* register all codecs, demux and protocols */ av_register_all(); avformat_network_init(); GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[FFMPEG Demuxer] Registering all ffmpeg plugins DONE.\n") ); ffd->RegisterMimeTypes = FFD_RegisterMimeTypes; ffd->CanHandleURL = FFD_CanHandleURL; ffd->CloseService = FFD_CloseService; ffd->ConnectChannel = FFD_ConnectChannel; ffd->ConnectService = FFD_ConnectService; ffd->DisconnectChannel = FFD_DisconnectChannel; ffd->GetServiceDescriptor = FFD_GetServiceDesc; ffd->ServiceCommand = FFD_ServiceCommand; ffd->CanHandleURLInService = FFD_CanHandleURLInService; priv->thread = gf_th_new("FFMPEG Demux"); priv->mx = gf_mx_new("FFMPEG Demux"); if (!priv->thread || !priv->mx) { if (priv->thread) gf_th_del(priv->thread); if (priv->mx) gf_mx_del(priv->mx); gf_free(priv); return NULL; } GF_REGISTER_MODULE_INTERFACE(ffd, GF_NET_CLIENT_INTERFACE, "FFMPEG Demuxer", "gpac distribution"); ffd->priv = priv; return ffd; } void Delete_FFMPEG_Demux(void *ifce) { FFDemux *ffd; GF_InputService *ptr = (GF_InputService *)ifce; if (!ptr) return; ffd = (FFDemux*)ptr->priv; if (ffd) { if (ffd->thread) gf_th_del(ffd->thread); ffd->thread = NULL; if (ffd->mx) gf_mx_del(ffd->mx); #ifndef USE_PRE_0_7 if (ffd->options) av_dict_free(&ffd->options); #endif ffd->mx = NULL; gf_free(ffd); ptr->priv = NULL; } gf_free(ptr); } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/bad_525_2
crossvul-cpp_data_bad_3037_0
/* * Copyright (c) 2016 Avago Technologies. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful. * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO * THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. * See the GNU General Public License for more details, a copy of which * can be found in the file COPYING included with this package * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/slab.h> #include <linux/blk-mq.h> #include <linux/parser.h> #include <linux/random.h> #include <uapi/scsi/fc/fc_fs.h> #include <uapi/scsi/fc/fc_els.h> #include "nvmet.h" #include <linux/nvme-fc-driver.h> #include <linux/nvme-fc.h> /* *************************** Data Structures/Defines ****************** */ #define NVMET_LS_CTX_COUNT 4 /* for this implementation, assume small single frame rqst/rsp */ #define NVME_FC_MAX_LS_BUFFER_SIZE 2048 struct nvmet_fc_tgtport; struct nvmet_fc_tgt_assoc; struct nvmet_fc_ls_iod { struct nvmefc_tgt_ls_req *lsreq; struct nvmefc_tgt_fcp_req *fcpreq; /* only if RS */ struct list_head ls_list; /* tgtport->ls_list */ struct nvmet_fc_tgtport *tgtport; struct nvmet_fc_tgt_assoc *assoc; u8 *rqstbuf; u8 *rspbuf; u16 rqstdatalen; dma_addr_t rspdma; struct scatterlist sg[2]; struct work_struct work; } __aligned(sizeof(unsigned long long)); #define NVMET_FC_MAX_SEQ_LENGTH (256 * 1024) #define NVMET_FC_MAX_XFR_SGENTS (NVMET_FC_MAX_SEQ_LENGTH / PAGE_SIZE) enum nvmet_fcp_datadir { NVMET_FCP_NODATA, NVMET_FCP_WRITE, NVMET_FCP_READ, NVMET_FCP_ABORTED, }; struct nvmet_fc_fcp_iod { struct nvmefc_tgt_fcp_req *fcpreq; struct nvme_fc_cmd_iu cmdiubuf; struct nvme_fc_ersp_iu rspiubuf; dma_addr_t rspdma; struct scatterlist *data_sg; int data_sg_cnt; u32 total_length; u32 offset; enum nvmet_fcp_datadir io_dir; bool active; bool abort; bool aborted; bool writedataactive; spinlock_t flock; struct nvmet_req req; struct work_struct work; struct work_struct done_work; struct nvmet_fc_tgtport *tgtport; struct nvmet_fc_tgt_queue *queue; struct list_head fcp_list; /* tgtport->fcp_list */ }; struct nvmet_fc_tgtport { struct nvmet_fc_target_port fc_target_port; struct list_head tgt_list; /* nvmet_fc_target_list */ struct device *dev; /* dev for dma mapping */ struct nvmet_fc_target_template *ops; struct nvmet_fc_ls_iod *iod; spinlock_t lock; struct list_head ls_list; struct list_head ls_busylist; struct list_head assoc_list; struct ida assoc_cnt; struct nvmet_port *port; struct kref ref; u32 max_sg_cnt; }; struct nvmet_fc_defer_fcp_req { struct list_head req_list; struct nvmefc_tgt_fcp_req *fcp_req; }; struct nvmet_fc_tgt_queue { bool ninetypercent; u16 qid; u16 sqsize; u16 ersp_ratio; __le16 sqhd; int cpu; atomic_t connected; atomic_t sqtail; atomic_t zrspcnt; atomic_t rsn; spinlock_t qlock; struct nvmet_port *port; struct nvmet_cq nvme_cq; struct nvmet_sq nvme_sq; struct nvmet_fc_tgt_assoc *assoc; struct nvmet_fc_fcp_iod *fod; /* array of fcp_iods */ struct list_head fod_list; struct list_head pending_cmd_list; struct list_head avail_defer_list; struct workqueue_struct *work_q; struct kref ref; } __aligned(sizeof(unsigned long long)); struct nvmet_fc_tgt_assoc { u64 association_id; u32 a_id; struct nvmet_fc_tgtport *tgtport; struct list_head a_list; struct nvmet_fc_tgt_queue *queues[NVMET_NR_QUEUES + 1]; struct kref ref; }; static inline int nvmet_fc_iodnum(struct nvmet_fc_ls_iod *iodptr) { return (iodptr - iodptr->tgtport->iod); } static inline int nvmet_fc_fodnum(struct nvmet_fc_fcp_iod *fodptr) { return (fodptr - fodptr->queue->fod); } /* * Association and Connection IDs: * * Association ID will have random number in upper 6 bytes and zero * in lower 2 bytes * * Connection IDs will be Association ID with QID or'd in lower 2 bytes * * note: Association ID = Connection ID for queue 0 */ #define BYTES_FOR_QID sizeof(u16) #define BYTES_FOR_QID_SHIFT (BYTES_FOR_QID * 8) #define NVMET_FC_QUEUEID_MASK ((u64)((1 << BYTES_FOR_QID_SHIFT) - 1)) static inline u64 nvmet_fc_makeconnid(struct nvmet_fc_tgt_assoc *assoc, u16 qid) { return (assoc->association_id | qid); } static inline u64 nvmet_fc_getassociationid(u64 connectionid) { return connectionid & ~NVMET_FC_QUEUEID_MASK; } static inline u16 nvmet_fc_getqueueid(u64 connectionid) { return (u16)(connectionid & NVMET_FC_QUEUEID_MASK); } static inline struct nvmet_fc_tgtport * targetport_to_tgtport(struct nvmet_fc_target_port *targetport) { return container_of(targetport, struct nvmet_fc_tgtport, fc_target_port); } static inline struct nvmet_fc_fcp_iod * nvmet_req_to_fod(struct nvmet_req *nvme_req) { return container_of(nvme_req, struct nvmet_fc_fcp_iod, req); } /* *************************** Globals **************************** */ static DEFINE_SPINLOCK(nvmet_fc_tgtlock); static LIST_HEAD(nvmet_fc_target_list); static DEFINE_IDA(nvmet_fc_tgtport_cnt); static void nvmet_fc_handle_ls_rqst_work(struct work_struct *work); static void nvmet_fc_handle_fcp_rqst_work(struct work_struct *work); static void nvmet_fc_fcp_rqst_op_done_work(struct work_struct *work); static void nvmet_fc_tgt_a_put(struct nvmet_fc_tgt_assoc *assoc); static int nvmet_fc_tgt_a_get(struct nvmet_fc_tgt_assoc *assoc); static void nvmet_fc_tgt_q_put(struct nvmet_fc_tgt_queue *queue); static int nvmet_fc_tgt_q_get(struct nvmet_fc_tgt_queue *queue); static void nvmet_fc_tgtport_put(struct nvmet_fc_tgtport *tgtport); static int nvmet_fc_tgtport_get(struct nvmet_fc_tgtport *tgtport); static void nvmet_fc_handle_fcp_rqst(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod); /* *********************** FC-NVME DMA Handling **************************** */ /* * The fcloop device passes in a NULL device pointer. Real LLD's will * pass in a valid device pointer. If NULL is passed to the dma mapping * routines, depending on the platform, it may or may not succeed, and * may crash. * * As such: * Wrapper all the dma routines and check the dev pointer. * * If simple mappings (return just a dma address, we'll noop them, * returning a dma address of 0. * * On more complex mappings (dma_map_sg), a pseudo routine fills * in the scatter list, setting all dma addresses to 0. */ static inline dma_addr_t fc_dma_map_single(struct device *dev, void *ptr, size_t size, enum dma_data_direction dir) { return dev ? dma_map_single(dev, ptr, size, dir) : (dma_addr_t)0L; } static inline int fc_dma_mapping_error(struct device *dev, dma_addr_t dma_addr) { return dev ? dma_mapping_error(dev, dma_addr) : 0; } static inline void fc_dma_unmap_single(struct device *dev, dma_addr_t addr, size_t size, enum dma_data_direction dir) { if (dev) dma_unmap_single(dev, addr, size, dir); } static inline void fc_dma_sync_single_for_cpu(struct device *dev, dma_addr_t addr, size_t size, enum dma_data_direction dir) { if (dev) dma_sync_single_for_cpu(dev, addr, size, dir); } static inline void fc_dma_sync_single_for_device(struct device *dev, dma_addr_t addr, size_t size, enum dma_data_direction dir) { if (dev) dma_sync_single_for_device(dev, addr, size, dir); } /* pseudo dma_map_sg call */ static int fc_map_sg(struct scatterlist *sg, int nents) { struct scatterlist *s; int i; WARN_ON(nents == 0 || sg[0].length == 0); for_each_sg(sg, s, nents, i) { s->dma_address = 0L; #ifdef CONFIG_NEED_SG_DMA_LENGTH s->dma_length = s->length; #endif } return nents; } static inline int fc_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir) { return dev ? dma_map_sg(dev, sg, nents, dir) : fc_map_sg(sg, nents); } static inline void fc_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir) { if (dev) dma_unmap_sg(dev, sg, nents, dir); } /* *********************** FC-NVME Port Management ************************ */ static int nvmet_fc_alloc_ls_iodlist(struct nvmet_fc_tgtport *tgtport) { struct nvmet_fc_ls_iod *iod; int i; iod = kcalloc(NVMET_LS_CTX_COUNT, sizeof(struct nvmet_fc_ls_iod), GFP_KERNEL); if (!iod) return -ENOMEM; tgtport->iod = iod; for (i = 0; i < NVMET_LS_CTX_COUNT; iod++, i++) { INIT_WORK(&iod->work, nvmet_fc_handle_ls_rqst_work); iod->tgtport = tgtport; list_add_tail(&iod->ls_list, &tgtport->ls_list); iod->rqstbuf = kcalloc(2, NVME_FC_MAX_LS_BUFFER_SIZE, GFP_KERNEL); if (!iod->rqstbuf) goto out_fail; iod->rspbuf = iod->rqstbuf + NVME_FC_MAX_LS_BUFFER_SIZE; iod->rspdma = fc_dma_map_single(tgtport->dev, iod->rspbuf, NVME_FC_MAX_LS_BUFFER_SIZE, DMA_TO_DEVICE); if (fc_dma_mapping_error(tgtport->dev, iod->rspdma)) goto out_fail; } return 0; out_fail: kfree(iod->rqstbuf); list_del(&iod->ls_list); for (iod--, i--; i >= 0; iod--, i--) { fc_dma_unmap_single(tgtport->dev, iod->rspdma, NVME_FC_MAX_LS_BUFFER_SIZE, DMA_TO_DEVICE); kfree(iod->rqstbuf); list_del(&iod->ls_list); } kfree(iod); return -EFAULT; } static void nvmet_fc_free_ls_iodlist(struct nvmet_fc_tgtport *tgtport) { struct nvmet_fc_ls_iod *iod = tgtport->iod; int i; for (i = 0; i < NVMET_LS_CTX_COUNT; iod++, i++) { fc_dma_unmap_single(tgtport->dev, iod->rspdma, NVME_FC_MAX_LS_BUFFER_SIZE, DMA_TO_DEVICE); kfree(iod->rqstbuf); list_del(&iod->ls_list); } kfree(tgtport->iod); } static struct nvmet_fc_ls_iod * nvmet_fc_alloc_ls_iod(struct nvmet_fc_tgtport *tgtport) { struct nvmet_fc_ls_iod *iod; unsigned long flags; spin_lock_irqsave(&tgtport->lock, flags); iod = list_first_entry_or_null(&tgtport->ls_list, struct nvmet_fc_ls_iod, ls_list); if (iod) list_move_tail(&iod->ls_list, &tgtport->ls_busylist); spin_unlock_irqrestore(&tgtport->lock, flags); return iod; } static void nvmet_fc_free_ls_iod(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_ls_iod *iod) { unsigned long flags; spin_lock_irqsave(&tgtport->lock, flags); list_move(&iod->ls_list, &tgtport->ls_list); spin_unlock_irqrestore(&tgtport->lock, flags); } static void nvmet_fc_prep_fcp_iodlist(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_tgt_queue *queue) { struct nvmet_fc_fcp_iod *fod = queue->fod; int i; for (i = 0; i < queue->sqsize; fod++, i++) { INIT_WORK(&fod->work, nvmet_fc_handle_fcp_rqst_work); INIT_WORK(&fod->done_work, nvmet_fc_fcp_rqst_op_done_work); fod->tgtport = tgtport; fod->queue = queue; fod->active = false; fod->abort = false; fod->aborted = false; fod->fcpreq = NULL; list_add_tail(&fod->fcp_list, &queue->fod_list); spin_lock_init(&fod->flock); fod->rspdma = fc_dma_map_single(tgtport->dev, &fod->rspiubuf, sizeof(fod->rspiubuf), DMA_TO_DEVICE); if (fc_dma_mapping_error(tgtport->dev, fod->rspdma)) { list_del(&fod->fcp_list); for (fod--, i--; i >= 0; fod--, i--) { fc_dma_unmap_single(tgtport->dev, fod->rspdma, sizeof(fod->rspiubuf), DMA_TO_DEVICE); fod->rspdma = 0L; list_del(&fod->fcp_list); } return; } } } static void nvmet_fc_destroy_fcp_iodlist(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_tgt_queue *queue) { struct nvmet_fc_fcp_iod *fod = queue->fod; int i; for (i = 0; i < queue->sqsize; fod++, i++) { if (fod->rspdma) fc_dma_unmap_single(tgtport->dev, fod->rspdma, sizeof(fod->rspiubuf), DMA_TO_DEVICE); } } static struct nvmet_fc_fcp_iod * nvmet_fc_alloc_fcp_iod(struct nvmet_fc_tgt_queue *queue) { struct nvmet_fc_fcp_iod *fod; lockdep_assert_held(&queue->qlock); fod = list_first_entry_or_null(&queue->fod_list, struct nvmet_fc_fcp_iod, fcp_list); if (fod) { list_del(&fod->fcp_list); fod->active = true; /* * no queue reference is taken, as it was taken by the * queue lookup just prior to the allocation. The iod * will "inherit" that reference. */ } return fod; } static void nvmet_fc_queue_fcp_req(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_tgt_queue *queue, struct nvmefc_tgt_fcp_req *fcpreq) { struct nvmet_fc_fcp_iod *fod = fcpreq->nvmet_fc_private; /* * put all admin cmds on hw queue id 0. All io commands go to * the respective hw queue based on a modulo basis */ fcpreq->hwqid = queue->qid ? ((queue->qid - 1) % tgtport->ops->max_hw_queues) : 0; if (tgtport->ops->target_features & NVMET_FCTGTFEAT_CMD_IN_ISR) queue_work_on(queue->cpu, queue->work_q, &fod->work); else nvmet_fc_handle_fcp_rqst(tgtport, fod); } static void nvmet_fc_free_fcp_iod(struct nvmet_fc_tgt_queue *queue, struct nvmet_fc_fcp_iod *fod) { struct nvmefc_tgt_fcp_req *fcpreq = fod->fcpreq; struct nvmet_fc_tgtport *tgtport = fod->tgtport; struct nvmet_fc_defer_fcp_req *deferfcp; unsigned long flags; fc_dma_sync_single_for_cpu(tgtport->dev, fod->rspdma, sizeof(fod->rspiubuf), DMA_TO_DEVICE); fcpreq->nvmet_fc_private = NULL; fod->active = false; fod->abort = false; fod->aborted = false; fod->writedataactive = false; fod->fcpreq = NULL; tgtport->ops->fcp_req_release(&tgtport->fc_target_port, fcpreq); spin_lock_irqsave(&queue->qlock, flags); deferfcp = list_first_entry_or_null(&queue->pending_cmd_list, struct nvmet_fc_defer_fcp_req, req_list); if (!deferfcp) { list_add_tail(&fod->fcp_list, &fod->queue->fod_list); spin_unlock_irqrestore(&queue->qlock, flags); /* Release reference taken at queue lookup and fod allocation */ nvmet_fc_tgt_q_put(queue); return; } /* Re-use the fod for the next pending cmd that was deferred */ list_del(&deferfcp->req_list); fcpreq = deferfcp->fcp_req; /* deferfcp can be reused for another IO at a later date */ list_add_tail(&deferfcp->req_list, &queue->avail_defer_list); spin_unlock_irqrestore(&queue->qlock, flags); /* Save NVME CMD IO in fod */ memcpy(&fod->cmdiubuf, fcpreq->rspaddr, fcpreq->rsplen); /* Setup new fcpreq to be processed */ fcpreq->rspaddr = NULL; fcpreq->rsplen = 0; fcpreq->nvmet_fc_private = fod; fod->fcpreq = fcpreq; fod->active = true; /* inform LLDD IO is now being processed */ tgtport->ops->defer_rcv(&tgtport->fc_target_port, fcpreq); /* Submit deferred IO for processing */ nvmet_fc_queue_fcp_req(tgtport, queue, fcpreq); /* * Leave the queue lookup get reference taken when * fod was originally allocated. */ } static int nvmet_fc_queue_to_cpu(struct nvmet_fc_tgtport *tgtport, int qid) { int cpu, idx, cnt; if (tgtport->ops->max_hw_queues == 1) return WORK_CPU_UNBOUND; /* Simple cpu selection based on qid modulo active cpu count */ idx = !qid ? 0 : (qid - 1) % num_active_cpus(); /* find the n'th active cpu */ for (cpu = 0, cnt = 0; ; ) { if (cpu_active(cpu)) { if (cnt == idx) break; cnt++; } cpu = (cpu + 1) % num_possible_cpus(); } return cpu; } static struct nvmet_fc_tgt_queue * nvmet_fc_alloc_target_queue(struct nvmet_fc_tgt_assoc *assoc, u16 qid, u16 sqsize) { struct nvmet_fc_tgt_queue *queue; unsigned long flags; int ret; if (qid > NVMET_NR_QUEUES) return NULL; queue = kzalloc((sizeof(*queue) + (sizeof(struct nvmet_fc_fcp_iod) * sqsize)), GFP_KERNEL); if (!queue) return NULL; if (!nvmet_fc_tgt_a_get(assoc)) goto out_free_queue; queue->work_q = alloc_workqueue("ntfc%d.%d.%d", 0, 0, assoc->tgtport->fc_target_port.port_num, assoc->a_id, qid); if (!queue->work_q) goto out_a_put; queue->fod = (struct nvmet_fc_fcp_iod *)&queue[1]; queue->qid = qid; queue->sqsize = sqsize; queue->assoc = assoc; queue->port = assoc->tgtport->port; queue->cpu = nvmet_fc_queue_to_cpu(assoc->tgtport, qid); INIT_LIST_HEAD(&queue->fod_list); INIT_LIST_HEAD(&queue->avail_defer_list); INIT_LIST_HEAD(&queue->pending_cmd_list); atomic_set(&queue->connected, 0); atomic_set(&queue->sqtail, 0); atomic_set(&queue->rsn, 1); atomic_set(&queue->zrspcnt, 0); spin_lock_init(&queue->qlock); kref_init(&queue->ref); nvmet_fc_prep_fcp_iodlist(assoc->tgtport, queue); ret = nvmet_sq_init(&queue->nvme_sq); if (ret) goto out_fail_iodlist; WARN_ON(assoc->queues[qid]); spin_lock_irqsave(&assoc->tgtport->lock, flags); assoc->queues[qid] = queue; spin_unlock_irqrestore(&assoc->tgtport->lock, flags); return queue; out_fail_iodlist: nvmet_fc_destroy_fcp_iodlist(assoc->tgtport, queue); destroy_workqueue(queue->work_q); out_a_put: nvmet_fc_tgt_a_put(assoc); out_free_queue: kfree(queue); return NULL; } static void nvmet_fc_tgt_queue_free(struct kref *ref) { struct nvmet_fc_tgt_queue *queue = container_of(ref, struct nvmet_fc_tgt_queue, ref); unsigned long flags; spin_lock_irqsave(&queue->assoc->tgtport->lock, flags); queue->assoc->queues[queue->qid] = NULL; spin_unlock_irqrestore(&queue->assoc->tgtport->lock, flags); nvmet_fc_destroy_fcp_iodlist(queue->assoc->tgtport, queue); nvmet_fc_tgt_a_put(queue->assoc); destroy_workqueue(queue->work_q); kfree(queue); } static void nvmet_fc_tgt_q_put(struct nvmet_fc_tgt_queue *queue) { kref_put(&queue->ref, nvmet_fc_tgt_queue_free); } static int nvmet_fc_tgt_q_get(struct nvmet_fc_tgt_queue *queue) { return kref_get_unless_zero(&queue->ref); } static void nvmet_fc_delete_target_queue(struct nvmet_fc_tgt_queue *queue) { struct nvmet_fc_tgtport *tgtport = queue->assoc->tgtport; struct nvmet_fc_fcp_iod *fod = queue->fod; struct nvmet_fc_defer_fcp_req *deferfcp, *tempptr; unsigned long flags; int i, writedataactive; bool disconnect; disconnect = atomic_xchg(&queue->connected, 0); spin_lock_irqsave(&queue->qlock, flags); /* about outstanding io's */ for (i = 0; i < queue->sqsize; fod++, i++) { if (fod->active) { spin_lock(&fod->flock); fod->abort = true; writedataactive = fod->writedataactive; spin_unlock(&fod->flock); /* * only call lldd abort routine if waiting for * writedata. other outstanding ops should finish * on their own. */ if (writedataactive) { spin_lock(&fod->flock); fod->aborted = true; spin_unlock(&fod->flock); tgtport->ops->fcp_abort( &tgtport->fc_target_port, fod->fcpreq); } } } /* Cleanup defer'ed IOs in queue */ list_for_each_entry_safe(deferfcp, tempptr, &queue->avail_defer_list, req_list) { list_del(&deferfcp->req_list); kfree(deferfcp); } for (;;) { deferfcp = list_first_entry_or_null(&queue->pending_cmd_list, struct nvmet_fc_defer_fcp_req, req_list); if (!deferfcp) break; list_del(&deferfcp->req_list); spin_unlock_irqrestore(&queue->qlock, flags); tgtport->ops->defer_rcv(&tgtport->fc_target_port, deferfcp->fcp_req); tgtport->ops->fcp_abort(&tgtport->fc_target_port, deferfcp->fcp_req); tgtport->ops->fcp_req_release(&tgtport->fc_target_port, deferfcp->fcp_req); kfree(deferfcp); spin_lock_irqsave(&queue->qlock, flags); } spin_unlock_irqrestore(&queue->qlock, flags); flush_workqueue(queue->work_q); if (disconnect) nvmet_sq_destroy(&queue->nvme_sq); nvmet_fc_tgt_q_put(queue); } static struct nvmet_fc_tgt_queue * 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; } static struct nvmet_fc_tgt_assoc * nvmet_fc_alloc_target_assoc(struct nvmet_fc_tgtport *tgtport) { struct nvmet_fc_tgt_assoc *assoc, *tmpassoc; unsigned long flags; u64 ran; int idx; bool needrandom = true; assoc = kzalloc(sizeof(*assoc), GFP_KERNEL); if (!assoc) return NULL; idx = ida_simple_get(&tgtport->assoc_cnt, 0, 0, GFP_KERNEL); if (idx < 0) goto out_free_assoc; if (!nvmet_fc_tgtport_get(tgtport)) goto out_ida_put; assoc->tgtport = tgtport; assoc->a_id = idx; INIT_LIST_HEAD(&assoc->a_list); kref_init(&assoc->ref); while (needrandom) { get_random_bytes(&ran, sizeof(ran) - BYTES_FOR_QID); ran = ran << BYTES_FOR_QID_SHIFT; spin_lock_irqsave(&tgtport->lock, flags); needrandom = false; list_for_each_entry(tmpassoc, &tgtport->assoc_list, a_list) if (ran == tmpassoc->association_id) { needrandom = true; break; } if (!needrandom) { assoc->association_id = ran; list_add_tail(&assoc->a_list, &tgtport->assoc_list); } spin_unlock_irqrestore(&tgtport->lock, flags); } return assoc; out_ida_put: ida_simple_remove(&tgtport->assoc_cnt, idx); out_free_assoc: kfree(assoc); return NULL; } static void nvmet_fc_target_assoc_free(struct kref *ref) { struct nvmet_fc_tgt_assoc *assoc = container_of(ref, struct nvmet_fc_tgt_assoc, ref); struct nvmet_fc_tgtport *tgtport = assoc->tgtport; unsigned long flags; spin_lock_irqsave(&tgtport->lock, flags); list_del(&assoc->a_list); spin_unlock_irqrestore(&tgtport->lock, flags); ida_simple_remove(&tgtport->assoc_cnt, assoc->a_id); kfree(assoc); nvmet_fc_tgtport_put(tgtport); } static void nvmet_fc_tgt_a_put(struct nvmet_fc_tgt_assoc *assoc) { kref_put(&assoc->ref, nvmet_fc_target_assoc_free); } static int nvmet_fc_tgt_a_get(struct nvmet_fc_tgt_assoc *assoc) { return kref_get_unless_zero(&assoc->ref); } static void nvmet_fc_delete_target_assoc(struct nvmet_fc_tgt_assoc *assoc) { struct nvmet_fc_tgtport *tgtport = assoc->tgtport; struct nvmet_fc_tgt_queue *queue; unsigned long flags; int i; spin_lock_irqsave(&tgtport->lock, flags); for (i = NVMET_NR_QUEUES; i >= 0; i--) { queue = assoc->queues[i]; if (queue) { if (!nvmet_fc_tgt_q_get(queue)) continue; spin_unlock_irqrestore(&tgtport->lock, flags); nvmet_fc_delete_target_queue(queue); nvmet_fc_tgt_q_put(queue); spin_lock_irqsave(&tgtport->lock, flags); } } spin_unlock_irqrestore(&tgtport->lock, flags); nvmet_fc_tgt_a_put(assoc); } static struct nvmet_fc_tgt_assoc * nvmet_fc_find_target_assoc(struct nvmet_fc_tgtport *tgtport, u64 association_id) { struct nvmet_fc_tgt_assoc *assoc; struct nvmet_fc_tgt_assoc *ret = NULL; 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) { ret = assoc; nvmet_fc_tgt_a_get(assoc); break; } } spin_unlock_irqrestore(&tgtport->lock, flags); return ret; } /** * nvme_fc_register_targetport - transport entry point called by an * LLDD to register the existence of a local * NVME subystem FC port. * @pinfo: pointer to information about the port to be registered * @template: LLDD entrypoints and operational parameters for the port * @dev: physical hardware device node port corresponds to. Will be * used for DMA mappings * @portptr: pointer to a local port pointer. Upon success, the routine * will allocate a nvme_fc_local_port structure and place its * address in the local port pointer. Upon failure, local port * pointer will be set to NULL. * * Returns: * a completion status. Must be 0 upon success; a negative errno * (ex: -ENXIO) upon failure. */ int nvmet_fc_register_targetport(struct nvmet_fc_port_info *pinfo, struct nvmet_fc_target_template *template, struct device *dev, struct nvmet_fc_target_port **portptr) { struct nvmet_fc_tgtport *newrec; unsigned long flags; int ret, idx; if (!template->xmt_ls_rsp || !template->fcp_op || !template->fcp_abort || !template->fcp_req_release || !template->targetport_delete || !template->max_hw_queues || !template->max_sgl_segments || !template->max_dif_sgl_segments || !template->dma_boundary) { ret = -EINVAL; goto out_regtgt_failed; } newrec = kzalloc((sizeof(*newrec) + template->target_priv_sz), GFP_KERNEL); if (!newrec) { ret = -ENOMEM; goto out_regtgt_failed; } idx = ida_simple_get(&nvmet_fc_tgtport_cnt, 0, 0, GFP_KERNEL); if (idx < 0) { ret = -ENOSPC; goto out_fail_kfree; } if (!get_device(dev) && dev) { ret = -ENODEV; goto out_ida_put; } newrec->fc_target_port.node_name = pinfo->node_name; newrec->fc_target_port.port_name = pinfo->port_name; newrec->fc_target_port.private = &newrec[1]; newrec->fc_target_port.port_id = pinfo->port_id; newrec->fc_target_port.port_num = idx; INIT_LIST_HEAD(&newrec->tgt_list); newrec->dev = dev; newrec->ops = template; spin_lock_init(&newrec->lock); INIT_LIST_HEAD(&newrec->ls_list); INIT_LIST_HEAD(&newrec->ls_busylist); INIT_LIST_HEAD(&newrec->assoc_list); kref_init(&newrec->ref); ida_init(&newrec->assoc_cnt); newrec->max_sg_cnt = min_t(u32, NVMET_FC_MAX_XFR_SGENTS, template->max_sgl_segments); ret = nvmet_fc_alloc_ls_iodlist(newrec); if (ret) { ret = -ENOMEM; goto out_free_newrec; } spin_lock_irqsave(&nvmet_fc_tgtlock, flags); list_add_tail(&newrec->tgt_list, &nvmet_fc_target_list); spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); *portptr = &newrec->fc_target_port; return 0; out_free_newrec: put_device(dev); out_ida_put: ida_simple_remove(&nvmet_fc_tgtport_cnt, idx); out_fail_kfree: kfree(newrec); out_regtgt_failed: *portptr = NULL; return ret; } EXPORT_SYMBOL_GPL(nvmet_fc_register_targetport); static void nvmet_fc_free_tgtport(struct kref *ref) { struct nvmet_fc_tgtport *tgtport = container_of(ref, struct nvmet_fc_tgtport, ref); struct device *dev = tgtport->dev; unsigned long flags; spin_lock_irqsave(&nvmet_fc_tgtlock, flags); list_del(&tgtport->tgt_list); spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); nvmet_fc_free_ls_iodlist(tgtport); /* let the LLDD know we've finished tearing it down */ tgtport->ops->targetport_delete(&tgtport->fc_target_port); ida_simple_remove(&nvmet_fc_tgtport_cnt, tgtport->fc_target_port.port_num); ida_destroy(&tgtport->assoc_cnt); kfree(tgtport); put_device(dev); } static void nvmet_fc_tgtport_put(struct nvmet_fc_tgtport *tgtport) { kref_put(&tgtport->ref, nvmet_fc_free_tgtport); } static int nvmet_fc_tgtport_get(struct nvmet_fc_tgtport *tgtport) { return kref_get_unless_zero(&tgtport->ref); } static void __nvmet_fc_free_assocs(struct nvmet_fc_tgtport *tgtport) { struct nvmet_fc_tgt_assoc *assoc, *next; unsigned long flags; spin_lock_irqsave(&tgtport->lock, flags); list_for_each_entry_safe(assoc, next, &tgtport->assoc_list, a_list) { if (!nvmet_fc_tgt_a_get(assoc)) continue; spin_unlock_irqrestore(&tgtport->lock, flags); nvmet_fc_delete_target_assoc(assoc); nvmet_fc_tgt_a_put(assoc); spin_lock_irqsave(&tgtport->lock, flags); } spin_unlock_irqrestore(&tgtport->lock, flags); } /* * nvmet layer has called to terminate an association */ static void nvmet_fc_delete_ctrl(struct nvmet_ctrl *ctrl) { struct nvmet_fc_tgtport *tgtport, *next; struct nvmet_fc_tgt_assoc *assoc; struct nvmet_fc_tgt_queue *queue; unsigned long flags; bool found_ctrl = false; /* this is a bit ugly, but don't want to make locks layered */ spin_lock_irqsave(&nvmet_fc_tgtlock, flags); list_for_each_entry_safe(tgtport, next, &nvmet_fc_target_list, tgt_list) { if (!nvmet_fc_tgtport_get(tgtport)) continue; spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); spin_lock_irqsave(&tgtport->lock, flags); list_for_each_entry(assoc, &tgtport->assoc_list, a_list) { queue = assoc->queues[0]; if (queue && queue->nvme_sq.ctrl == ctrl) { if (nvmet_fc_tgt_a_get(assoc)) found_ctrl = true; break; } } spin_unlock_irqrestore(&tgtport->lock, flags); nvmet_fc_tgtport_put(tgtport); if (found_ctrl) { nvmet_fc_delete_target_assoc(assoc); nvmet_fc_tgt_a_put(assoc); return; } spin_lock_irqsave(&nvmet_fc_tgtlock, flags); } spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); } /** * nvme_fc_unregister_targetport - transport entry point called by an * LLDD to deregister/remove a previously * registered a local NVME subsystem FC port. * @tgtport: pointer to the (registered) target port that is to be * deregistered. * * Returns: * a completion status. Must be 0 upon success; a negative errno * (ex: -ENXIO) upon failure. */ int nvmet_fc_unregister_targetport(struct nvmet_fc_target_port *target_port) { struct nvmet_fc_tgtport *tgtport = targetport_to_tgtport(target_port); /* terminate any outstanding associations */ __nvmet_fc_free_assocs(tgtport); nvmet_fc_tgtport_put(tgtport); return 0; } EXPORT_SYMBOL_GPL(nvmet_fc_unregister_targetport); /* *********************** FC-NVME LS Handling **************************** */ static void nvmet_fc_format_rsp_hdr(void *buf, u8 ls_cmd, __be32 desc_len, u8 rqst_ls_cmd) { struct fcnvme_ls_acc_hdr *acc = buf; acc->w0.ls_cmd = ls_cmd; acc->desc_list_len = desc_len; acc->rqst.desc_tag = cpu_to_be32(FCNVME_LSDESC_RQST); acc->rqst.desc_len = fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_rqst)); acc->rqst.w0.ls_cmd = rqst_ls_cmd; } static int nvmet_fc_format_rjt(void *buf, u16 buflen, u8 ls_cmd, u8 reason, u8 explanation, u8 vendor) { struct fcnvme_ls_rjt *rjt = buf; nvmet_fc_format_rsp_hdr(buf, FCNVME_LSDESC_RQST, fcnvme_lsdesc_len(sizeof(struct fcnvme_ls_rjt)), ls_cmd); rjt->rjt.desc_tag = cpu_to_be32(FCNVME_LSDESC_RJT); rjt->rjt.desc_len = fcnvme_lsdesc_len(sizeof(struct fcnvme_lsdesc_rjt)); rjt->rjt.reason_code = reason; rjt->rjt.reason_explanation = explanation; rjt->rjt.vendor = vendor; return sizeof(struct fcnvme_ls_rjt); } /* Validation Error indexes into the string table below */ enum { VERR_NO_ERROR = 0, VERR_CR_ASSOC_LEN = 1, VERR_CR_ASSOC_RQST_LEN = 2, VERR_CR_ASSOC_CMD = 3, VERR_CR_ASSOC_CMD_LEN = 4, VERR_ERSP_RATIO = 5, VERR_ASSOC_ALLOC_FAIL = 6, VERR_QUEUE_ALLOC_FAIL = 7, VERR_CR_CONN_LEN = 8, VERR_CR_CONN_RQST_LEN = 9, VERR_ASSOC_ID = 10, VERR_ASSOC_ID_LEN = 11, VERR_NO_ASSOC = 12, VERR_CONN_ID = 13, VERR_CONN_ID_LEN = 14, VERR_NO_CONN = 15, VERR_CR_CONN_CMD = 16, VERR_CR_CONN_CMD_LEN = 17, VERR_DISCONN_LEN = 18, VERR_DISCONN_RQST_LEN = 19, VERR_DISCONN_CMD = 20, VERR_DISCONN_CMD_LEN = 21, VERR_DISCONN_SCOPE = 22, VERR_RS_LEN = 23, VERR_RS_RQST_LEN = 24, VERR_RS_CMD = 25, VERR_RS_CMD_LEN = 26, VERR_RS_RCTL = 27, VERR_RS_RO = 28, }; static char *validation_errors[] = { "OK", "Bad CR_ASSOC Length", "Bad CR_ASSOC Rqst Length", "Not CR_ASSOC Cmd", "Bad CR_ASSOC Cmd Length", "Bad Ersp Ratio", "Association Allocation Failed", "Queue Allocation Failed", "Bad CR_CONN Length", "Bad CR_CONN Rqst Length", "Not Association ID", "Bad Association ID Length", "No Association", "Not Connection ID", "Bad Connection ID Length", "No Connection", "Not CR_CONN Cmd", "Bad CR_CONN Cmd Length", "Bad DISCONN Length", "Bad DISCONN Rqst Length", "Not DISCONN Cmd", "Bad DISCONN Cmd Length", "Bad Disconnect Scope", "Bad RS Length", "Bad RS Rqst Length", "Not RS Cmd", "Bad RS Cmd Length", "Bad RS R_CTL", "Bad RS Relative Offset", }; static void nvmet_fc_ls_create_association(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_ls_iod *iod) { struct fcnvme_ls_cr_assoc_rqst *rqst = (struct fcnvme_ls_cr_assoc_rqst *)iod->rqstbuf; struct fcnvme_ls_cr_assoc_acc *acc = (struct fcnvme_ls_cr_assoc_acc *)iod->rspbuf; struct nvmet_fc_tgt_queue *queue; int ret = 0; memset(acc, 0, sizeof(*acc)); /* * FC-NVME spec changes. There are initiators sending different * lengths as padding sizes for Create Association Cmd descriptor * was incorrect. * Accept anything of "minimum" length. Assume format per 1.15 * spec (with HOSTID reduced to 16 bytes), ignore how long the * trailing pad length is. */ if (iod->rqstdatalen < FCNVME_LSDESC_CRA_RQST_MINLEN) ret = VERR_CR_ASSOC_LEN; else if (be32_to_cpu(rqst->desc_list_len) < FCNVME_LSDESC_CRA_RQST_MIN_LISTLEN) ret = VERR_CR_ASSOC_RQST_LEN; else if (rqst->assoc_cmd.desc_tag != cpu_to_be32(FCNVME_LSDESC_CREATE_ASSOC_CMD)) ret = VERR_CR_ASSOC_CMD; else if (be32_to_cpu(rqst->assoc_cmd.desc_len) < FCNVME_LSDESC_CRA_CMD_DESC_MIN_DESCLEN) ret = VERR_CR_ASSOC_CMD_LEN; else if (!rqst->assoc_cmd.ersp_ratio || (be16_to_cpu(rqst->assoc_cmd.ersp_ratio) >= be16_to_cpu(rqst->assoc_cmd.sqsize))) ret = VERR_ERSP_RATIO; else { /* new association w/ admin queue */ iod->assoc = nvmet_fc_alloc_target_assoc(tgtport); if (!iod->assoc) ret = VERR_ASSOC_ALLOC_FAIL; else { queue = nvmet_fc_alloc_target_queue(iod->assoc, 0, be16_to_cpu(rqst->assoc_cmd.sqsize)); if (!queue) ret = VERR_QUEUE_ALLOC_FAIL; } } if (ret) { dev_err(tgtport->dev, "Create Association LS failed: %s\n", validation_errors[ret]); iod->lsreq->rsplen = nvmet_fc_format_rjt(acc, NVME_FC_MAX_LS_BUFFER_SIZE, rqst->w0.ls_cmd, FCNVME_RJT_RC_LOGIC, FCNVME_RJT_EXP_NONE, 0); return; } queue->ersp_ratio = be16_to_cpu(rqst->assoc_cmd.ersp_ratio); atomic_set(&queue->connected, 1); queue->sqhd = 0; /* best place to init value */ /* format a response */ iod->lsreq->rsplen = sizeof(*acc); nvmet_fc_format_rsp_hdr(acc, FCNVME_LS_ACC, fcnvme_lsdesc_len( sizeof(struct fcnvme_ls_cr_assoc_acc)), FCNVME_LS_CREATE_ASSOCIATION); acc->associd.desc_tag = cpu_to_be32(FCNVME_LSDESC_ASSOC_ID); acc->associd.desc_len = fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_assoc_id)); acc->associd.association_id = cpu_to_be64(nvmet_fc_makeconnid(iod->assoc, 0)); acc->connectid.desc_tag = cpu_to_be32(FCNVME_LSDESC_CONN_ID); acc->connectid.desc_len = fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_conn_id)); acc->connectid.connection_id = acc->associd.association_id; } static void nvmet_fc_ls_create_connection(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_ls_iod *iod) { struct fcnvme_ls_cr_conn_rqst *rqst = (struct fcnvme_ls_cr_conn_rqst *)iod->rqstbuf; struct fcnvme_ls_cr_conn_acc *acc = (struct fcnvme_ls_cr_conn_acc *)iod->rspbuf; struct nvmet_fc_tgt_queue *queue; int ret = 0; memset(acc, 0, sizeof(*acc)); if (iod->rqstdatalen < sizeof(struct fcnvme_ls_cr_conn_rqst)) ret = VERR_CR_CONN_LEN; else if (rqst->desc_list_len != fcnvme_lsdesc_len( sizeof(struct fcnvme_ls_cr_conn_rqst))) ret = VERR_CR_CONN_RQST_LEN; else if (rqst->associd.desc_tag != cpu_to_be32(FCNVME_LSDESC_ASSOC_ID)) ret = VERR_ASSOC_ID; else if (rqst->associd.desc_len != fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_assoc_id))) ret = VERR_ASSOC_ID_LEN; else if (rqst->connect_cmd.desc_tag != cpu_to_be32(FCNVME_LSDESC_CREATE_CONN_CMD)) ret = VERR_CR_CONN_CMD; else if (rqst->connect_cmd.desc_len != fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_cr_conn_cmd))) ret = VERR_CR_CONN_CMD_LEN; else if (!rqst->connect_cmd.ersp_ratio || (be16_to_cpu(rqst->connect_cmd.ersp_ratio) >= be16_to_cpu(rqst->connect_cmd.sqsize))) ret = VERR_ERSP_RATIO; else { /* new io queue */ iod->assoc = nvmet_fc_find_target_assoc(tgtport, be64_to_cpu(rqst->associd.association_id)); if (!iod->assoc) ret = VERR_NO_ASSOC; else { queue = nvmet_fc_alloc_target_queue(iod->assoc, be16_to_cpu(rqst->connect_cmd.qid), be16_to_cpu(rqst->connect_cmd.sqsize)); if (!queue) ret = VERR_QUEUE_ALLOC_FAIL; /* release get taken in nvmet_fc_find_target_assoc */ nvmet_fc_tgt_a_put(iod->assoc); } } if (ret) { dev_err(tgtport->dev, "Create Connection LS failed: %s\n", validation_errors[ret]); iod->lsreq->rsplen = nvmet_fc_format_rjt(acc, NVME_FC_MAX_LS_BUFFER_SIZE, rqst->w0.ls_cmd, (ret == VERR_NO_ASSOC) ? FCNVME_RJT_RC_INV_ASSOC : FCNVME_RJT_RC_LOGIC, FCNVME_RJT_EXP_NONE, 0); return; } queue->ersp_ratio = be16_to_cpu(rqst->connect_cmd.ersp_ratio); atomic_set(&queue->connected, 1); queue->sqhd = 0; /* best place to init value */ /* format a response */ iod->lsreq->rsplen = sizeof(*acc); nvmet_fc_format_rsp_hdr(acc, FCNVME_LS_ACC, fcnvme_lsdesc_len(sizeof(struct fcnvme_ls_cr_conn_acc)), FCNVME_LS_CREATE_CONNECTION); acc->connectid.desc_tag = cpu_to_be32(FCNVME_LSDESC_CONN_ID); acc->connectid.desc_len = fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_conn_id)); acc->connectid.connection_id = cpu_to_be64(nvmet_fc_makeconnid(iod->assoc, be16_to_cpu(rqst->connect_cmd.qid))); } static void nvmet_fc_ls_disconnect(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_ls_iod *iod) { struct fcnvme_ls_disconnect_rqst *rqst = (struct fcnvme_ls_disconnect_rqst *)iod->rqstbuf; struct fcnvme_ls_disconnect_acc *acc = (struct fcnvme_ls_disconnect_acc *)iod->rspbuf; struct nvmet_fc_tgt_queue *queue = NULL; struct nvmet_fc_tgt_assoc *assoc; int ret = 0; bool del_assoc = false; memset(acc, 0, sizeof(*acc)); if (iod->rqstdatalen < sizeof(struct fcnvme_ls_disconnect_rqst)) ret = VERR_DISCONN_LEN; else if (rqst->desc_list_len != fcnvme_lsdesc_len( sizeof(struct fcnvme_ls_disconnect_rqst))) ret = VERR_DISCONN_RQST_LEN; else if (rqst->associd.desc_tag != cpu_to_be32(FCNVME_LSDESC_ASSOC_ID)) ret = VERR_ASSOC_ID; else if (rqst->associd.desc_len != fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_assoc_id))) ret = VERR_ASSOC_ID_LEN; else if (rqst->discon_cmd.desc_tag != cpu_to_be32(FCNVME_LSDESC_DISCONN_CMD)) ret = VERR_DISCONN_CMD; else if (rqst->discon_cmd.desc_len != fcnvme_lsdesc_len( sizeof(struct fcnvme_lsdesc_disconn_cmd))) ret = VERR_DISCONN_CMD_LEN; else if ((rqst->discon_cmd.scope != FCNVME_DISCONN_ASSOCIATION) && (rqst->discon_cmd.scope != FCNVME_DISCONN_CONNECTION)) ret = VERR_DISCONN_SCOPE; else { /* match an active association */ assoc = nvmet_fc_find_target_assoc(tgtport, be64_to_cpu(rqst->associd.association_id)); iod->assoc = assoc; if (assoc) { if (rqst->discon_cmd.scope == FCNVME_DISCONN_CONNECTION) { queue = nvmet_fc_find_target_queue(tgtport, be64_to_cpu( rqst->discon_cmd.id)); if (!queue) { nvmet_fc_tgt_a_put(assoc); ret = VERR_NO_CONN; } } } else ret = VERR_NO_ASSOC; } if (ret) { dev_err(tgtport->dev, "Disconnect LS failed: %s\n", validation_errors[ret]); iod->lsreq->rsplen = nvmet_fc_format_rjt(acc, NVME_FC_MAX_LS_BUFFER_SIZE, rqst->w0.ls_cmd, (ret == VERR_NO_ASSOC) ? FCNVME_RJT_RC_INV_ASSOC : (ret == VERR_NO_CONN) ? FCNVME_RJT_RC_INV_CONN : FCNVME_RJT_RC_LOGIC, FCNVME_RJT_EXP_NONE, 0); return; } /* format a response */ iod->lsreq->rsplen = sizeof(*acc); nvmet_fc_format_rsp_hdr(acc, FCNVME_LS_ACC, fcnvme_lsdesc_len( sizeof(struct fcnvme_ls_disconnect_acc)), FCNVME_LS_DISCONNECT); /* are we to delete a Connection ID (queue) */ if (queue) { int qid = queue->qid; nvmet_fc_delete_target_queue(queue); /* release the get taken by find_target_queue */ nvmet_fc_tgt_q_put(queue); /* tear association down if io queue terminated */ if (!qid) del_assoc = true; } /* release get taken in nvmet_fc_find_target_assoc */ nvmet_fc_tgt_a_put(iod->assoc); if (del_assoc) nvmet_fc_delete_target_assoc(iod->assoc); } /* *********************** NVME Ctrl Routines **************************** */ static void nvmet_fc_fcp_nvme_cmd_done(struct nvmet_req *nvme_req); static struct nvmet_fabrics_ops nvmet_fc_tgt_fcp_ops; static void nvmet_fc_xmt_ls_rsp_done(struct nvmefc_tgt_ls_req *lsreq) { struct nvmet_fc_ls_iod *iod = lsreq->nvmet_fc_private; struct nvmet_fc_tgtport *tgtport = iod->tgtport; fc_dma_sync_single_for_cpu(tgtport->dev, iod->rspdma, NVME_FC_MAX_LS_BUFFER_SIZE, DMA_TO_DEVICE); nvmet_fc_free_ls_iod(tgtport, iod); nvmet_fc_tgtport_put(tgtport); } static void nvmet_fc_xmt_ls_rsp(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_ls_iod *iod) { int ret; fc_dma_sync_single_for_device(tgtport->dev, iod->rspdma, NVME_FC_MAX_LS_BUFFER_SIZE, DMA_TO_DEVICE); ret = tgtport->ops->xmt_ls_rsp(&tgtport->fc_target_port, iod->lsreq); if (ret) nvmet_fc_xmt_ls_rsp_done(iod->lsreq); } /* * Actual processing routine for received FC-NVME LS Requests from the LLD */ static void nvmet_fc_handle_ls_rqst(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_ls_iod *iod) { struct fcnvme_ls_rqst_w0 *w0 = (struct fcnvme_ls_rqst_w0 *)iod->rqstbuf; iod->lsreq->nvmet_fc_private = iod; iod->lsreq->rspbuf = iod->rspbuf; iod->lsreq->rspdma = iod->rspdma; iod->lsreq->done = nvmet_fc_xmt_ls_rsp_done; /* Be preventative. handlers will later set to valid length */ iod->lsreq->rsplen = 0; iod->assoc = NULL; /* * handlers: * parse request input, execute the request, and format the * LS response */ switch (w0->ls_cmd) { case FCNVME_LS_CREATE_ASSOCIATION: /* Creates Association and initial Admin Queue/Connection */ nvmet_fc_ls_create_association(tgtport, iod); break; case FCNVME_LS_CREATE_CONNECTION: /* Creates an IO Queue/Connection */ nvmet_fc_ls_create_connection(tgtport, iod); break; case FCNVME_LS_DISCONNECT: /* Terminate a Queue/Connection or the Association */ nvmet_fc_ls_disconnect(tgtport, iod); break; default: iod->lsreq->rsplen = nvmet_fc_format_rjt(iod->rspbuf, NVME_FC_MAX_LS_BUFFER_SIZE, w0->ls_cmd, FCNVME_RJT_RC_INVAL, FCNVME_RJT_EXP_NONE, 0); } nvmet_fc_xmt_ls_rsp(tgtport, iod); } /* * Actual processing routine for received FC-NVME LS Requests from the LLD */ static void nvmet_fc_handle_ls_rqst_work(struct work_struct *work) { struct nvmet_fc_ls_iod *iod = container_of(work, struct nvmet_fc_ls_iod, work); struct nvmet_fc_tgtport *tgtport = iod->tgtport; nvmet_fc_handle_ls_rqst(tgtport, iod); } /** * nvmet_fc_rcv_ls_req - transport entry point called by an LLDD * upon the reception of a NVME LS request. * * The nvmet-fc layer will copy payload to an internal structure for * processing. As such, upon completion of the routine, the LLDD may * immediately free/reuse the LS request buffer passed in the call. * * If this routine returns error, the LLDD should abort the exchange. * * @tgtport: pointer to the (registered) target port the LS was * received on. * @lsreq: pointer to a lsreq request structure to be used to reference * the exchange corresponding to the LS. * @lsreqbuf: pointer to the buffer containing the LS Request * @lsreqbuf_len: length, in bytes, of the received LS request */ int nvmet_fc_rcv_ls_req(struct nvmet_fc_target_port *target_port, struct nvmefc_tgt_ls_req *lsreq, void *lsreqbuf, u32 lsreqbuf_len) { struct nvmet_fc_tgtport *tgtport = targetport_to_tgtport(target_port); struct nvmet_fc_ls_iod *iod; if (lsreqbuf_len > NVME_FC_MAX_LS_BUFFER_SIZE) return -E2BIG; if (!nvmet_fc_tgtport_get(tgtport)) return -ESHUTDOWN; iod = nvmet_fc_alloc_ls_iod(tgtport); if (!iod) { nvmet_fc_tgtport_put(tgtport); return -ENOENT; } iod->lsreq = lsreq; iod->fcpreq = NULL; memcpy(iod->rqstbuf, lsreqbuf, lsreqbuf_len); iod->rqstdatalen = lsreqbuf_len; schedule_work(&iod->work); return 0; } EXPORT_SYMBOL_GPL(nvmet_fc_rcv_ls_req); /* * ********************** * Start of FCP handling * ********************** */ static int nvmet_fc_alloc_tgt_pgs(struct nvmet_fc_fcp_iod *fod) { struct scatterlist *sg; struct page *page; unsigned int nent; u32 page_len, length; int i = 0; length = fod->total_length; nent = DIV_ROUND_UP(length, PAGE_SIZE); sg = kmalloc_array(nent, sizeof(struct scatterlist), GFP_KERNEL); if (!sg) goto out; sg_init_table(sg, nent); while (length) { page_len = min_t(u32, length, PAGE_SIZE); page = alloc_page(GFP_KERNEL); if (!page) goto out_free_pages; sg_set_page(&sg[i], page, page_len, 0); length -= page_len; i++; } fod->data_sg = sg; fod->data_sg_cnt = nent; fod->data_sg_cnt = fc_dma_map_sg(fod->tgtport->dev, sg, nent, ((fod->io_dir == NVMET_FCP_WRITE) ? DMA_FROM_DEVICE : DMA_TO_DEVICE)); /* note: write from initiator perspective */ return 0; out_free_pages: while (i > 0) { i--; __free_page(sg_page(&sg[i])); } kfree(sg); fod->data_sg = NULL; fod->data_sg_cnt = 0; out: return NVME_SC_INTERNAL; } static void nvmet_fc_free_tgt_pgs(struct nvmet_fc_fcp_iod *fod) { struct scatterlist *sg; int count; if (!fod->data_sg || !fod->data_sg_cnt) return; fc_dma_unmap_sg(fod->tgtport->dev, fod->data_sg, fod->data_sg_cnt, ((fod->io_dir == NVMET_FCP_WRITE) ? DMA_FROM_DEVICE : DMA_TO_DEVICE)); for_each_sg(fod->data_sg, sg, fod->data_sg_cnt, count) __free_page(sg_page(sg)); kfree(fod->data_sg); fod->data_sg = NULL; fod->data_sg_cnt = 0; } static bool queue_90percent_full(struct nvmet_fc_tgt_queue *q, u32 sqhd) { u32 sqtail, used; /* egad, this is ugly. And sqtail is just a best guess */ sqtail = atomic_read(&q->sqtail) % q->sqsize; used = (sqtail < sqhd) ? (sqtail + q->sqsize - sqhd) : (sqtail - sqhd); return ((used * 10) >= (((u32)(q->sqsize - 1) * 9))); } /* * Prep RSP payload. * May be a NVMET_FCOP_RSP or NVMET_FCOP_READDATA_RSP op */ static void nvmet_fc_prep_fcp_rsp(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod) { struct nvme_fc_ersp_iu *ersp = &fod->rspiubuf; struct nvme_common_command *sqe = &fod->cmdiubuf.sqe.common; struct nvme_completion *cqe = &ersp->cqe; u32 *cqewd = (u32 *)cqe; bool send_ersp = false; u32 rsn, rspcnt, xfr_length; if (fod->fcpreq->op == NVMET_FCOP_READDATA_RSP) xfr_length = fod->total_length; else xfr_length = fod->offset; /* * check to see if we can send a 0's rsp. * Note: to send a 0's response, the NVME-FC host transport will * recreate the CQE. The host transport knows: sq id, SQHD (last * seen in an ersp), and command_id. Thus it will create a * zero-filled CQE with those known fields filled in. Transport * must send an ersp for any condition where the cqe won't match * this. * * Here are the FC-NVME mandated cases where we must send an ersp: * every N responses, where N=ersp_ratio * force fabric commands to send ersp's (not in FC-NVME but good * practice) * normal cmds: any time status is non-zero, or status is zero * but words 0 or 1 are non-zero. * the SQ is 90% or more full * the cmd is a fused command * transferred data length not equal to cmd iu length */ rspcnt = atomic_inc_return(&fod->queue->zrspcnt); if (!(rspcnt % fod->queue->ersp_ratio) || sqe->opcode == nvme_fabrics_command || xfr_length != fod->total_length || (le16_to_cpu(cqe->status) & 0xFFFE) || cqewd[0] || cqewd[1] || (sqe->flags & (NVME_CMD_FUSE_FIRST | NVME_CMD_FUSE_SECOND)) || queue_90percent_full(fod->queue, le16_to_cpu(cqe->sq_head))) send_ersp = true; /* re-set the fields */ fod->fcpreq->rspaddr = ersp; fod->fcpreq->rspdma = fod->rspdma; if (!send_ersp) { memset(ersp, 0, NVME_FC_SIZEOF_ZEROS_RSP); fod->fcpreq->rsplen = NVME_FC_SIZEOF_ZEROS_RSP; } else { ersp->iu_len = cpu_to_be16(sizeof(*ersp)/sizeof(u32)); rsn = atomic_inc_return(&fod->queue->rsn); ersp->rsn = cpu_to_be32(rsn); ersp->xfrd_len = cpu_to_be32(xfr_length); fod->fcpreq->rsplen = sizeof(*ersp); } fc_dma_sync_single_for_device(tgtport->dev, fod->rspdma, sizeof(fod->rspiubuf), DMA_TO_DEVICE); } static void nvmet_fc_xmt_fcp_op_done(struct nvmefc_tgt_fcp_req *fcpreq); static void nvmet_fc_abort_op(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod) { struct nvmefc_tgt_fcp_req *fcpreq = fod->fcpreq; /* data no longer needed */ nvmet_fc_free_tgt_pgs(fod); /* * if an ABTS was received or we issued the fcp_abort early * don't call abort routine again. */ /* no need to take lock - lock was taken earlier to get here */ if (!fod->aborted) tgtport->ops->fcp_abort(&tgtport->fc_target_port, fcpreq); nvmet_fc_free_fcp_iod(fod->queue, fod); } static void nvmet_fc_xmt_fcp_rsp(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod) { int ret; fod->fcpreq->op = NVMET_FCOP_RSP; fod->fcpreq->timeout = 0; nvmet_fc_prep_fcp_rsp(tgtport, fod); ret = tgtport->ops->fcp_op(&tgtport->fc_target_port, fod->fcpreq); if (ret) nvmet_fc_abort_op(tgtport, fod); } static void nvmet_fc_transfer_fcp_data(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod, u8 op) { struct nvmefc_tgt_fcp_req *fcpreq = fod->fcpreq; unsigned long flags; u32 tlen; int ret; fcpreq->op = op; fcpreq->offset = fod->offset; fcpreq->timeout = NVME_FC_TGTOP_TIMEOUT_SEC; tlen = min_t(u32, tgtport->max_sg_cnt * PAGE_SIZE, (fod->total_length - fod->offset)); fcpreq->transfer_length = tlen; fcpreq->transferred_length = 0; fcpreq->fcp_error = 0; fcpreq->rsplen = 0; fcpreq->sg = &fod->data_sg[fod->offset / PAGE_SIZE]; fcpreq->sg_cnt = DIV_ROUND_UP(tlen, PAGE_SIZE); /* * If the last READDATA request: check if LLDD supports * combined xfr with response. */ if ((op == NVMET_FCOP_READDATA) && ((fod->offset + fcpreq->transfer_length) == fod->total_length) && (tgtport->ops->target_features & NVMET_FCTGTFEAT_READDATA_RSP)) { fcpreq->op = NVMET_FCOP_READDATA_RSP; nvmet_fc_prep_fcp_rsp(tgtport, fod); } ret = tgtport->ops->fcp_op(&tgtport->fc_target_port, fod->fcpreq); if (ret) { /* * should be ok to set w/o lock as its in the thread of * execution (not an async timer routine) and doesn't * contend with any clearing action */ fod->abort = true; if (op == NVMET_FCOP_WRITEDATA) { spin_lock_irqsave(&fod->flock, flags); fod->writedataactive = false; spin_unlock_irqrestore(&fod->flock, flags); nvmet_req_complete(&fod->req, NVME_SC_INTERNAL); } else /* NVMET_FCOP_READDATA or NVMET_FCOP_READDATA_RSP */ { fcpreq->fcp_error = ret; fcpreq->transferred_length = 0; nvmet_fc_xmt_fcp_op_done(fod->fcpreq); } } } static inline bool __nvmet_fc_fod_op_abort(struct nvmet_fc_fcp_iod *fod, bool abort) { struct nvmefc_tgt_fcp_req *fcpreq = fod->fcpreq; struct nvmet_fc_tgtport *tgtport = fod->tgtport; /* if in the middle of an io and we need to tear down */ if (abort) { if (fcpreq->op == NVMET_FCOP_WRITEDATA) { nvmet_req_complete(&fod->req, NVME_SC_INTERNAL); return true; } nvmet_fc_abort_op(tgtport, fod); return true; } return false; } /* * actual done handler for FCP operations when completed by the lldd */ static void nvmet_fc_fod_op_done(struct nvmet_fc_fcp_iod *fod) { struct nvmefc_tgt_fcp_req *fcpreq = fod->fcpreq; struct nvmet_fc_tgtport *tgtport = fod->tgtport; unsigned long flags; bool abort; spin_lock_irqsave(&fod->flock, flags); abort = fod->abort; fod->writedataactive = false; spin_unlock_irqrestore(&fod->flock, flags); switch (fcpreq->op) { case NVMET_FCOP_WRITEDATA: if (__nvmet_fc_fod_op_abort(fod, abort)) return; if (fcpreq->fcp_error || fcpreq->transferred_length != fcpreq->transfer_length) { spin_lock(&fod->flock); fod->abort = true; spin_unlock(&fod->flock); nvmet_req_complete(&fod->req, NVME_SC_INTERNAL); return; } fod->offset += fcpreq->transferred_length; if (fod->offset != fod->total_length) { spin_lock_irqsave(&fod->flock, flags); fod->writedataactive = true; spin_unlock_irqrestore(&fod->flock, flags); /* transfer the next chunk */ nvmet_fc_transfer_fcp_data(tgtport, fod, NVMET_FCOP_WRITEDATA); return; } /* data transfer complete, resume with nvmet layer */ fod->req.execute(&fod->req); break; case NVMET_FCOP_READDATA: case NVMET_FCOP_READDATA_RSP: if (__nvmet_fc_fod_op_abort(fod, abort)) return; if (fcpreq->fcp_error || fcpreq->transferred_length != fcpreq->transfer_length) { nvmet_fc_abort_op(tgtport, fod); return; } /* success */ if (fcpreq->op == NVMET_FCOP_READDATA_RSP) { /* data no longer needed */ nvmet_fc_free_tgt_pgs(fod); nvmet_fc_free_fcp_iod(fod->queue, fod); return; } fod->offset += fcpreq->transferred_length; if (fod->offset != fod->total_length) { /* transfer the next chunk */ nvmet_fc_transfer_fcp_data(tgtport, fod, NVMET_FCOP_READDATA); return; } /* data transfer complete, send response */ /* data no longer needed */ nvmet_fc_free_tgt_pgs(fod); nvmet_fc_xmt_fcp_rsp(tgtport, fod); break; case NVMET_FCOP_RSP: if (__nvmet_fc_fod_op_abort(fod, abort)) return; nvmet_fc_free_fcp_iod(fod->queue, fod); break; default: break; } } static void nvmet_fc_fcp_rqst_op_done_work(struct work_struct *work) { struct nvmet_fc_fcp_iod *fod = container_of(work, struct nvmet_fc_fcp_iod, done_work); nvmet_fc_fod_op_done(fod); } static void nvmet_fc_xmt_fcp_op_done(struct nvmefc_tgt_fcp_req *fcpreq) { struct nvmet_fc_fcp_iod *fod = fcpreq->nvmet_fc_private; struct nvmet_fc_tgt_queue *queue = fod->queue; if (fod->tgtport->ops->target_features & NVMET_FCTGTFEAT_OPDONE_IN_ISR) /* context switch so completion is not in ISR context */ queue_work_on(queue->cpu, queue->work_q, &fod->done_work); else nvmet_fc_fod_op_done(fod); } /* * actual completion handler after execution by the nvmet layer */ static void __nvmet_fc_fcp_nvme_cmd_done(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod, int status) { struct nvme_common_command *sqe = &fod->cmdiubuf.sqe.common; struct nvme_completion *cqe = &fod->rspiubuf.cqe; unsigned long flags; bool abort; spin_lock_irqsave(&fod->flock, flags); abort = fod->abort; spin_unlock_irqrestore(&fod->flock, flags); /* if we have a CQE, snoop the last sq_head value */ if (!status) fod->queue->sqhd = cqe->sq_head; if (abort) { nvmet_fc_abort_op(tgtport, fod); return; } /* if an error handling the cmd post initial parsing */ if (status) { /* fudge up a failed CQE status for our transport error */ memset(cqe, 0, sizeof(*cqe)); cqe->sq_head = fod->queue->sqhd; /* echo last cqe sqhd */ cqe->sq_id = cpu_to_le16(fod->queue->qid); cqe->command_id = sqe->command_id; cqe->status = cpu_to_le16(status); } else { /* * try to push the data even if the SQE status is non-zero. * There may be a status where data still was intended to * be moved */ if ((fod->io_dir == NVMET_FCP_READ) && (fod->data_sg_cnt)) { /* push the data over before sending rsp */ nvmet_fc_transfer_fcp_data(tgtport, fod, NVMET_FCOP_READDATA); return; } /* writes & no data - fall thru */ } /* data no longer needed */ nvmet_fc_free_tgt_pgs(fod); nvmet_fc_xmt_fcp_rsp(tgtport, fod); } static void nvmet_fc_fcp_nvme_cmd_done(struct nvmet_req *nvme_req) { struct nvmet_fc_fcp_iod *fod = nvmet_req_to_fod(nvme_req); struct nvmet_fc_tgtport *tgtport = fod->tgtport; __nvmet_fc_fcp_nvme_cmd_done(tgtport, fod, 0); } /* * Actual processing routine for received FC-NVME LS Requests from the LLD */ static void nvmet_fc_handle_fcp_rqst(struct nvmet_fc_tgtport *tgtport, struct nvmet_fc_fcp_iod *fod) { struct nvme_fc_cmd_iu *cmdiu = &fod->cmdiubuf; int ret; /* * Fused commands are currently not supported in the linux * implementation. * * As such, the implementation of the FC transport does not * look at the fused commands and order delivery to the upper * layer until we have both based on csn. */ fod->fcpreq->done = nvmet_fc_xmt_fcp_op_done; fod->total_length = be32_to_cpu(cmdiu->data_len); if (cmdiu->flags & FCNVME_CMD_FLAGS_WRITE) { fod->io_dir = NVMET_FCP_WRITE; if (!nvme_is_write(&cmdiu->sqe)) goto transport_error; } else if (cmdiu->flags & FCNVME_CMD_FLAGS_READ) { fod->io_dir = NVMET_FCP_READ; if (nvme_is_write(&cmdiu->sqe)) goto transport_error; } else { fod->io_dir = NVMET_FCP_NODATA; if (fod->total_length) goto transport_error; } fod->req.cmd = &fod->cmdiubuf.sqe; fod->req.rsp = &fod->rspiubuf.cqe; fod->req.port = fod->queue->port; /* ensure nvmet handlers will set cmd handler callback */ fod->req.execute = NULL; /* clear any response payload */ memset(&fod->rspiubuf, 0, sizeof(fod->rspiubuf)); fod->data_sg = NULL; fod->data_sg_cnt = 0; ret = nvmet_req_init(&fod->req, &fod->queue->nvme_cq, &fod->queue->nvme_sq, &nvmet_fc_tgt_fcp_ops); if (!ret) { /* bad SQE content or invalid ctrl state */ /* nvmet layer has already called op done to send rsp. */ return; } /* keep a running counter of tail position */ atomic_inc(&fod->queue->sqtail); if (fod->total_length) { ret = nvmet_fc_alloc_tgt_pgs(fod); if (ret) { nvmet_req_complete(&fod->req, ret); return; } } fod->req.sg = fod->data_sg; fod->req.sg_cnt = fod->data_sg_cnt; fod->offset = 0; if (fod->io_dir == NVMET_FCP_WRITE) { /* pull the data over before invoking nvmet layer */ nvmet_fc_transfer_fcp_data(tgtport, fod, NVMET_FCOP_WRITEDATA); return; } /* * Reads or no data: * * can invoke the nvmet_layer now. If read data, cmd completion will * push the data */ fod->req.execute(&fod->req); return; transport_error: nvmet_fc_abort_op(tgtport, fod); } /* * Actual processing routine for received FC-NVME LS Requests from the LLD */ static void nvmet_fc_handle_fcp_rqst_work(struct work_struct *work) { struct nvmet_fc_fcp_iod *fod = container_of(work, struct nvmet_fc_fcp_iod, work); struct nvmet_fc_tgtport *tgtport = fod->tgtport; nvmet_fc_handle_fcp_rqst(tgtport, fod); } /** * nvmet_fc_rcv_fcp_req - transport entry point called by an LLDD * upon the reception of a NVME FCP CMD IU. * * Pass a FC-NVME FCP CMD IU received from the FC link to the nvmet-fc * layer for processing. * * The nvmet_fc layer allocates a local job structure (struct * nvmet_fc_fcp_iod) from the queue for the io and copies the * CMD IU buffer to the job structure. As such, on a successful * completion (returns 0), the LLDD may immediately free/reuse * the CMD IU buffer passed in the call. * * However, in some circumstances, due to the packetized nature of FC * and the api of the FC LLDD which may issue a hw command to send the * response, but the LLDD may not get the hw completion for that command * and upcall the nvmet_fc layer before a new command may be * asynchronously received - its possible for a command to be received * before the LLDD and nvmet_fc have recycled the job structure. It gives * the appearance of more commands received than fits in the sq. * To alleviate this scenario, a temporary queue is maintained in the * transport for pending LLDD requests waiting for a queue job structure. * In these "overrun" cases, a temporary queue element is allocated * the LLDD request and CMD iu buffer information remembered, and the * routine returns a -EOVERFLOW status. Subsequently, when a queue job * structure is freed, it is immediately reallocated for anything on the * pending request list. The LLDDs defer_rcv() callback is called, * informing the LLDD that it may reuse the CMD IU buffer, and the io * is then started normally with the transport. * * The LLDD, when receiving an -EOVERFLOW completion status, is to treat * the completion as successful but must not reuse the CMD IU buffer * until the LLDD's defer_rcv() callback has been called for the * corresponding struct nvmefc_tgt_fcp_req pointer. * * If there is any other condition in which an error occurs, the * transport will return a non-zero status indicating the error. * In all cases other than -EOVERFLOW, the transport has not accepted the * request and the LLDD should abort the exchange. * * @target_port: pointer to the (registered) target port the FCP CMD IU * was received on. * @fcpreq: pointer to a fcpreq request structure to be used to reference * the exchange corresponding to the FCP Exchange. * @cmdiubuf: pointer to the buffer containing the FCP CMD IU * @cmdiubuf_len: length, in bytes, of the received FCP CMD IU */ int nvmet_fc_rcv_fcp_req(struct nvmet_fc_target_port *target_port, struct nvmefc_tgt_fcp_req *fcpreq, void *cmdiubuf, u32 cmdiubuf_len) { struct nvmet_fc_tgtport *tgtport = targetport_to_tgtport(target_port); struct nvme_fc_cmd_iu *cmdiu = cmdiubuf; struct nvmet_fc_tgt_queue *queue; struct nvmet_fc_fcp_iod *fod; struct nvmet_fc_defer_fcp_req *deferfcp; unsigned long flags; /* validate iu, so the connection id can be used to find the queue */ if ((cmdiubuf_len != sizeof(*cmdiu)) || (cmdiu->scsi_id != NVME_CMD_SCSI_ID) || (cmdiu->fc_id != NVME_CMD_FC_ID) || (be16_to_cpu(cmdiu->iu_len) != (sizeof(*cmdiu)/4))) return -EIO; queue = nvmet_fc_find_target_queue(tgtport, be64_to_cpu(cmdiu->connection_id)); if (!queue) return -ENOTCONN; /* * note: reference taken by find_target_queue * After successful fod allocation, the fod will inherit the * ownership of that reference and will remove the reference * when the fod is freed. */ spin_lock_irqsave(&queue->qlock, flags); fod = nvmet_fc_alloc_fcp_iod(queue); if (fod) { spin_unlock_irqrestore(&queue->qlock, flags); fcpreq->nvmet_fc_private = fod; fod->fcpreq = fcpreq; memcpy(&fod->cmdiubuf, cmdiubuf, cmdiubuf_len); nvmet_fc_queue_fcp_req(tgtport, queue, fcpreq); return 0; } if (!tgtport->ops->defer_rcv) { spin_unlock_irqrestore(&queue->qlock, flags); /* release the queue lookup reference */ nvmet_fc_tgt_q_put(queue); return -ENOENT; } deferfcp = list_first_entry_or_null(&queue->avail_defer_list, struct nvmet_fc_defer_fcp_req, req_list); if (deferfcp) { /* Just re-use one that was previously allocated */ list_del(&deferfcp->req_list); } else { spin_unlock_irqrestore(&queue->qlock, flags); /* Now we need to dynamically allocate one */ deferfcp = kmalloc(sizeof(*deferfcp), GFP_KERNEL); if (!deferfcp) { /* release the queue lookup reference */ nvmet_fc_tgt_q_put(queue); return -ENOMEM; } spin_lock_irqsave(&queue->qlock, flags); } /* For now, use rspaddr / rsplen to save payload information */ fcpreq->rspaddr = cmdiubuf; fcpreq->rsplen = cmdiubuf_len; deferfcp->fcp_req = fcpreq; /* defer processing till a fod becomes available */ list_add_tail(&deferfcp->req_list, &queue->pending_cmd_list); /* NOTE: the queue lookup reference is still valid */ spin_unlock_irqrestore(&queue->qlock, flags); return -EOVERFLOW; } EXPORT_SYMBOL_GPL(nvmet_fc_rcv_fcp_req); /** * nvmet_fc_rcv_fcp_abort - transport entry point called by an LLDD * upon the reception of an ABTS for a FCP command * * Notify the transport that an ABTS has been received for a FCP command * that had been given to the transport via nvmet_fc_rcv_fcp_req(). The * LLDD believes the command is still being worked on * (template_ops->fcp_req_release() has not been called). * * The transport will wait for any outstanding work (an op to the LLDD, * which the lldd should complete with error due to the ABTS; or the * completion from the nvmet layer of the nvme command), then will * stop processing and call the nvmet_fc_rcv_fcp_req() callback to * return the i/o context to the LLDD. The LLDD may send the BA_ACC * to the ABTS either after return from this function (assuming any * outstanding op work has been terminated) or upon the callback being * called. * * @target_port: pointer to the (registered) target port the FCP CMD IU * was received on. * @fcpreq: pointer to the fcpreq request structure that corresponds * to the exchange that received the ABTS. */ void nvmet_fc_rcv_fcp_abort(struct nvmet_fc_target_port *target_port, struct nvmefc_tgt_fcp_req *fcpreq) { struct nvmet_fc_fcp_iod *fod = fcpreq->nvmet_fc_private; struct nvmet_fc_tgt_queue *queue; unsigned long flags; if (!fod || fod->fcpreq != fcpreq) /* job appears to have already completed, ignore abort */ return; queue = fod->queue; spin_lock_irqsave(&queue->qlock, flags); if (fod->active) { /* * mark as abort. The abort handler, invoked upon completion * of any work, will detect the aborted status and do the * callback. */ spin_lock(&fod->flock); fod->abort = true; fod->aborted = true; spin_unlock(&fod->flock); } spin_unlock_irqrestore(&queue->qlock, flags); } EXPORT_SYMBOL_GPL(nvmet_fc_rcv_fcp_abort); struct nvmet_fc_traddr { u64 nn; u64 pn; }; static int __nvme_fc_parse_u64(substring_t *sstr, u64 *val) { u64 token64; if (match_u64(sstr, &token64)) return -EINVAL; *val = token64; return 0; } /* * This routine validates and extracts the WWN's from the TRADDR string. * As kernel parsers need the 0x to determine number base, universally * build string to parse with 0x prefix before parsing name strings. */ static int nvme_fc_parse_traddr(struct nvmet_fc_traddr *traddr, char *buf, size_t blen) { char name[2 + NVME_FC_TRADDR_HEXNAMELEN + 1]; substring_t wwn = { name, &name[sizeof(name)-1] }; int nnoffset, pnoffset; /* validate it string one of the 2 allowed formats */ if (strnlen(buf, blen) == NVME_FC_TRADDR_MAXLENGTH && !strncmp(buf, "nn-0x", NVME_FC_TRADDR_OXNNLEN) && !strncmp(&buf[NVME_FC_TRADDR_MAX_PN_OFFSET], "pn-0x", NVME_FC_TRADDR_OXNNLEN)) { nnoffset = NVME_FC_TRADDR_OXNNLEN; pnoffset = NVME_FC_TRADDR_MAX_PN_OFFSET + NVME_FC_TRADDR_OXNNLEN; } else if ((strnlen(buf, blen) == NVME_FC_TRADDR_MINLENGTH && !strncmp(buf, "nn-", NVME_FC_TRADDR_NNLEN) && !strncmp(&buf[NVME_FC_TRADDR_MIN_PN_OFFSET], "pn-", NVME_FC_TRADDR_NNLEN))) { nnoffset = NVME_FC_TRADDR_NNLEN; pnoffset = NVME_FC_TRADDR_MIN_PN_OFFSET + NVME_FC_TRADDR_NNLEN; } else goto out_einval; name[0] = '0'; name[1] = 'x'; name[2 + NVME_FC_TRADDR_HEXNAMELEN] = 0; memcpy(&name[2], &buf[nnoffset], NVME_FC_TRADDR_HEXNAMELEN); if (__nvme_fc_parse_u64(&wwn, &traddr->nn)) goto out_einval; memcpy(&name[2], &buf[pnoffset], NVME_FC_TRADDR_HEXNAMELEN); if (__nvme_fc_parse_u64(&wwn, &traddr->pn)) goto out_einval; return 0; out_einval: pr_warn("%s: bad traddr string\n", __func__); return -EINVAL; } static int nvmet_fc_add_port(struct nvmet_port *port) { struct nvmet_fc_tgtport *tgtport; struct nvmet_fc_traddr traddr = { 0L, 0L }; unsigned long flags; int ret; /* validate the address info */ if ((port->disc_addr.trtype != NVMF_TRTYPE_FC) || (port->disc_addr.adrfam != NVMF_ADDR_FAMILY_FC)) return -EINVAL; /* map the traddr address info to a target port */ ret = nvme_fc_parse_traddr(&traddr, port->disc_addr.traddr, sizeof(port->disc_addr.traddr)); if (ret) return ret; ret = -ENXIO; spin_lock_irqsave(&nvmet_fc_tgtlock, flags); list_for_each_entry(tgtport, &nvmet_fc_target_list, tgt_list) { if ((tgtport->fc_target_port.node_name == traddr.nn) && (tgtport->fc_target_port.port_name == traddr.pn)) { /* a FC port can only be 1 nvmet port id */ if (!tgtport->port) { tgtport->port = port; port->priv = tgtport; nvmet_fc_tgtport_get(tgtport); ret = 0; } else ret = -EALREADY; break; } } spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); return ret; } static void nvmet_fc_remove_port(struct nvmet_port *port) { struct nvmet_fc_tgtport *tgtport = port->priv; unsigned long flags; bool matched = false; spin_lock_irqsave(&nvmet_fc_tgtlock, flags); if (tgtport->port == port) { matched = true; tgtport->port = NULL; } spin_unlock_irqrestore(&nvmet_fc_tgtlock, flags); if (matched) nvmet_fc_tgtport_put(tgtport); } static struct nvmet_fabrics_ops nvmet_fc_tgt_fcp_ops = { .owner = THIS_MODULE, .type = NVMF_TRTYPE_FC, .msdbd = 1, .add_port = nvmet_fc_add_port, .remove_port = nvmet_fc_remove_port, .queue_response = nvmet_fc_fcp_nvme_cmd_done, .delete_ctrl = nvmet_fc_delete_ctrl, }; static int __init nvmet_fc_init_module(void) { return nvmet_register_transport(&nvmet_fc_tgt_fcp_ops); } static void __exit nvmet_fc_exit_module(void) { /* sanity check - all lports should be removed */ if (!list_empty(&nvmet_fc_target_list)) pr_warn("%s: targetport list not empty\n", __func__); nvmet_unregister_transport(&nvmet_fc_tgt_fcp_ops); ida_destroy(&nvmet_fc_tgtport_cnt); } module_init(nvmet_fc_init_module); module_exit(nvmet_fc_exit_module); MODULE_LICENSE("GPL v2");
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3037_0
crossvul-cpp_data_good_5035_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2011 Andres Mejia * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include <time.h> #include <limits.h> #ifdef HAVE_ZLIB_H #include <zlib.h> /* crc32 */ #endif #include "archive.h" #ifndef HAVE_ZLIB_H #include "archive_crc32.h" #endif #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_ppmd7_private.h" #include "archive_private.h" #include "archive_read_private.h" /* RAR signature, also known as the mark header */ #define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00" /* Header types */ #define MARK_HEAD 0x72 #define MAIN_HEAD 0x73 #define FILE_HEAD 0x74 #define COMM_HEAD 0x75 #define AV_HEAD 0x76 #define SUB_HEAD 0x77 #define PROTECT_HEAD 0x78 #define SIGN_HEAD 0x79 #define NEWSUB_HEAD 0x7a #define ENDARC_HEAD 0x7b /* Main Header Flags */ #define MHD_VOLUME 0x0001 #define MHD_COMMENT 0x0002 #define MHD_LOCK 0x0004 #define MHD_SOLID 0x0008 #define MHD_NEWNUMBERING 0x0010 #define MHD_AV 0x0020 #define MHD_PROTECT 0x0040 #define MHD_PASSWORD 0x0080 #define MHD_FIRSTVOLUME 0x0100 #define MHD_ENCRYPTVER 0x0200 /* Flags common to all headers */ #define HD_MARKDELETION 0x4000 #define HD_ADD_SIZE_PRESENT 0x8000 /* File Header Flags */ #define FHD_SPLIT_BEFORE 0x0001 #define FHD_SPLIT_AFTER 0x0002 #define FHD_PASSWORD 0x0004 #define FHD_COMMENT 0x0008 #define FHD_SOLID 0x0010 #define FHD_LARGE 0x0100 #define FHD_UNICODE 0x0200 #define FHD_SALT 0x0400 #define FHD_VERSION 0x0800 #define FHD_EXTTIME 0x1000 #define FHD_EXTFLAGS 0x2000 /* File dictionary sizes */ #define DICTIONARY_SIZE_64 0x00 #define DICTIONARY_SIZE_128 0x20 #define DICTIONARY_SIZE_256 0x40 #define DICTIONARY_SIZE_512 0x60 #define DICTIONARY_SIZE_1024 0x80 #define DICTIONARY_SIZE_2048 0xA0 #define DICTIONARY_SIZE_4096 0xC0 #define FILE_IS_DIRECTORY 0xE0 #define DICTIONARY_MASK FILE_IS_DIRECTORY /* OS Flags */ #define OS_MSDOS 0 #define OS_OS2 1 #define OS_WIN32 2 #define OS_UNIX 3 #define OS_MAC_OS 4 #define OS_BEOS 5 /* Compression Methods */ #define COMPRESS_METHOD_STORE 0x30 /* LZSS */ #define COMPRESS_METHOD_FASTEST 0x31 #define COMPRESS_METHOD_FAST 0x32 #define COMPRESS_METHOD_NORMAL 0x33 /* PPMd Variant H */ #define COMPRESS_METHOD_GOOD 0x34 #define COMPRESS_METHOD_BEST 0x35 #define CRC_POLYNOMIAL 0xEDB88320 #define NS_UNIT 10000000 #define DICTIONARY_MAX_SIZE 0x400000 #define MAINCODE_SIZE 299 #define OFFSETCODE_SIZE 60 #define LOWOFFSETCODE_SIZE 17 #define LENGTHCODE_SIZE 28 #define HUFFMAN_TABLE_SIZE \ MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE #define MAX_SYMBOL_LENGTH 0xF #define MAX_SYMBOLS 20 /* * Considering L1,L2 cache miss and a calling of write system-call, * the best size of the output buffer(uncompressed buffer) is 128K. * If the structure of extracting process is changed, this value * might be researched again. */ #define UNP_BUFFER_SIZE (128 * 1024) /* Define this here for non-Windows platforms */ #if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__)) #define FILE_ATTRIBUTE_DIRECTORY 0x10 #endif /* Fields common to all headers */ struct rar_header { char crc[2]; char type; char flags[2]; char size[2]; }; /* Fields common to all file headers */ struct rar_file_header { char pack_size[4]; char unp_size[4]; char host_os; char file_crc[4]; char file_time[4]; char unp_ver; char method; char name_size[2]; char file_attr[4]; }; struct huffman_tree_node { int branches[2]; }; struct huffman_table_entry { unsigned int length; int value; }; struct huffman_code { struct huffman_tree_node *tree; int numentries; int numallocatedentries; int minlength; int maxlength; int tablesize; struct huffman_table_entry *table; }; struct lzss { unsigned char *window; int mask; int64_t position; }; struct data_block_offsets { int64_t header_size; int64_t start_offset; int64_t end_offset; }; struct rar { /* Entries from main RAR header */ unsigned main_flags; unsigned long file_crc; char reserved1[2]; char reserved2[4]; char encryptver; /* File header entries */ char compression_method; unsigned file_flags; int64_t packed_size; int64_t unp_size; time_t mtime; long mnsec; mode_t mode; char *filename; char *filename_save; size_t filename_save_size; size_t filename_allocated; /* File header optional entries */ char salt[8]; time_t atime; long ansec; time_t ctime; long cnsec; time_t arctime; long arcnsec; /* Fields to help with tracking decompression of files. */ int64_t bytes_unconsumed; int64_t bytes_remaining; int64_t bytes_uncopied; int64_t offset; int64_t offset_outgoing; int64_t offset_seek; char valid; unsigned int unp_offset; unsigned int unp_buffer_size; unsigned char *unp_buffer; unsigned int dictionary_size; char start_new_block; char entry_eof; unsigned long crc_calculated; int found_first_header; char has_endarc_header; struct data_block_offsets *dbo; unsigned int cursor; unsigned int nodes; /* LZSS members */ struct huffman_code maincode; struct huffman_code offsetcode; struct huffman_code lowoffsetcode; struct huffman_code lengthcode; unsigned char lengthtable[HUFFMAN_TABLE_SIZE]; struct lzss lzss; char output_last_match; unsigned int lastlength; unsigned int lastoffset; unsigned int oldoffset[4]; unsigned int lastlowoffset; unsigned int numlowoffsetrepeats; int64_t filterstart; char start_new_table; /* PPMd Variant H members */ char ppmd_valid; char ppmd_eod; char is_ppmd_block; int ppmd_escape; CPpmd7 ppmd7_context; CPpmd7z_RangeDec range_dec; IByteIn bytein; /* * String conversion object. */ int init_default_conversion; struct archive_string_conv *sconv_default; struct archive_string_conv *opt_sconv; struct archive_string_conv *sconv_utf8; struct archive_string_conv *sconv_utf16be; /* * Bit stream reader. */ struct rar_br { #define CACHE_TYPE uint64_t #define CACHE_BITS (8 * sizeof(CACHE_TYPE)) /* Cache buffer. */ CACHE_TYPE cache_buffer; /* Indicates how many bits avail in cache_buffer. */ int cache_avail; ssize_t avail_in; const unsigned char *next_in; } br; /* * Custom field to denote that this archive contains encrypted entries */ int has_encrypted_entries; }; static int archive_read_support_format_rar_capabilities(struct archive_read *); static int archive_read_format_rar_has_encrypted_entries(struct archive_read *); static int archive_read_format_rar_bid(struct archive_read *, int); static int archive_read_format_rar_options(struct archive_read *, const char *, const char *); static int archive_read_format_rar_read_header(struct archive_read *, struct archive_entry *); static int archive_read_format_rar_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_rar_read_data_skip(struct archive_read *a); static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t, int); static int archive_read_format_rar_cleanup(struct archive_read *); /* Support functions */ static int read_header(struct archive_read *, struct archive_entry *, char); static time_t get_time(int); static int read_exttime(const char *, struct rar *, const char *); static int read_symlink_stored(struct archive_read *, struct archive_entry *, struct archive_string_conv *); static int read_data_stored(struct archive_read *, const void **, size_t *, int64_t *); static int read_data_compressed(struct archive_read *, const void **, size_t *, int64_t *); static int rar_br_preparation(struct archive_read *, struct rar_br *); static int parse_codes(struct archive_read *); static void free_codes(struct archive_read *); static int read_next_symbol(struct archive_read *, struct huffman_code *); static int create_code(struct archive_read *, struct huffman_code *, unsigned char *, int, char); static int add_value(struct archive_read *, struct huffman_code *, int, int, int); static int new_node(struct huffman_code *); static int make_table(struct archive_read *, struct huffman_code *); static int make_table_recurse(struct archive_read *, struct huffman_code *, int, struct huffman_table_entry *, int, int); static int64_t expand(struct archive_read *, int64_t); static int copy_from_lzss_window(struct archive_read *, const void **, int64_t, int); static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *); /* * Bit stream reader. */ /* Check that the cache buffer has enough bits. */ #define rar_br_has(br, n) ((br)->cache_avail >= n) /* Get compressed data by bit. */ #define rar_br_bits(br, n) \ (((uint32_t)((br)->cache_buffer >> \ ((br)->cache_avail - (n)))) & cache_masks[n]) #define rar_br_bits_forced(br, n) \ (((uint32_t)((br)->cache_buffer << \ ((n) - (br)->cache_avail))) & cache_masks[n]) /* Read ahead to make sure the cache buffer has enough compressed data we * will use. * True : completed, there is enough data in the cache buffer. * False : there is no data in the stream. */ #define rar_br_read_ahead(a, br, n) \ ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n))) /* Notify how many bits we consumed. */ #define rar_br_consume(br, n) ((br)->cache_avail -= (n)) #define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7) static const uint32_t cache_masks[] = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; /* * Shift away used bits in the cache data and fill it up with following bits. * Call this when cache buffer does not have enough bits you need. * * Returns 1 if the cache buffer is full. * Returns 0 if the cache buffer is not full; input buffer is empty. */ static int rar_br_fillup(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); int n = CACHE_BITS - br->cache_avail; for (;;) { switch (n >> 3) { case 8: if (br->avail_in >= 8) { br->cache_buffer = ((uint64_t)br->next_in[0]) << 56 | ((uint64_t)br->next_in[1]) << 48 | ((uint64_t)br->next_in[2]) << 40 | ((uint64_t)br->next_in[3]) << 32 | ((uint32_t)br->next_in[4]) << 24 | ((uint32_t)br->next_in[5]) << 16 | ((uint32_t)br->next_in[6]) << 8 | (uint32_t)br->next_in[7]; br->next_in += 8; br->avail_in -= 8; br->cache_avail += 8 * 8; rar->bytes_unconsumed += 8; rar->bytes_remaining -= 8; return (1); } break; case 7: if (br->avail_in >= 7) { br->cache_buffer = (br->cache_buffer << 56) | ((uint64_t)br->next_in[0]) << 48 | ((uint64_t)br->next_in[1]) << 40 | ((uint64_t)br->next_in[2]) << 32 | ((uint32_t)br->next_in[3]) << 24 | ((uint32_t)br->next_in[4]) << 16 | ((uint32_t)br->next_in[5]) << 8 | (uint32_t)br->next_in[6]; br->next_in += 7; br->avail_in -= 7; br->cache_avail += 7 * 8; rar->bytes_unconsumed += 7; rar->bytes_remaining -= 7; return (1); } break; case 6: if (br->avail_in >= 6) { br->cache_buffer = (br->cache_buffer << 48) | ((uint64_t)br->next_in[0]) << 40 | ((uint64_t)br->next_in[1]) << 32 | ((uint32_t)br->next_in[2]) << 24 | ((uint32_t)br->next_in[3]) << 16 | ((uint32_t)br->next_in[4]) << 8 | (uint32_t)br->next_in[5]; br->next_in += 6; br->avail_in -= 6; br->cache_avail += 6 * 8; rar->bytes_unconsumed += 6; rar->bytes_remaining -= 6; return (1); } break; case 0: /* We have enough compressed data in * the cache buffer.*/ return (1); default: break; } if (br->avail_in <= 0) { if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor * actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) return (0); if (br->avail_in == 0) return (0); } br->cache_buffer = (br->cache_buffer << 8) | *br->next_in++; br->avail_in--; br->cache_avail += 8; n -= 8; rar->bytes_unconsumed++; rar->bytes_remaining--; } } static int rar_br_preparation(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); if (rar->bytes_remaining > 0) { br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } if (br->cache_avail == 0) (void)rar_br_fillup(a, br); } return (ARCHIVE_OK); } /* Find last bit set */ static inline int rar_fls(unsigned int word) { word |= (word >> 1); word |= (word >> 2); word |= (word >> 4); word |= (word >> 8); word |= (word >> 16); return word - (word >> 1); } /* LZSS functions */ static inline int64_t lzss_position(struct lzss *lzss) { return lzss->position; } static inline int lzss_mask(struct lzss *lzss) { return lzss->mask; } static inline int lzss_size(struct lzss *lzss) { return lzss->mask + 1; } static inline int lzss_offset_for_position(struct lzss *lzss, int64_t pos) { return (int)(pos & lzss->mask); } static inline unsigned char * lzss_pointer_for_position(struct lzss *lzss, int64_t pos) { return &lzss->window[lzss_offset_for_position(lzss, pos)]; } static inline int lzss_current_offset(struct lzss *lzss) { return lzss_offset_for_position(lzss, lzss->position); } static inline uint8_t * lzss_current_pointer(struct lzss *lzss) { return lzss_pointer_for_position(lzss, lzss->position); } static inline void lzss_emit_literal(struct rar *rar, uint8_t literal) { *lzss_current_pointer(&rar->lzss) = literal; rar->lzss.position++; } static inline void lzss_emit_match(struct rar *rar, int offset, int length) { int dstoffs = lzss_current_offset(&rar->lzss); int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss); int l, li, remaining; unsigned char *d, *s; remaining = length; while (remaining > 0) { l = remaining; if (dstoffs > srcoffs) { if (l > lzss_size(&rar->lzss) - dstoffs) l = lzss_size(&rar->lzss) - dstoffs; } else { if (l > lzss_size(&rar->lzss) - srcoffs) l = lzss_size(&rar->lzss) - srcoffs; } d = &(rar->lzss.window[dstoffs]); s = &(rar->lzss.window[srcoffs]); if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs)) memcpy(d, s, l); else { for (li = 0; li < l; li++) d[li] = s[li]; } remaining -= l; dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss)); srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss)); } rar->lzss.position += length; } static void * ppmd_alloc(void *p, size_t size) { (void)p; return malloc(size); } static void ppmd_free(void *p, void *address) { (void)p; free(address); } static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free }; static Byte ppmd_read(void *p) { struct archive_read *a = ((IByteIn*)p)->a; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); Byte b; if (!rar_br_read_ahead(a, br, 8)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return 0; } b = rar_br_bits(br, 8); rar_br_consume(br, 8); return b; } int archive_read_support_format_rar(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct rar *rar; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_rar"); rar = (struct rar *)malloc(sizeof(*rar)); if (rar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data"); return (ARCHIVE_FATAL); } memset(rar, 0, sizeof(*rar)); /* * Until enough data has been read, we cannot tell about * any encrypted entries yet. */ rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; r = __archive_read_register_format(a, rar, "rar", archive_read_format_rar_bid, archive_read_format_rar_options, archive_read_format_rar_read_header, archive_read_format_rar_read_data, archive_read_format_rar_read_data_skip, archive_read_format_rar_seek_data, archive_read_format_rar_cleanup, archive_read_support_format_rar_capabilities, archive_read_format_rar_has_encrypted_entries); if (r != ARCHIVE_OK) free(rar); return (r); } static int archive_read_support_format_rar_capabilities(struct archive_read * a) { (void)a; /* UNUSED */ return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); } static int archive_read_format_rar_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct rar * rar = (struct rar *)_a->format->data; if (rar) { return rar->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } static int archive_read_format_rar_bid(struct archive_read *a, int best_bid) { const char *p; /* If there's already a bid > 30, we'll never win. */ if (best_bid > 30) return (-1); if ((p = __archive_read_ahead(a, 7, NULL)) == NULL) return (-1); if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { /* This is a PE file */ ssize_t offset = 0x10000; ssize_t window = 4096; ssize_t bytes_avail; while (offset + window <= (1024 * 128)) { const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) return (0); continue; } p = buff + offset; while (p + 7 < buff + bytes_avail) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); p += 0x10; } offset = p - buff; } } return (0); } static int skip_sfx(struct archive_read *a) { const void *h; const char *p, *q; size_t skip, total; ssize_t bytes, window; total = 0; window = 4096; while (total + window <= (1024 * 128)) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) goto fatal; continue; } if (bytes < 0x40) goto fatal; p = h; q = p + bytes; /* * Scan ahead until we find something that looks * like the RAR header. */ while (p + 7 < q) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) { skip = p - (const char *)h; __archive_read_consume(a, skip); return (ARCHIVE_OK); } p += 0x10; } skip = p - (const char *)h; __archive_read_consume(a, skip); total += skip; } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out RAR header"); return (ARCHIVE_FATAL); } static int archive_read_format_rar_options(struct archive_read *a, const char *key, const char *val) { struct rar *rar; int ret = ARCHIVE_FAILED; rar = (struct rar *)(a->format->data); if (strcmp(key, "hdrcharset") == 0) { if (val == NULL || val[0] == 0) archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "rar: hdrcharset option needs a character-set name"); else { rar->opt_sconv = archive_string_conversion_from_charset( &a->archive, val, 0); if (rar->opt_sconv != NULL) ret = ARCHIVE_OK; else ret = ARCHIVE_FATAL; } return (ret); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int archive_read_format_rar_read_header(struct archive_read *a, struct archive_entry *entry) { const void *h; const char *p; struct rar *rar; size_t skip; char head_type; int ret; unsigned flags; unsigned long crc32_expected; a->archive.archive_format = ARCHIVE_FORMAT_RAR; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "RAR"; rar = (struct rar *)(a->format->data); /* * It should be sufficient to call archive_read_next_header() for * a reader to determine if an entry is encrypted or not. If the * encryption of an entry is only detectable when calling * archive_read_data(), so be it. We'll do the same check there * as well. */ if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if * this fails. */ if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_EOF); p = h; if (rar->found_first_header == 0 && ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) { /* This is an executable ? Must be self-extracting... */ ret = skip_sfx(a); if (ret < ARCHIVE_WARN) return (ret); } rar->found_first_header = 1; while (1) { unsigned long crc32_val; if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; head_type = p[2]; switch(head_type) { case MARK_HEAD: if (memcmp(p, RAR_SIGNATURE, 7) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid marker header"); return (ARCHIVE_FATAL); } __archive_read_consume(a, 7); break; case MAIN_HEAD: rar->main_flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1)); memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1), sizeof(rar->reserved2)); if (rar->main_flags & MHD_ENCRYPTVER) { if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } rar->encryptver = *(p + 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)); } /* Main header is password encrytped, so we cannot read any file names or any other info about files from the header. */ if (rar->main_flags & MHD_PASSWORD) { archive_entry_set_is_metadata_encrypted(entry, 1); archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2); if ((crc32_val & 0xffff) != archive_le16dec(p)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } __archive_read_consume(a, skip); break; case FILE_HEAD: return read_header(a, entry, head_type); case COMM_HEAD: case AV_HEAD: case SUB_HEAD: case PROTECT_HEAD: case SIGN_HEAD: case ENDARC_HEAD: flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if (flags & HD_ADD_SIZE_PRESENT) { if (skip < 7 + 4) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; skip += archive_le32dec(p + 7); } /* Skip over the 2-byte CRC at the beginning of the header. */ crc32_expected = archive_le16dec(p); __archive_read_consume(a, 2); skip -= 2; /* Skim the entire header and compute the CRC. */ crc32_val = 0; while (skip > 0) { size_t to_read = skip; ssize_t did_read; if (to_read > 32 * 1024) { to_read = 32 * 1024; } if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) { return (ARCHIVE_FATAL); } p = h; crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read); __archive_read_consume(a, did_read); skip -= did_read; } if ((crc32_val & 0xffff) != crc32_expected) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } if (head_type == ENDARC_HEAD) return (ARCHIVE_EOF); break; case NEWSUB_HEAD: if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN) return ret; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file"); return (ARCHIVE_FATAL); } } } static int archive_read_format_rar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar = (struct rar *)(a->format->data); int ret; if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } *buff = NULL; if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { *size = 0; *offset = rar->offset; if (*offset < rar->unp_size) *offset = rar->unp_size; return (ARCHIVE_EOF); } switch (rar->compression_method) { case COMPRESS_METHOD_STORE: ret = read_data_stored(a, buff, size, offset); break; case COMPRESS_METHOD_FASTEST: case COMPRESS_METHOD_FAST: case COMPRESS_METHOD_NORMAL: case COMPRESS_METHOD_GOOD: case COMPRESS_METHOD_BEST: ret = read_data_compressed(a, buff, size, offset); if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported compression method for RAR file."); ret = ARCHIVE_FATAL; break; } return (ret); } static int archive_read_format_rar_read_data_skip(struct archive_read *a) { struct rar *rar; int64_t bytes_skipped; int ret; rar = (struct rar *)(a->format->data); if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } if (rar->bytes_remaining > 0) { bytes_skipped = __archive_read_consume(a, rar->bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); } /* Compressed data to skip must be read from each header in a multivolume * archive. */ if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) return ret; return archive_read_format_rar_read_data_skip(a); } return (ARCHIVE_OK); } static int64_t archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset, int whence) { int64_t client_offset, ret; unsigned int i; struct rar *rar = (struct rar *)(a->format->data); if (rar->compression_method == COMPRESS_METHOD_STORE) { /* Modify the offset for use with SEEK_SET */ switch (whence) { case SEEK_CUR: client_offset = rar->offset_seek; break; case SEEK_END: client_offset = rar->unp_size; break; case SEEK_SET: default: client_offset = 0; } client_offset += offset; if (client_offset < 0) { /* Can't seek past beginning of data block */ return -1; } else if (client_offset > rar->unp_size) { /* * Set the returned offset but only seek to the end of * the data block. */ rar->offset_seek = client_offset; client_offset = rar->unp_size; } client_offset += rar->dbo[0].start_offset; i = 0; while (i < rar->cursor) { i++; client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset; } if (rar->main_flags & MHD_VOLUME) { /* Find the appropriate offset among the multivolume archive */ while (1) { if (client_offset < rar->dbo[rar->cursor].start_offset && rar->file_flags & FHD_SPLIT_BEFORE) { /* Search backwards for the correct data block */ if (rar->cursor == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Attempt to seek past beginning of RAR data block"); return (ARCHIVE_FAILED); } rar->cursor--; client_offset -= rar->dbo[rar->cursor+1].start_offset - rar->dbo[rar->cursor].end_offset; if (client_offset < rar->dbo[rar->cursor].start_offset) continue; ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor].header_size, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } rar->cursor--; break; } else if (client_offset > rar->dbo[rar->cursor].end_offset && rar->file_flags & FHD_SPLIT_AFTER) { /* Search forward for the correct data block */ rar->cursor++; if (rar->cursor < rar->nodes && client_offset > rar->dbo[rar->cursor].end_offset) { client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } rar->cursor--; ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } break; } } ret = __archive_read_seek(a, client_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret; i = rar->cursor; while (i > 0) { i--; ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset; } ret -= rar->dbo[0].start_offset; /* Always restart reading the file after a seek */ __archive_reset_read_data(&a->archive); rar->bytes_unconsumed = 0; rar->offset = 0; /* * If a seek past the end of file was requested, return the requested * offset. */ if (ret == rar->unp_size && rar->offset_seek > rar->unp_size) return rar->offset_seek; /* Return the new offset */ rar->offset_seek = ret; return rar->offset_seek; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Seeking of compressed RAR files is unsupported"); } return (ARCHIVE_FAILED); } static int archive_read_format_rar_cleanup(struct archive_read *a) { struct rar *rar; rar = (struct rar *)(a->format->data); free_codes(a); free(rar->filename); free(rar->filename_save); free(rar->dbo); free(rar->unp_buffer); free(rar->lzss.window); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); free(rar); (a->format->data) = NULL; return (ARCHIVE_OK); } static int read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; filename[filename_size++] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; } static time_t get_time(int ttime) { struct tm tm; tm.tm_sec = 2 * (ttime & 0x1f); tm.tm_min = (ttime >> 5) & 0x3f; tm.tm_hour = (ttime >> 11) & 0x1f; tm.tm_mday = (ttime >> 16) & 0x1f; tm.tm_mon = ((ttime >> 21) & 0x0f) - 1; tm.tm_year = ((ttime >> 25) & 0x7f) + 80; tm.tm_isdst = -1; return mktime(&tm); } static int read_exttime(const char *p, struct rar *rar, const char *endp) { unsigned rmode, flags, rem, j, count; int ttime, i; struct tm *tm; time_t t; long nsec; if (p + 2 > endp) return (-1); flags = archive_le16dec(p); p += 2; for (i = 3; i >= 0; i--) { t = 0; if (i == 3) t = rar->mtime; rmode = flags >> i * 4; if (rmode & 8) { if (!t) { if (p + 4 > endp) return (-1); ttime = archive_le32dec(p); t = get_time(ttime); p += 4; } rem = 0; count = rmode & 3; if (p + count > endp) return (-1); for (j = 0; j < count; j++) { rem = ((*p) << 16) | (rem >> 8); p++; } tm = localtime(&t); nsec = tm->tm_sec + rem / NS_UNIT; if (rmode & 4) { tm->tm_sec++; t = mktime(tm); } if (i == 3) { rar->mtime = t; rar->mnsec = nsec; } else if (i == 2) { rar->ctime = t; rar->cnsec = nsec; } else if (i == 1) { rar->atime = t; rar->ansec = nsec; } else { rar->arctime = t; rar->arcnsec = nsec; } } } return (0); } static int read_symlink_stored(struct archive_read *a, struct archive_entry *entry, struct archive_string_conv *sconv) { const void *h; const char *p; struct rar *rar; int ret = (ARCHIVE_OK); rar = (struct rar *)(a->format->data); if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; if (archive_entry_copy_symlink_l(entry, p, (size_t)rar->packed_size, sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for link"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "link cannot be converted from %s to current locale.", archive_string_conversion_charset_name(sconv)); ret = (ARCHIVE_WARN); } __archive_read_consume(a, rar->packed_size); return ret; } static int read_data_stored(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; ssize_t bytes_avail; rar = (struct rar *)(a->format->data); if (rar->bytes_remaining == 0 && !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)) { *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } *buff = rar_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } *size = bytes_avail; *offset = rar->offset; rar->offset += bytes_avail; rar->offset_seek += bytes_avail; rar->bytes_remaining -= bytes_avail; rar->bytes_unconsumed = bytes_avail; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)bytes_avail); return (ARCHIVE_OK); } static int read_data_compressed(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; int64_t start, end, actualend; size_t bs; int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i; rar = (struct rar *)(a->format->data); do { if (!rar->valid) return (ARCHIVE_FATAL); if (rar->ppmd_eod || (rar->dictionary_size && rar->offset >= rar->unp_size)) { if (rar->unp_offset > 0) { /* * We have unprocessed extracted data. write it out. */ *buff = rar->unp_buffer; *size = rar->unp_offset; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); rar->unp_offset = 0; return (ARCHIVE_OK); } *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0) { if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; if (*buff != NULL) { rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return (ret); } continue; } if (!rar->br.next_in && (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN) return (ret); if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN))) return (ret); if (rar->is_ppmd_block) { if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } if(sym != rar->ppmd_escape) { lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } else { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } switch(code) { case 0: rar->start_new_table = 1; return read_data_compressed(a, buff, size, offset); case 2: rar->ppmd_eod = 1;/* End Of ppmd Data. */ continue; case 3: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); case 4: lzss_offset = 0; for (i = 2; i >= 0; i--) { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_offset |= code << (i * 8); } if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, lzss_offset + 2, length + 32); rar->bytes_uncopied += length + 32; break; case 5: if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, 1, length + 4); rar->bytes_uncopied += length + 4; break; default: lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } } } else { start = rar->offset; end = start + rar->dictionary_size; rar->filterstart = INT64_MAX; if ((actualend = expand(a, end)) < 0) return ((int)actualend); rar->bytes_uncopied = actualend - start; if (rar->bytes_uncopied == 0) { /* Broken RAR files cause this case. * NOTE: If this case were possible on a normal RAR file * we would find out where it was actually bad and * what we would do to solve it. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file"); return (ARCHIVE_FATAL); } } if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; /* * If *buff is NULL, it means unp_buffer is not full. * So we have to continue extracting a RAR file. */ } while (*buff == NULL); rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return ret; } static int parse_codes(struct archive_read *a) { int i, j, val, n, r; unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; unsigned int maxorder; struct huffman_code precode; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); free_codes(a); /* Skip to the next byte */ rar_br_consume_unalined_bits(br); /* PPMd block flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) { rar_br_consume(br, 1); if (!rar_br_read_ahead(a, br, 7)) goto truncated_data; ppmd_flags = rar_br_bits(br, 7); rar_br_consume(br, 7); /* Memory is allocated in MB */ if (ppmd_flags & 0x20) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; rar_br_consume(br, 8); } if (ppmd_flags & 0x40) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); rar_br_consume(br, 8); } else rar->ppmd_escape = 2; if (ppmd_flags & 0x20) { maxorder = (ppmd_flags & 0x1F) + 1; if(maxorder > 16) maxorder = 16 + (maxorder - 16) * 3; if (maxorder == 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } /* Make sure ppmd7_contest is freed before Ppmd7_Construct * because reading a broken file cause this abnormal sequence. */ __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->bytein.a = a; rar->bytein.Read = &ppmd_read; __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); rar->range_dec.Stream = &rar->bytein; __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); if (rar->dictionary_size == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid zero dictionary size"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, rar->dictionary_size, &g_szalloc)) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); rar->ppmd_valid = 1; } else { if (!rar->ppmd_valid) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid PPMd sequence"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } } } else { rar_br_consume(br, 1); /* Keep existing table flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if (!rar_br_bits(br, 1)) memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); rar_br_consume(br, 1); memset(&bitlengths, 0, sizeof(bitlengths)); for (i = 0; i < MAX_SYMBOLS;) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; bitlengths[i++] = rar_br_bits(br, 4); rar_br_consume(br, 4); if (bitlengths[i-1] == 0xF) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; zerocount = rar_br_bits(br, 4); rar_br_consume(br, 4); if (zerocount) { i--; for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) bitlengths[i++] = 0; } } } memset(&precode, 0, sizeof(precode)); r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) { free(precode.tree); free(precode.table); return (r); } for (i = 0; i < HUFFMAN_TABLE_SIZE;) { if ((val = read_next_symbol(a, &precode)) < 0) { free(precode.tree); free(precode.table); return (ARCHIVE_FATAL); } if (val < 16) { rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; i++; } else if (val < 18) { if (i == 0) { free(precode.tree); free(precode.table); archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file."); return (ARCHIVE_FATAL); } if(val == 16) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) { rar->lengthtable[i] = rar->lengthtable[i-1]; i++; } } else { if(val == 18) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) rar->lengthtable[i++] = 0; } } free(precode.tree); free(precode.table); r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lowoffsetcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lengthcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); } if (!rar->dictionary_size || !rar->lzss.window) { /* Seems as though dictionary sizes are not used. Even so, minimize * memory usage as much as possible. */ void *new_window; unsigned int new_size; if (rar->unp_size >= DICTIONARY_MAX_SIZE) new_size = DICTIONARY_MAX_SIZE; else new_size = rar_fls((unsigned int)rar->unp_size) << 1; new_window = realloc(rar->lzss.window, new_size); if (new_window == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } rar->lzss.window = (unsigned char *)new_window; rar->dictionary_size = new_size; memset(rar->lzss.window, 0, rar->dictionary_size); rar->lzss.mask = rar->dictionary_size - 1; } rar->start_new_table = 0; return (ARCHIVE_OK); truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); } static void free_codes(struct archive_read *a) { struct rar *rar = (struct rar *)(a->format->data); free(rar->maincode.tree); free(rar->offsetcode.tree); free(rar->lowoffsetcode.tree); free(rar->lengthcode.tree); free(rar->maincode.table); free(rar->offsetcode.table); free(rar->lowoffsetcode.table); free(rar->lengthcode.table); memset(&rar->maincode, 0, sizeof(rar->maincode)); memset(&rar->offsetcode, 0, sizeof(rar->offsetcode)); memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode)); memset(&rar->lengthcode, 0, sizeof(rar->lengthcode)); } static int read_next_symbol(struct archive_read *a, struct huffman_code *code) { unsigned char bit; unsigned int bits; int length, value, node; struct rar *rar; struct rar_br *br; if (!code->table) { if (make_table(a, code) != (ARCHIVE_OK)) return -1; } rar = (struct rar *)(a->format->data); br = &(rar->br); /* Look ahead (peek) at bits */ if (!rar_br_read_ahead(a, br, code->tablesize)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bits = rar_br_bits(br, code->tablesize); length = code->table[bits].length; value = code->table[bits].value; if (length < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } if (length <= code->tablesize) { /* Skip length bits */ rar_br_consume(br, length); return value; } /* Skip tablesize bits */ rar_br_consume(br, code->tablesize); node = value; while (!(code->tree[node].branches[0] == code->tree[node].branches[1])) { if (!rar_br_read_ahead(a, br, 1)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bit = rar_br_bits(br, 1); rar_br_consume(br, 1); if (code->tree[node].branches[bit] < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } node = code->tree[node].branches[bit]; } return code->tree[node].branches[0]; } static int create_code(struct archive_read *a, struct huffman_code *code, unsigned char *lengths, int numsymbols, char maxlength) { int i, j, codebits = 0, symbolsleft = numsymbols; code->numentries = 0; code->numallocatedentries = 0; if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->numentries = 1; code->minlength = INT_MAX; code->maxlength = INT_MIN; codebits = 0; for(i = 1; i <= maxlength; i++) { for(j = 0; j < numsymbols; j++) { if (lengths[j] != i) continue; if (add_value(a, code, j, codebits, i) != ARCHIVE_OK) return (ARCHIVE_FATAL); codebits++; if (--symbolsleft <= 0) { break; break; } } codebits <<= 1; } return (ARCHIVE_OK); } static int add_value(struct archive_read *a, struct huffman_code *code, int value, int codebits, int length) { int repeatpos, lastnode, bitpos, bit, repeatnode, nextnode; free(code->table); code->table = NULL; if(length > code->maxlength) code->maxlength = length; if(length < code->minlength) code->minlength = length; repeatpos = -1; if (repeatpos == 0 || (repeatpos >= 0 && (((codebits >> (repeatpos - 1)) & 3) == 0 || ((codebits >> (repeatpos - 1)) & 3) == 3))) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeat position"); return (ARCHIVE_FATAL); } lastnode = 0; for (bitpos = length - 1; bitpos >= 0; bitpos--) { bit = (codebits >> bitpos) & 1; /* Leaf node check */ if (code->tree[lastnode].branches[0] == code->tree[lastnode].branches[1]) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } if (bitpos == repeatpos) { /* Open branch check */ if (!(code->tree[lastnode].branches[bit] < 0)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeating code"); return (ARCHIVE_FATAL); } if ((repeatnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } if ((nextnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } /* Set branches */ code->tree[lastnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit^1] = nextnode; lastnode = nextnode; bitpos++; /* terminating bit already handled, skip it */ } else { /* Open branch check */ if (code->tree[lastnode].branches[bit] < 0) { if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->tree[lastnode].branches[bit] = code->numentries++; } /* set to branch */ lastnode = code->tree[lastnode].branches[bit]; } } if (!(code->tree[lastnode].branches[0] == -1 && code->tree[lastnode].branches[1] == -2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } /* Set leaf value */ code->tree[lastnode].branches[0] = value; code->tree[lastnode].branches[1] = value; return (ARCHIVE_OK); } static int new_node(struct huffman_code *code) { void *new_tree; if (code->numallocatedentries == code->numentries) { int new_num_entries = 256; if (code->numentries > 0) { new_num_entries = code->numentries * 2; } new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree)); if (new_tree == NULL) return (-1); code->tree = (struct huffman_tree_node *)new_tree; code->numallocatedentries = new_num_entries; } code->tree[code->numentries].branches[0] = -1; code->tree[code->numentries].branches[1] = -2; return 1; } static int make_table(struct archive_read *a, struct huffman_code *code) { if (code->maxlength < code->minlength || code->maxlength > 10) code->tablesize = 10; else code->tablesize = code->maxlength; code->table = (struct huffman_table_entry *)calloc(1, sizeof(*code->table) * ((size_t)1 << code->tablesize)); return make_table_recurse(a, code, 0, code->table, 0, code->tablesize); } static int make_table_recurse(struct archive_read *a, struct huffman_code *code, int node, struct huffman_table_entry *table, int depth, int maxdepth) { int currtablesize, i, ret = (ARCHIVE_OK); if (!code->tree) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Huffman tree was not created."); return (ARCHIVE_FATAL); } if (node < 0 || node >= code->numentries) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid location to Huffman tree specified."); return (ARCHIVE_FATAL); } currtablesize = 1 << (maxdepth - depth); if (code->tree[node].branches[0] == code->tree[node].branches[1]) { for(i = 0; i < currtablesize; i++) { table[i].length = depth; table[i].value = code->tree[node].branches[0]; } } else if (node < 0) { for(i = 0; i < currtablesize; i++) table[i].length = -1; } else { if(depth == maxdepth) { table[0].length = maxdepth + 1; table[0].value = node; } else { ret |= make_table_recurse(a, code, code->tree[node].branches[0], table, depth + 1, maxdepth); ret |= make_table_recurse(a, code, code->tree[node].branches[1], table + currtablesize / 2, depth + 1, maxdepth); } } return ret; } static int64_t expand(struct archive_read *a, int64_t end) { static const unsigned char lengthbases[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224 }; static const unsigned char lengthbits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; static const unsigned int offsetbases[] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040, 1048576, 1310720, 1572864, 1835008, 2097152, 2359296, 2621440, 2883584, 3145728, 3407872, 3670016, 3932160 }; static const unsigned char offsetbits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 }; static const unsigned char shortbases[] = { 0, 4, 8, 16, 32, 64, 128, 192 }; static const unsigned char shortbits[] = { 2, 2, 3, 4, 5, 6, 6, 6 }; int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol; unsigned char newfile; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); if (rar->filterstart < end) end = rar->filterstart; while (1) { if (rar->output_last_match && lzss_position(&rar->lzss) + rar->lastlength <= end) { lzss_emit_match(rar, rar->lastoffset, rar->lastlength); rar->output_last_match = 0; } if(rar->is_ppmd_block || rar->output_last_match || lzss_position(&rar->lzss) >= end) return lzss_position(&rar->lzss); if ((symbol = read_next_symbol(a, &rar->maincode)) < 0) return (ARCHIVE_FATAL); rar->output_last_match = 0; if (symbol < 256) { lzss_emit_literal(rar, symbol); continue; } else if (symbol == 256) { if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; newfile = !rar_br_bits(br, 1); rar_br_consume(br, 1); if(newfile) { rar->start_new_block = 1; if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; rar->start_new_table = rar_br_bits(br, 1); rar_br_consume(br, 1); return lzss_position(&rar->lzss); } else { if (parse_codes(a) != ARCHIVE_OK) return (ARCHIVE_FATAL); continue; } } else if(symbol==257) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); } else if(symbol==258) { if(rar->lastlength == 0) continue; offs = rar->lastoffset; len = rar->lastlength; } else if (symbol <= 262) { offsindex = symbol - 259; offs = rar->oldoffset[offsindex]; if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0) goto bad_data; if (lensymbol > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (lensymbol > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[lensymbol] + 2; if (lengthbits[lensymbol] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[lensymbol])) goto truncated_data; len += rar_br_bits(br, lengthbits[lensymbol]); rar_br_consume(br, lengthbits[lensymbol]); } for (i = offsindex; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else if(symbol<=270) { offs = shortbases[symbol-263] + 1; if(shortbits[symbol-263] > 0) { if (!rar_br_read_ahead(a, br, shortbits[symbol-263])) goto truncated_data; offs += rar_br_bits(br, shortbits[symbol-263]); rar_br_consume(br, shortbits[symbol-263]); } len = 2; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else { if (symbol-271 > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (symbol-271 > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[symbol-271]+3; if(lengthbits[symbol-271] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[symbol-271])) goto truncated_data; len += rar_br_bits(br, lengthbits[symbol-271]); rar_br_consume(br, lengthbits[symbol-271]); } if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0) goto bad_data; if (offssymbol > (int)(sizeof(offsetbases)/sizeof(offsetbases[0]))) goto bad_data; if (offssymbol > (int)(sizeof(offsetbits)/sizeof(offsetbits[0]))) goto bad_data; offs = offsetbases[offssymbol]+1; if(offsetbits[offssymbol] > 0) { if(offssymbol > 9) { if(offsetbits[offssymbol] > 4) { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4)) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4; rar_br_consume(br, offsetbits[offssymbol] - 4); } if(rar->numlowoffsetrepeats > 0) { rar->numlowoffsetrepeats--; offs += rar->lastlowoffset; } else { if ((lowoffsetsymbol = read_next_symbol(a, &rar->lowoffsetcode)) < 0) return (ARCHIVE_FATAL); if(lowoffsetsymbol == 16) { rar->numlowoffsetrepeats = 15; offs += rar->lastlowoffset; } else { offs += lowoffsetsymbol; rar->lastlowoffset = lowoffsetsymbol; } } } else { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol])) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol]); rar_br_consume(br, offsetbits[offssymbol]); } } if (offs >= 0x40000) len++; if (offs >= 0x2000) len++; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } rar->lastoffset = offs; rar->lastlength = len; rar->output_last_match = 1; } truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); bad_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } static int copy_from_lzss_window(struct archive_read *a, const void **buffer, int64_t startpos, int length) { int windowoffs, firstpart; struct rar *rar = (struct rar *)(a->format->data); if (!rar->unp_buffer) { if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } } windowoffs = lzss_offset_for_position(&rar->lzss, startpos); if(windowoffs + length <= lzss_size(&rar->lzss)) memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); else { firstpart = lzss_size(&rar->lzss) - windowoffs; if (firstpart < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } if (firstpart < length) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], firstpart); memcpy(&rar->unp_buffer[rar->unp_offset + firstpart], &rar->lzss.window[0], length - firstpart); } else memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } rar->unp_offset += length; if (rar->unp_offset >= rar->unp_buffer_size) *buffer = rar->unp_buffer; else *buffer = NULL; return (ARCHIVE_OK); } static const void * rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { struct rar *rar = (struct rar *)(a->format->data); const void *h = __archive_read_ahead(a, min, avail); int ret; if (avail) { if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) *avail = a->archive.read_data_requested; if (*avail > rar->bytes_remaining) *avail = (ssize_t)rar->bytes_remaining; if (*avail < 0) return NULL; else if (*avail == 0 && rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) return NULL; return rar_read_ahead(a, min, avail); } } return h; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5035_0
crossvul-cpp_data_bad_4945_1
/* (See Documentation/git-fast-import.txt for maintained documentation.) Format of STDIN stream: stream ::= cmd*; cmd ::= new_blob | new_commit | new_tag | reset_branch | checkpoint | progress ; new_blob ::= 'blob' lf mark? file_content; file_content ::= data; new_commit ::= 'commit' sp ref_str lf mark? ('author' (sp name)? sp '<' email '>' sp when lf)? 'committer' (sp name)? sp '<' email '>' sp when lf commit_msg ('from' sp commit-ish lf)? ('merge' sp commit-ish lf)* (file_change | ls)* lf?; commit_msg ::= data; ls ::= 'ls' sp '"' quoted(path) '"' lf; file_change ::= file_clr | file_del | file_rnm | file_cpy | file_obm | file_inm; file_clr ::= 'deleteall' lf; file_del ::= 'D' sp path_str lf; file_rnm ::= 'R' sp path_str sp path_str lf; file_cpy ::= 'C' sp path_str sp path_str lf; file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf; file_inm ::= 'M' sp mode sp 'inline' sp path_str lf data; note_obm ::= 'N' sp (hexsha1 | idnum) sp commit-ish lf; note_inm ::= 'N' sp 'inline' sp commit-ish lf data; new_tag ::= 'tag' sp tag_str lf 'from' sp commit-ish lf ('tagger' (sp name)? sp '<' email '>' sp when lf)? tag_msg; tag_msg ::= data; reset_branch ::= 'reset' sp ref_str lf ('from' sp commit-ish lf)? lf?; checkpoint ::= 'checkpoint' lf lf?; progress ::= 'progress' sp not_lf* lf lf?; # note: the first idnum in a stream should be 1 and subsequent # idnums should not have gaps between values as this will cause # the stream parser to reserve space for the gapped values. An # idnum can be updated in the future to a new object by issuing # a new mark directive with the old idnum. # mark ::= 'mark' sp idnum lf; data ::= (delimited_data | exact_data) lf?; # note: delim may be any string but must not contain lf. # data_line may contain any data but must not be exactly # delim. delimited_data ::= 'data' sp '<<' delim lf (data_line lf)* delim lf; # note: declen indicates the length of binary_data in bytes. # declen does not include the lf preceding the binary data. # exact_data ::= 'data' sp declen lf binary_data; # note: quoted strings are C-style quoting supporting \c for # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn # is the signed byte value in octal. Note that the only # characters which must actually be escaped to protect the # stream formatting is: \, " and LF. Otherwise these values # are UTF8. # commit-ish ::= (ref_str | hexsha1 | sha1exp_str | idnum); ref_str ::= ref; sha1exp_str ::= sha1exp; tag_str ::= tag; path_str ::= path | '"' quoted(path) '"' ; mode ::= '100644' | '644' | '100755' | '755' | '120000' ; declen ::= # unsigned 32 bit value, ascii base10 notation; bigint ::= # unsigned integer value, ascii base10 notation; binary_data ::= # file content, not interpreted; when ::= raw_when | rfc2822_when; raw_when ::= ts sp tz; rfc2822_when ::= # Valid RFC 2822 date and time; sp ::= # ASCII space character; lf ::= # ASCII newline (LF) character; # note: a colon (':') must precede the numerical value assigned to # an idnum. This is to distinguish it from a ref or tag name as # GIT does not permit ':' in ref or tag strings. # idnum ::= ':' bigint; path ::= # GIT style file path, e.g. "a/b/c"; ref ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT"; tag ::= # GIT tag name, e.g. "FIREFOX_1_5"; sha1exp ::= # Any valid GIT SHA1 expression; hexsha1 ::= # SHA1 in hexadecimal format; # note: name and email are UTF8 strings, however name must not # contain '<' or lf and email must not contain any of the # following: '<', '>', lf. # name ::= # valid GIT author/committer name; email ::= # valid GIT author/committer email; ts ::= # time since the epoch in seconds, ascii base10 notation; tz ::= # GIT style timezone; # note: comments, get-mark, ls-tree, and cat-blob requests may # appear anywhere in the input, except within a data command. Any # form of the data command always escapes the related input from # comment processing. # # In case it is not clear, the '#' that starts the comment # must be the first character on that line (an lf # preceded it). # get_mark ::= 'get-mark' sp idnum lf; cat_blob ::= 'cat-blob' sp (hexsha1 | idnum) lf; ls_tree ::= 'ls' sp (hexsha1 | idnum) sp path_str lf; comment ::= '#' not_lf* lf; not_lf ::= # Any byte that is not ASCII newline (LF); */ #include "builtin.h" #include "cache.h" #include "lockfile.h" #include "object.h" #include "blob.h" #include "tree.h" #include "commit.h" #include "delta.h" #include "pack.h" #include "refs.h" #include "csum-file.h" #include "quote.h" #include "exec_cmd.h" #include "dir.h" #define PACK_ID_BITS 16 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1) #define DEPTH_BITS 13 #define MAX_DEPTH ((1<<DEPTH_BITS)-1) /* * We abuse the setuid bit on directories to mean "do not delta". */ #define NO_DELTA S_ISUID struct object_entry { struct pack_idx_entry idx; struct object_entry *next; uint32_t type : TYPE_BITS, pack_id : PACK_ID_BITS, depth : DEPTH_BITS; }; struct object_entry_pool { struct object_entry_pool *next_pool; struct object_entry *next_free; struct object_entry *end; struct object_entry entries[FLEX_ARRAY]; /* more */ }; struct mark_set { union { struct object_entry *marked[1024]; struct mark_set *sets[1024]; } data; unsigned int shift; }; struct last_object { struct strbuf data; off_t offset; unsigned int depth; unsigned no_swap : 1; }; struct mem_pool { struct mem_pool *next_pool; char *next_free; char *end; uintmax_t space[FLEX_ARRAY]; /* more */ }; struct atom_str { struct atom_str *next_atom; unsigned short str_len; char str_dat[FLEX_ARRAY]; /* more */ }; struct tree_content; struct tree_entry { struct tree_content *tree; struct atom_str *name; struct tree_entry_ms { uint16_t mode; unsigned char sha1[20]; } versions[2]; }; struct tree_content { unsigned int entry_capacity; /* must match avail_tree_content */ unsigned int entry_count; unsigned int delta_depth; struct tree_entry *entries[FLEX_ARRAY]; /* more */ }; struct avail_tree_content { unsigned int entry_capacity; /* must match tree_content */ struct avail_tree_content *next_avail; }; struct branch { struct branch *table_next_branch; struct branch *active_next_branch; const char *name; struct tree_entry branch_tree; uintmax_t last_commit; uintmax_t num_notes; unsigned active : 1; unsigned delete : 1; unsigned pack_id : PACK_ID_BITS; unsigned char sha1[20]; }; struct tag { struct tag *next_tag; const char *name; unsigned int pack_id; unsigned char sha1[20]; }; struct hash_list { struct hash_list *next; unsigned char sha1[20]; }; typedef enum { WHENSPEC_RAW = 1, WHENSPEC_RFC2822, WHENSPEC_NOW } whenspec_type; struct recent_command { struct recent_command *prev; struct recent_command *next; char *buf; }; /* Configured limits on output */ static unsigned long max_depth = 10; static off_t max_packsize; static int force_update; static int pack_compression_level = Z_DEFAULT_COMPRESSION; static int pack_compression_seen; /* Stats and misc. counters */ static uintmax_t alloc_count; static uintmax_t marks_set_count; static uintmax_t object_count_by_type[1 << TYPE_BITS]; static uintmax_t duplicate_count_by_type[1 << TYPE_BITS]; static uintmax_t delta_count_by_type[1 << TYPE_BITS]; static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS]; static unsigned long object_count; static unsigned long branch_count; static unsigned long branch_load_count; static int failure; static FILE *pack_edges; static unsigned int show_stats = 1; static int global_argc; static char **global_argv; /* Memory pools */ static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool); static size_t total_allocd; static struct mem_pool *mem_pool; /* Atom management */ static unsigned int atom_table_sz = 4451; static unsigned int atom_cnt; static struct atom_str **atom_table; /* The .pack file being generated */ static struct pack_idx_option pack_idx_opts; static unsigned int pack_id; static struct sha1file *pack_file; static struct packed_git *pack_data; static struct packed_git **all_packs; static off_t pack_size; /* Table of objects we've written. */ static unsigned int object_entry_alloc = 5000; static struct object_entry_pool *blocks; static struct object_entry *object_table[1 << 16]; static struct mark_set *marks; static const char *export_marks_file; static const char *import_marks_file; static int import_marks_file_from_stream; static int import_marks_file_ignore_missing; static int relative_marks_paths; /* Our last blob */ static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 }; /* Tree management */ static unsigned int tree_entry_alloc = 1000; static void *avail_tree_entry; static unsigned int avail_tree_table_sz = 100; static struct avail_tree_content **avail_tree_table; static struct strbuf old_tree = STRBUF_INIT; static struct strbuf new_tree = STRBUF_INIT; /* Branch data */ static unsigned long max_active_branches = 5; static unsigned long cur_active_branches; static unsigned long branch_table_sz = 1039; static struct branch **branch_table; static struct branch *active_branches; /* Tag data */ static struct tag *first_tag; static struct tag *last_tag; /* Input stream parsing */ static whenspec_type whenspec = WHENSPEC_RAW; static struct strbuf command_buf = STRBUF_INIT; static int unread_command_buf; static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL}; static struct recent_command *cmd_tail = &cmd_hist; static struct recent_command *rc_free; static unsigned int cmd_save = 100; static uintmax_t next_mark; static struct strbuf new_data = STRBUF_INIT; static int seen_data_command; static int require_explicit_termination; /* Signal handling */ static volatile sig_atomic_t checkpoint_requested; /* Where to write output of cat-blob commands */ static int cat_blob_fd = STDOUT_FILENO; static void parse_argv(void); static void parse_get_mark(const char *p); static void parse_cat_blob(const char *p); static void parse_ls(const char *p, struct branch *b); static void write_branch_report(FILE *rpt, struct branch *b) { fprintf(rpt, "%s:\n", b->name); fprintf(rpt, " status :"); if (b->active) fputs(" active", rpt); if (b->branch_tree.tree) fputs(" loaded", rpt); if (is_null_sha1(b->branch_tree.versions[1].sha1)) fputs(" dirty", rpt); fputc('\n', rpt); fprintf(rpt, " tip commit : %s\n", sha1_to_hex(b->sha1)); fprintf(rpt, " old tree : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1)); fprintf(rpt, " cur tree : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1)); fprintf(rpt, " commit clock: %" PRIuMAX "\n", b->last_commit); fputs(" last pack : ", rpt); if (b->pack_id < MAX_PACK_ID) fprintf(rpt, "%u", b->pack_id); fputc('\n', rpt); fputc('\n', rpt); } static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *); static void write_crash_report(const char *err) { char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid()); FILE *rpt = fopen(loc, "w"); struct branch *b; unsigned long lu; struct recent_command *rc; if (!rpt) { error("can't write crash report %s: %s", loc, strerror(errno)); free(loc); return; } fprintf(stderr, "fast-import: dumping crash report to %s\n", loc); fprintf(rpt, "fast-import crash report:\n"); fprintf(rpt, " fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid()); fprintf(rpt, " parent process : %"PRIuMAX"\n", (uintmax_t) getppid()); fprintf(rpt, " at %s\n", show_date(time(NULL), 0, DATE_MODE(LOCAL))); fputc('\n', rpt); fputs("fatal: ", rpt); fputs(err, rpt); fputc('\n', rpt); fputc('\n', rpt); fputs("Most Recent Commands Before Crash\n", rpt); fputs("---------------------------------\n", rpt); for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) { if (rc->next == &cmd_hist) fputs("* ", rpt); else fputs(" ", rpt); fputs(rc->buf, rpt); fputc('\n', rpt); } fputc('\n', rpt); fputs("Active Branch LRU\n", rpt); fputs("-----------------\n", rpt); fprintf(rpt, " active_branches = %lu cur, %lu max\n", cur_active_branches, max_active_branches); fputc('\n', rpt); fputs(" pos clock name\n", rpt); fputs(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt); for (b = active_branches, lu = 0; b; b = b->active_next_branch) fprintf(rpt, " %2lu) %6" PRIuMAX" %s\n", ++lu, b->last_commit, b->name); fputc('\n', rpt); fputs("Inactive Branches\n", rpt); fputs("-----------------\n", rpt); for (lu = 0; lu < branch_table_sz; lu++) { for (b = branch_table[lu]; b; b = b->table_next_branch) write_branch_report(rpt, b); } if (first_tag) { struct tag *tg; fputc('\n', rpt); fputs("Annotated Tags\n", rpt); fputs("--------------\n", rpt); for (tg = first_tag; tg; tg = tg->next_tag) { fputs(sha1_to_hex(tg->sha1), rpt); fputc(' ', rpt); fputs(tg->name, rpt); fputc('\n', rpt); } } fputc('\n', rpt); fputs("Marks\n", rpt); fputs("-----\n", rpt); if (export_marks_file) fprintf(rpt, " exported to %s\n", export_marks_file); else dump_marks_helper(rpt, 0, marks); fputc('\n', rpt); fputs("-------------------\n", rpt); fputs("END OF CRASH REPORT\n", rpt); fclose(rpt); free(loc); } static void end_packfile(void); static void unkeep_all_packs(void); static void dump_marks(void); static NORETURN void die_nicely(const char *err, va_list params) { static int zombie; char message[2 * PATH_MAX]; vsnprintf(message, sizeof(message), err, params); fputs("fatal: ", stderr); fputs(message, stderr); fputc('\n', stderr); if (!zombie) { zombie = 1; write_crash_report(message); end_packfile(); unkeep_all_packs(); dump_marks(); } exit(128); } #ifndef SIGUSR1 /* Windows, for example */ static void set_checkpoint_signal(void) { } #else static void checkpoint_signal(int signo) { checkpoint_requested = 1; } static void set_checkpoint_signal(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = checkpoint_signal; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(SIGUSR1, &sa, NULL); } #endif static void alloc_objects(unsigned int cnt) { struct object_entry_pool *b; b = xmalloc(sizeof(struct object_entry_pool) + cnt * sizeof(struct object_entry)); b->next_pool = blocks; b->next_free = b->entries; b->end = b->entries + cnt; blocks = b; alloc_count += cnt; } static struct object_entry *new_object(unsigned char *sha1) { struct object_entry *e; if (blocks->next_free == blocks->end) alloc_objects(object_entry_alloc); e = blocks->next_free++; hashcpy(e->idx.sha1, sha1); return e; } static struct object_entry *find_object(unsigned char *sha1) { unsigned int h = sha1[0] << 8 | sha1[1]; struct object_entry *e; for (e = object_table[h]; e; e = e->next) if (!hashcmp(sha1, e->idx.sha1)) return e; return NULL; } static struct object_entry *insert_object(unsigned char *sha1) { unsigned int h = sha1[0] << 8 | sha1[1]; struct object_entry *e = object_table[h]; while (e) { if (!hashcmp(sha1, e->idx.sha1)) return e; e = e->next; } e = new_object(sha1); e->next = object_table[h]; e->idx.offset = 0; object_table[h] = e; return e; } static unsigned int hc_str(const char *s, size_t len) { unsigned int r = 0; while (len-- > 0) r = r * 31 + *s++; return r; } static void *pool_alloc(size_t len) { struct mem_pool *p; void *r; /* round up to a 'uintmax_t' alignment */ if (len & (sizeof(uintmax_t) - 1)) len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1)); for (p = mem_pool; p; p = p->next_pool) if ((p->end - p->next_free >= len)) break; if (!p) { if (len >= (mem_pool_alloc/2)) { total_allocd += len; return xmalloc(len); } total_allocd += sizeof(struct mem_pool) + mem_pool_alloc; p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc); p->next_pool = mem_pool; p->next_free = (char *) p->space; p->end = p->next_free + mem_pool_alloc; mem_pool = p; } r = p->next_free; p->next_free += len; return r; } static void *pool_calloc(size_t count, size_t size) { size_t len = count * size; void *r = pool_alloc(len); memset(r, 0, len); return r; } static char *pool_strdup(const char *s) { char *r = pool_alloc(strlen(s) + 1); strcpy(r, s); return r; } static void insert_mark(uintmax_t idnum, struct object_entry *oe) { struct mark_set *s = marks; while ((idnum >> s->shift) >= 1024) { s = pool_calloc(1, sizeof(struct mark_set)); s->shift = marks->shift + 10; s->data.sets[0] = marks; marks = s; } while (s->shift) { uintmax_t i = idnum >> s->shift; idnum -= i << s->shift; if (!s->data.sets[i]) { s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set)); s->data.sets[i]->shift = s->shift - 10; } s = s->data.sets[i]; } if (!s->data.marked[idnum]) marks_set_count++; s->data.marked[idnum] = oe; } static struct object_entry *find_mark(uintmax_t idnum) { uintmax_t orig_idnum = idnum; struct mark_set *s = marks; struct object_entry *oe = NULL; if ((idnum >> s->shift) < 1024) { while (s && s->shift) { uintmax_t i = idnum >> s->shift; idnum -= i << s->shift; s = s->data.sets[i]; } if (s) oe = s->data.marked[idnum]; } if (!oe) die("mark :%" PRIuMAX " not declared", orig_idnum); return oe; } static struct atom_str *to_atom(const char *s, unsigned short len) { unsigned int hc = hc_str(s, len) % atom_table_sz; struct atom_str *c; for (c = atom_table[hc]; c; c = c->next_atom) if (c->str_len == len && !strncmp(s, c->str_dat, len)) return c; c = pool_alloc(sizeof(struct atom_str) + len + 1); c->str_len = len; strncpy(c->str_dat, s, len); c->str_dat[len] = 0; c->next_atom = atom_table[hc]; atom_table[hc] = c; atom_cnt++; return c; } static struct branch *lookup_branch(const char *name) { unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz; struct branch *b; for (b = branch_table[hc]; b; b = b->table_next_branch) if (!strcmp(name, b->name)) return b; return NULL; } static struct branch *new_branch(const char *name) { unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz; struct branch *b = lookup_branch(name); if (b) die("Invalid attempt to create duplicate branch: %s", name); if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL)) die("Branch name doesn't conform to GIT standards: %s", name); b = pool_calloc(1, sizeof(struct branch)); b->name = pool_strdup(name); b->table_next_branch = branch_table[hc]; b->branch_tree.versions[0].mode = S_IFDIR; b->branch_tree.versions[1].mode = S_IFDIR; b->num_notes = 0; b->active = 0; b->pack_id = MAX_PACK_ID; branch_table[hc] = b; branch_count++; return b; } static unsigned int hc_entries(unsigned int cnt) { cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8; return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1; } static struct tree_content *new_tree_content(unsigned int cnt) { struct avail_tree_content *f, *l = NULL; struct tree_content *t; unsigned int hc = hc_entries(cnt); for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail) if (f->entry_capacity >= cnt) break; if (f) { if (l) l->next_avail = f->next_avail; else avail_tree_table[hc] = f->next_avail; } else { cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt; f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt); f->entry_capacity = cnt; } t = (struct tree_content*)f; t->entry_count = 0; t->delta_depth = 0; return t; } static void release_tree_entry(struct tree_entry *e); static void release_tree_content(struct tree_content *t) { struct avail_tree_content *f = (struct avail_tree_content*)t; unsigned int hc = hc_entries(f->entry_capacity); f->next_avail = avail_tree_table[hc]; avail_tree_table[hc] = f; } static void release_tree_content_recursive(struct tree_content *t) { unsigned int i; for (i = 0; i < t->entry_count; i++) release_tree_entry(t->entries[i]); release_tree_content(t); } static struct tree_content *grow_tree_content( struct tree_content *t, int amt) { struct tree_content *r = new_tree_content(t->entry_count + amt); r->entry_count = t->entry_count; r->delta_depth = t->delta_depth; memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0])); release_tree_content(t); return r; } static struct tree_entry *new_tree_entry(void) { struct tree_entry *e; if (!avail_tree_entry) { unsigned int n = tree_entry_alloc; total_allocd += n * sizeof(struct tree_entry); avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry)); while (n-- > 1) { *((void**)e) = e + 1; e++; } *((void**)e) = NULL; } e = avail_tree_entry; avail_tree_entry = *((void**)e); return e; } static void release_tree_entry(struct tree_entry *e) { if (e->tree) release_tree_content_recursive(e->tree); *((void**)e) = avail_tree_entry; avail_tree_entry = e; } static struct tree_content *dup_tree_content(struct tree_content *s) { struct tree_content *d; struct tree_entry *a, *b; unsigned int i; if (!s) return NULL; d = new_tree_content(s->entry_count); for (i = 0; i < s->entry_count; i++) { a = s->entries[i]; b = new_tree_entry(); memcpy(b, a, sizeof(*a)); if (a->tree && is_null_sha1(b->versions[1].sha1)) b->tree = dup_tree_content(a->tree); else b->tree = NULL; d->entries[i] = b; } d->entry_count = s->entry_count; d->delta_depth = s->delta_depth; return d; } static void start_packfile(void) { static char tmp_file[PATH_MAX]; struct packed_git *p; int namelen; struct pack_header hdr; int pack_fd; pack_fd = odb_mkstemp(tmp_file, sizeof(tmp_file), "pack/tmp_pack_XXXXXX"); namelen = strlen(tmp_file) + 2; p = xcalloc(1, sizeof(*p) + namelen); xsnprintf(p->pack_name, namelen, "%s", tmp_file); p->pack_fd = pack_fd; p->do_not_close = 1; pack_file = sha1fd(pack_fd, p->pack_name); hdr.hdr_signature = htonl(PACK_SIGNATURE); hdr.hdr_version = htonl(2); hdr.hdr_entries = 0; sha1write(pack_file, &hdr, sizeof(hdr)); pack_data = p; pack_size = sizeof(hdr); object_count = 0; REALLOC_ARRAY(all_packs, pack_id + 1); all_packs[pack_id] = p; } static const char *create_index(void) { const char *tmpfile; struct pack_idx_entry **idx, **c, **last; struct object_entry *e; struct object_entry_pool *o; /* Build the table of object IDs. */ idx = xmalloc(object_count * sizeof(*idx)); c = idx; for (o = blocks; o; o = o->next_pool) for (e = o->next_free; e-- != o->entries;) if (pack_id == e->pack_id) *c++ = &e->idx; last = idx + object_count; if (c != last) die("internal consistency error creating the index"); tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1); free(idx); return tmpfile; } static char *keep_pack(const char *curr_index_name) { static char name[PATH_MAX]; static const char *keep_msg = "fast-import"; int keep_fd; keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1); if (keep_fd < 0) die_errno("cannot create keep file"); write_or_die(keep_fd, keep_msg, strlen(keep_msg)); if (close(keep_fd)) die_errno("failed to write keep file"); snprintf(name, sizeof(name), "%s/pack/pack-%s.pack", get_object_directory(), sha1_to_hex(pack_data->sha1)); if (finalize_object_file(pack_data->pack_name, name)) die("cannot store pack file"); snprintf(name, sizeof(name), "%s/pack/pack-%s.idx", get_object_directory(), sha1_to_hex(pack_data->sha1)); if (finalize_object_file(curr_index_name, name)) die("cannot store index file"); free((void *)curr_index_name); return name; } static void unkeep_all_packs(void) { static char name[PATH_MAX]; int k; for (k = 0; k < pack_id; k++) { struct packed_git *p = all_packs[k]; snprintf(name, sizeof(name), "%s/pack/pack-%s.keep", get_object_directory(), sha1_to_hex(p->sha1)); unlink_or_warn(name); } } static void end_packfile(void) { static int running; if (running || !pack_data) return; running = 1; clear_delta_base_cache(); if (object_count) { struct packed_git *new_p; unsigned char cur_pack_sha1[20]; char *idx_name; int i; struct branch *b; struct tag *t; close_pack_windows(pack_data); sha1close(pack_file, cur_pack_sha1, 0); fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1, pack_data->pack_name, object_count, cur_pack_sha1, pack_size); close(pack_data->pack_fd); idx_name = keep_pack(create_index()); /* Register the packfile with core git's machinery. */ new_p = add_packed_git(idx_name, strlen(idx_name), 1); if (!new_p) die("core git rejected index %s", idx_name); all_packs[pack_id] = new_p; install_packed_git(new_p); /* Print the boundary */ if (pack_edges) { fprintf(pack_edges, "%s:", new_p->pack_name); for (i = 0; i < branch_table_sz; i++) { for (b = branch_table[i]; b; b = b->table_next_branch) { if (b->pack_id == pack_id) fprintf(pack_edges, " %s", sha1_to_hex(b->sha1)); } } for (t = first_tag; t; t = t->next_tag) { if (t->pack_id == pack_id) fprintf(pack_edges, " %s", sha1_to_hex(t->sha1)); } fputc('\n', pack_edges); fflush(pack_edges); } pack_id++; } else { close(pack_data->pack_fd); unlink_or_warn(pack_data->pack_name); } free(pack_data); pack_data = NULL; running = 0; /* We can't carry a delta across packfiles. */ strbuf_release(&last_blob.data); last_blob.offset = 0; last_blob.depth = 0; } static void cycle_packfile(void) { end_packfile(); start_packfile(); } static int store_object( enum object_type type, struct strbuf *dat, struct last_object *last, unsigned char *sha1out, uintmax_t mark) { void *out, *delta; struct object_entry *e; unsigned char hdr[96]; unsigned char sha1[20]; unsigned long hdrlen, deltalen; git_SHA_CTX c; git_zstream s; hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu", typename(type), (unsigned long)dat->len) + 1; git_SHA1_Init(&c); git_SHA1_Update(&c, hdr, hdrlen); git_SHA1_Update(&c, dat->buf, dat->len); git_SHA1_Final(sha1, &c); if (sha1out) hashcpy(sha1out, sha1); e = insert_object(sha1); if (mark) insert_mark(mark, e); if (e->idx.offset) { duplicate_count_by_type[type]++; return 1; } else if (find_sha1_pack(sha1, packed_git)) { e->type = type; e->pack_id = MAX_PACK_ID; e->idx.offset = 1; /* just not zero! */ duplicate_count_by_type[type]++; return 1; } if (last && last->data.buf && last->depth < max_depth && dat->len > 20) { delta_count_attempts_by_type[type]++; delta = diff_delta(last->data.buf, last->data.len, dat->buf, dat->len, &deltalen, dat->len - 20); } else delta = NULL; git_deflate_init(&s, pack_compression_level); if (delta) { s.next_in = delta; s.avail_in = deltalen; } else { s.next_in = (void *)dat->buf; s.avail_in = dat->len; } s.avail_out = git_deflate_bound(&s, s.avail_in); s.next_out = out = xmalloc(s.avail_out); while (git_deflate(&s, Z_FINISH) == Z_OK) ; /* nothing */ git_deflate_end(&s); /* Determine if we should auto-checkpoint. */ if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize) || (pack_size + 60 + s.total_out) < pack_size) { /* This new object needs to *not* have the current pack_id. */ e->pack_id = pack_id + 1; cycle_packfile(); /* We cannot carry a delta into the new pack. */ if (delta) { free(delta); delta = NULL; git_deflate_init(&s, pack_compression_level); s.next_in = (void *)dat->buf; s.avail_in = dat->len; s.avail_out = git_deflate_bound(&s, s.avail_in); s.next_out = out = xrealloc(out, s.avail_out); while (git_deflate(&s, Z_FINISH) == Z_OK) ; /* nothing */ git_deflate_end(&s); } } e->type = type; e->pack_id = pack_id; e->idx.offset = pack_size; object_count++; object_count_by_type[type]++; crc32_begin(pack_file); if (delta) { off_t ofs = e->idx.offset - last->offset; unsigned pos = sizeof(hdr) - 1; delta_count_by_type[type]++; e->depth = last->depth + 1; hdrlen = encode_in_pack_object_header(OBJ_OFS_DELTA, deltalen, hdr); sha1write(pack_file, hdr, hdrlen); pack_size += hdrlen; hdr[pos] = ofs & 127; while (ofs >>= 7) hdr[--pos] = 128 | (--ofs & 127); sha1write(pack_file, hdr + pos, sizeof(hdr) - pos); pack_size += sizeof(hdr) - pos; } else { e->depth = 0; hdrlen = encode_in_pack_object_header(type, dat->len, hdr); sha1write(pack_file, hdr, hdrlen); pack_size += hdrlen; } sha1write(pack_file, out, s.total_out); pack_size += s.total_out; e->idx.crc32 = crc32_end(pack_file); free(out); free(delta); if (last) { if (last->no_swap) { last->data = *dat; } else { strbuf_swap(&last->data, dat); } last->offset = e->idx.offset; last->depth = e->depth; } return 0; } static void truncate_pack(struct sha1file_checkpoint *checkpoint) { if (sha1file_truncate(pack_file, checkpoint)) die_errno("cannot truncate pack to skip duplicate"); pack_size = checkpoint->offset; } static void stream_blob(uintmax_t len, unsigned char *sha1out, uintmax_t mark) { size_t in_sz = 64 * 1024, out_sz = 64 * 1024; unsigned char *in_buf = xmalloc(in_sz); unsigned char *out_buf = xmalloc(out_sz); struct object_entry *e; unsigned char sha1[20]; unsigned long hdrlen; off_t offset; git_SHA_CTX c; git_zstream s; struct sha1file_checkpoint checkpoint; int status = Z_OK; /* Determine if we should auto-checkpoint. */ if ((max_packsize && (pack_size + 60 + len) > max_packsize) || (pack_size + 60 + len) < pack_size) cycle_packfile(); sha1file_checkpoint(pack_file, &checkpoint); offset = checkpoint.offset; hdrlen = snprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1; if (out_sz <= hdrlen) die("impossibly large object header"); git_SHA1_Init(&c); git_SHA1_Update(&c, out_buf, hdrlen); crc32_begin(pack_file); git_deflate_init(&s, pack_compression_level); hdrlen = encode_in_pack_object_header(OBJ_BLOB, len, out_buf); if (out_sz <= hdrlen) die("impossibly large object header"); s.next_out = out_buf + hdrlen; s.avail_out = out_sz - hdrlen; while (status != Z_STREAM_END) { if (0 < len && !s.avail_in) { size_t cnt = in_sz < len ? in_sz : (size_t)len; size_t n = fread(in_buf, 1, cnt, stdin); if (!n && feof(stdin)) die("EOF in data (%" PRIuMAX " bytes remaining)", len); git_SHA1_Update(&c, in_buf, n); s.next_in = in_buf; s.avail_in = n; len -= n; } status = git_deflate(&s, len ? 0 : Z_FINISH); if (!s.avail_out || status == Z_STREAM_END) { size_t n = s.next_out - out_buf; sha1write(pack_file, out_buf, n); pack_size += n; s.next_out = out_buf; s.avail_out = out_sz; } switch (status) { case Z_OK: case Z_BUF_ERROR: case Z_STREAM_END: continue; default: die("unexpected deflate failure: %d", status); } } git_deflate_end(&s); git_SHA1_Final(sha1, &c); if (sha1out) hashcpy(sha1out, sha1); e = insert_object(sha1); if (mark) insert_mark(mark, e); if (e->idx.offset) { duplicate_count_by_type[OBJ_BLOB]++; truncate_pack(&checkpoint); } else if (find_sha1_pack(sha1, packed_git)) { e->type = OBJ_BLOB; e->pack_id = MAX_PACK_ID; e->idx.offset = 1; /* just not zero! */ duplicate_count_by_type[OBJ_BLOB]++; truncate_pack(&checkpoint); } else { e->depth = 0; e->type = OBJ_BLOB; e->pack_id = pack_id; e->idx.offset = offset; e->idx.crc32 = crc32_end(pack_file); object_count++; object_count_by_type[OBJ_BLOB]++; } free(in_buf); free(out_buf); } /* All calls must be guarded by find_object() or find_mark() to * ensure the 'struct object_entry' passed was written by this * process instance. We unpack the entry by the offset, avoiding * the need for the corresponding .idx file. This unpacking rule * works because we only use OBJ_REF_DELTA within the packfiles * created by fast-import. * * oe must not be NULL. Such an oe usually comes from giving * an unknown SHA-1 to find_object() or an undefined mark to * find_mark(). Callers must test for this condition and use * the standard read_sha1_file() when it happens. * * oe->pack_id must not be MAX_PACK_ID. Such an oe is usually from * find_mark(), where the mark was reloaded from an existing marks * file and is referencing an object that this fast-import process * instance did not write out to a packfile. Callers must test for * this condition and use read_sha1_file() instead. */ static void *gfi_unpack_entry( struct object_entry *oe, unsigned long *sizep) { enum object_type type; struct packed_git *p = all_packs[oe->pack_id]; if (p == pack_data && p->pack_size < (pack_size + 20)) { /* The object is stored in the packfile we are writing to * and we have modified it since the last time we scanned * back to read a previously written object. If an old * window covered [p->pack_size, p->pack_size + 20) its * data is stale and is not valid. Closing all windows * and updating the packfile length ensures we can read * the newly written data. */ close_pack_windows(p); sha1flush(pack_file); /* We have to offer 20 bytes additional on the end of * the packfile as the core unpacker code assumes the * footer is present at the file end and must promise * at least 20 bytes within any window it maps. But * we don't actually create the footer here. */ p->pack_size = pack_size + 20; } return unpack_entry(p, oe->idx.offset, &type, sizep); } static const char *get_mode(const char *str, uint16_t *modep) { unsigned char c; uint16_t mode = 0; while ((c = *str++) != ' ') { if (c < '0' || c > '7') return NULL; mode = (mode << 3) + (c - '0'); } *modep = mode; return str; } static void load_tree(struct tree_entry *root) { unsigned char *sha1 = root->versions[1].sha1; struct object_entry *myoe; struct tree_content *t; unsigned long size; char *buf; const char *c; root->tree = t = new_tree_content(8); if (is_null_sha1(sha1)) return; myoe = find_object(sha1); if (myoe && myoe->pack_id != MAX_PACK_ID) { if (myoe->type != OBJ_TREE) die("Not a tree: %s", sha1_to_hex(sha1)); t->delta_depth = myoe->depth; buf = gfi_unpack_entry(myoe, &size); if (!buf) die("Can't load tree %s", sha1_to_hex(sha1)); } else { enum object_type type; buf = read_sha1_file(sha1, &type, &size); if (!buf || type != OBJ_TREE) die("Can't load tree %s", sha1_to_hex(sha1)); } c = buf; while (c != (buf + size)) { struct tree_entry *e = new_tree_entry(); if (t->entry_count == t->entry_capacity) root->tree = t = grow_tree_content(t, t->entry_count); t->entries[t->entry_count++] = e; e->tree = NULL; c = get_mode(c, &e->versions[1].mode); if (!c) die("Corrupt mode in %s", sha1_to_hex(sha1)); e->versions[0].mode = e->versions[1].mode; e->name = to_atom(c, strlen(c)); c += e->name->str_len + 1; hashcpy(e->versions[0].sha1, (unsigned char *)c); hashcpy(e->versions[1].sha1, (unsigned char *)c); c += 20; } free(buf); } static int tecmp0 (const void *_a, const void *_b) { struct tree_entry *a = *((struct tree_entry**)_a); struct tree_entry *b = *((struct tree_entry**)_b); return base_name_compare( a->name->str_dat, a->name->str_len, a->versions[0].mode, b->name->str_dat, b->name->str_len, b->versions[0].mode); } static int tecmp1 (const void *_a, const void *_b) { struct tree_entry *a = *((struct tree_entry**)_a); struct tree_entry *b = *((struct tree_entry**)_b); return base_name_compare( a->name->str_dat, a->name->str_len, a->versions[1].mode, b->name->str_dat, b->name->str_len, b->versions[1].mode); } static void mktree(struct tree_content *t, int v, struct strbuf *b) { size_t maxlen = 0; unsigned int i; if (!v) qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0); else qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1); for (i = 0; i < t->entry_count; i++) { if (t->entries[i]->versions[v].mode) maxlen += t->entries[i]->name->str_len + 34; } strbuf_reset(b); strbuf_grow(b, maxlen); for (i = 0; i < t->entry_count; i++) { struct tree_entry *e = t->entries[i]; if (!e->versions[v].mode) continue; strbuf_addf(b, "%o %s%c", (unsigned int)(e->versions[v].mode & ~NO_DELTA), e->name->str_dat, '\0'); strbuf_add(b, e->versions[v].sha1, 20); } } static void store_tree(struct tree_entry *root) { struct tree_content *t; unsigned int i, j, del; struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 }; struct object_entry *le = NULL; if (!is_null_sha1(root->versions[1].sha1)) return; if (!root->tree) load_tree(root); t = root->tree; for (i = 0; i < t->entry_count; i++) { if (t->entries[i]->tree) store_tree(t->entries[i]); } if (!(root->versions[0].mode & NO_DELTA)) le = find_object(root->versions[0].sha1); if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) { mktree(t, 0, &old_tree); lo.data = old_tree; lo.offset = le->idx.offset; lo.depth = t->delta_depth; } mktree(t, 1, &new_tree); store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0); t->delta_depth = lo.depth; for (i = 0, j = 0, del = 0; i < t->entry_count; i++) { struct tree_entry *e = t->entries[i]; if (e->versions[1].mode) { e->versions[0].mode = e->versions[1].mode; hashcpy(e->versions[0].sha1, e->versions[1].sha1); t->entries[j++] = e; } else { release_tree_entry(e); del++; } } t->entry_count -= del; } static void tree_content_replace( struct tree_entry *root, const unsigned char *sha1, const uint16_t mode, struct tree_content *newtree) { if (!S_ISDIR(mode)) die("Root cannot be a non-directory"); hashclr(root->versions[0].sha1); hashcpy(root->versions[1].sha1, sha1); if (root->tree) release_tree_content_recursive(root->tree); root->tree = newtree; } static int tree_content_set( struct tree_entry *root, const char *p, const unsigned char *sha1, const uint16_t mode, struct tree_content *subtree) { struct tree_content *t; const char *slash1; unsigned int i, n; struct tree_entry *e; slash1 = strchrnul(p, '/'); n = slash1 - p; if (!n) die("Empty path component found in input"); if (!*slash1 && !S_ISDIR(mode) && subtree) die("Non-directories cannot have subtrees"); if (!root->tree) load_tree(root); t = root->tree; for (i = 0; i < t->entry_count; i++) { e = t->entries[i]; if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { if (!*slash1) { if (!S_ISDIR(mode) && e->versions[1].mode == mode && !hashcmp(e->versions[1].sha1, sha1)) return 0; e->versions[1].mode = mode; hashcpy(e->versions[1].sha1, sha1); if (e->tree) release_tree_content_recursive(e->tree); e->tree = subtree; /* * We need to leave e->versions[0].sha1 alone * to avoid modifying the preimage tree used * when writing out the parent directory. * But after replacing the subdir with a * completely different one, it's not a good * delta base any more, and besides, we've * thrown away the tree entries needed to * make a delta against it. * * So let's just explicitly disable deltas * for the subtree. */ if (S_ISDIR(e->versions[0].mode)) e->versions[0].mode |= NO_DELTA; hashclr(root->versions[1].sha1); return 1; } if (!S_ISDIR(e->versions[1].mode)) { e->tree = new_tree_content(8); e->versions[1].mode = S_IFDIR; } if (!e->tree) load_tree(e); if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) { hashclr(root->versions[1].sha1); return 1; } return 0; } } if (t->entry_count == t->entry_capacity) root->tree = t = grow_tree_content(t, t->entry_count); e = new_tree_entry(); e->name = to_atom(p, n); e->versions[0].mode = 0; hashclr(e->versions[0].sha1); t->entries[t->entry_count++] = e; if (*slash1) { e->tree = new_tree_content(8); e->versions[1].mode = S_IFDIR; tree_content_set(e, slash1 + 1, sha1, mode, subtree); } else { e->tree = subtree; e->versions[1].mode = mode; hashcpy(e->versions[1].sha1, sha1); } hashclr(root->versions[1].sha1); return 1; } static int tree_content_remove( struct tree_entry *root, const char *p, struct tree_entry *backup_leaf, int allow_root) { struct tree_content *t; const char *slash1; unsigned int i, n; struct tree_entry *e; slash1 = strchrnul(p, '/'); n = slash1 - p; if (!root->tree) load_tree(root); if (!*p && allow_root) { e = root; goto del_entry; } t = root->tree; for (i = 0; i < t->entry_count; i++) { e = t->entries[i]; if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { if (*slash1 && !S_ISDIR(e->versions[1].mode)) /* * If p names a file in some subdirectory, and a * file or symlink matching the name of the * parent directory of p exists, then p cannot * exist and need not be deleted. */ return 1; if (!*slash1 || !S_ISDIR(e->versions[1].mode)) goto del_entry; if (!e->tree) load_tree(e); if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) { for (n = 0; n < e->tree->entry_count; n++) { if (e->tree->entries[n]->versions[1].mode) { hashclr(root->versions[1].sha1); return 1; } } backup_leaf = NULL; goto del_entry; } return 0; } } return 0; del_entry: if (backup_leaf) memcpy(backup_leaf, e, sizeof(*backup_leaf)); else if (e->tree) release_tree_content_recursive(e->tree); e->tree = NULL; e->versions[1].mode = 0; hashclr(e->versions[1].sha1); hashclr(root->versions[1].sha1); return 1; } static int tree_content_get( struct tree_entry *root, const char *p, struct tree_entry *leaf, int allow_root) { struct tree_content *t; const char *slash1; unsigned int i, n; struct tree_entry *e; slash1 = strchrnul(p, '/'); n = slash1 - p; if (!n && !allow_root) die("Empty path component found in input"); if (!root->tree) load_tree(root); if (!n) { e = root; goto found_entry; } t = root->tree; for (i = 0; i < t->entry_count; i++) { e = t->entries[i]; if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { if (!*slash1) goto found_entry; if (!S_ISDIR(e->versions[1].mode)) return 0; if (!e->tree) load_tree(e); return tree_content_get(e, slash1 + 1, leaf, 0); } } return 0; found_entry: memcpy(leaf, e, sizeof(*leaf)); if (e->tree && is_null_sha1(e->versions[1].sha1)) leaf->tree = dup_tree_content(e->tree); else leaf->tree = NULL; return 1; } static int update_branch(struct branch *b) { static const char *msg = "fast-import"; struct ref_transaction *transaction; unsigned char old_sha1[20]; struct strbuf err = STRBUF_INIT; if (is_null_sha1(b->sha1)) { if (b->delete) delete_ref(b->name, NULL, 0); return 0; } if (read_ref(b->name, old_sha1)) hashclr(old_sha1); if (!force_update && !is_null_sha1(old_sha1)) { struct commit *old_cmit, *new_cmit; old_cmit = lookup_commit_reference_gently(old_sha1, 0); new_cmit = lookup_commit_reference_gently(b->sha1, 0); if (!old_cmit || !new_cmit) return error("Branch %s is missing commits.", b->name); if (!in_merge_bases(old_cmit, new_cmit)) { warning("Not updating %s" " (new tip %s does not contain %s)", b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1)); return -1; } } transaction = ref_transaction_begin(&err); if (!transaction || ref_transaction_update(transaction, b->name, b->sha1, old_sha1, 0, msg, &err) || ref_transaction_commit(transaction, &err)) { ref_transaction_free(transaction); error("%s", err.buf); strbuf_release(&err); return -1; } ref_transaction_free(transaction); strbuf_release(&err); return 0; } static void dump_branches(void) { unsigned int i; struct branch *b; for (i = 0; i < branch_table_sz; i++) { for (b = branch_table[i]; b; b = b->table_next_branch) failure |= update_branch(b); } } static void dump_tags(void) { static const char *msg = "fast-import"; struct tag *t; struct strbuf ref_name = STRBUF_INIT; struct strbuf err = STRBUF_INIT; struct ref_transaction *transaction; transaction = ref_transaction_begin(&err); if (!transaction) { failure |= error("%s", err.buf); goto cleanup; } for (t = first_tag; t; t = t->next_tag) { strbuf_reset(&ref_name); strbuf_addf(&ref_name, "refs/tags/%s", t->name); if (ref_transaction_update(transaction, ref_name.buf, t->sha1, NULL, 0, msg, &err)) { failure |= error("%s", err.buf); goto cleanup; } } if (ref_transaction_commit(transaction, &err)) failure |= error("%s", err.buf); cleanup: ref_transaction_free(transaction); strbuf_release(&ref_name); strbuf_release(&err); } static void dump_marks_helper(FILE *f, uintmax_t base, struct mark_set *m) { uintmax_t k; if (m->shift) { for (k = 0; k < 1024; k++) { if (m->data.sets[k]) dump_marks_helper(f, base + (k << m->shift), m->data.sets[k]); } } else { for (k = 0; k < 1024; k++) { if (m->data.marked[k]) fprintf(f, ":%" PRIuMAX " %s\n", base + k, sha1_to_hex(m->data.marked[k]->idx.sha1)); } } } static void dump_marks(void) { static struct lock_file mark_lock; FILE *f; if (!export_marks_file) return; if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) { failure |= error("Unable to write marks file %s: %s", export_marks_file, strerror(errno)); return; } f = fdopen_lock_file(&mark_lock, "w"); if (!f) { int saved_errno = errno; rollback_lock_file(&mark_lock); failure |= error("Unable to write marks file %s: %s", export_marks_file, strerror(saved_errno)); return; } dump_marks_helper(f, 0, marks); if (commit_lock_file(&mark_lock)) { failure |= error("Unable to commit marks file %s: %s", export_marks_file, strerror(errno)); return; } } static void read_marks(void) { char line[512]; FILE *f = fopen(import_marks_file, "r"); if (f) ; else if (import_marks_file_ignore_missing && errno == ENOENT) return; /* Marks file does not exist */ else die_errno("cannot read '%s'", import_marks_file); while (fgets(line, sizeof(line), f)) { uintmax_t mark; char *end; unsigned char sha1[20]; struct object_entry *e; end = strchr(line, '\n'); if (line[0] != ':' || !end) die("corrupt mark line: %s", line); *end = 0; mark = strtoumax(line + 1, &end, 10); if (!mark || end == line + 1 || *end != ' ' || get_sha1_hex(end + 1, sha1)) die("corrupt mark line: %s", line); e = find_object(sha1); if (!e) { enum object_type type = sha1_object_info(sha1, NULL); if (type < 0) die("object not found: %s", sha1_to_hex(sha1)); e = insert_object(sha1); e->type = type; e->pack_id = MAX_PACK_ID; e->idx.offset = 1; /* just not zero! */ } insert_mark(mark, e); } fclose(f); } static int read_next_command(void) { static int stdin_eof = 0; if (stdin_eof) { unread_command_buf = 0; return EOF; } for (;;) { const char *p; if (unread_command_buf) { unread_command_buf = 0; } else { struct recent_command *rc; strbuf_detach(&command_buf, NULL); stdin_eof = strbuf_getline(&command_buf, stdin, '\n'); if (stdin_eof) return EOF; if (!seen_data_command && !starts_with(command_buf.buf, "feature ") && !starts_with(command_buf.buf, "option ")) { parse_argv(); } rc = rc_free; if (rc) rc_free = rc->next; else { rc = cmd_hist.next; cmd_hist.next = rc->next; cmd_hist.next->prev = &cmd_hist; free(rc->buf); } rc->buf = command_buf.buf; rc->prev = cmd_tail; rc->next = cmd_hist.prev; rc->prev->next = rc; cmd_tail = rc; } if (skip_prefix(command_buf.buf, "get-mark ", &p)) { parse_get_mark(p); continue; } if (skip_prefix(command_buf.buf, "cat-blob ", &p)) { parse_cat_blob(p); continue; } if (command_buf.buf[0] == '#') continue; return 0; } } static void skip_optional_lf(void) { int term_char = fgetc(stdin); if (term_char != '\n' && term_char != EOF) ungetc(term_char, stdin); } static void parse_mark(void) { const char *v; if (skip_prefix(command_buf.buf, "mark :", &v)) { next_mark = strtoumax(v, NULL, 10); read_next_command(); } else next_mark = 0; } static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res) { const char *data; strbuf_reset(sb); if (!skip_prefix(command_buf.buf, "data ", &data)) die("Expected 'data n' command, found: %s", command_buf.buf); if (skip_prefix(data, "<<", &data)) { char *term = xstrdup(data); size_t term_len = command_buf.len - (data - command_buf.buf); strbuf_detach(&command_buf, NULL); for (;;) { if (strbuf_getline(&command_buf, stdin, '\n') == EOF) die("EOF in data (terminator '%s' not found)", term); if (term_len == command_buf.len && !strcmp(term, command_buf.buf)) break; strbuf_addbuf(sb, &command_buf); strbuf_addch(sb, '\n'); } free(term); } else { uintmax_t len = strtoumax(data, NULL, 10); size_t n = 0, length = (size_t)len; if (limit && limit < len) { *len_res = len; return 0; } if (length < len) die("data is too large to use in this context"); while (n < length) { size_t s = strbuf_fread(sb, length - n, stdin); if (!s && feof(stdin)) die("EOF in data (%lu bytes remaining)", (unsigned long)(length - n)); n += s; } } skip_optional_lf(); return 1; } static int validate_raw_date(const char *src, struct strbuf *result) { const char *orig_src = src; char *endp; unsigned long num; errno = 0; num = strtoul(src, &endp, 10); /* NEEDSWORK: perhaps check for reasonable values? */ if (errno || endp == src || *endp != ' ') return -1; src = endp + 1; if (*src != '-' && *src != '+') return -1; num = strtoul(src + 1, &endp, 10); if (errno || endp == src + 1 || *endp || 1400 < num) return -1; strbuf_addstr(result, orig_src); return 0; } static char *parse_ident(const char *buf) { const char *ltgt; size_t name_len; struct strbuf ident = STRBUF_INIT; /* ensure there is a space delimiter even if there is no name */ if (*buf == '<') --buf; ltgt = buf + strcspn(buf, "<>"); if (*ltgt != '<') die("Missing < in ident string: %s", buf); if (ltgt != buf && ltgt[-1] != ' ') die("Missing space before < in ident string: %s", buf); ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>"); if (*ltgt != '>') die("Missing > in ident string: %s", buf); ltgt++; if (*ltgt != ' ') die("Missing space after > in ident string: %s", buf); ltgt++; name_len = ltgt - buf; strbuf_add(&ident, buf, name_len); switch (whenspec) { case WHENSPEC_RAW: if (validate_raw_date(ltgt, &ident) < 0) die("Invalid raw date \"%s\" in ident: %s", ltgt, buf); break; case WHENSPEC_RFC2822: if (parse_date(ltgt, &ident) < 0) die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf); break; case WHENSPEC_NOW: if (strcmp("now", ltgt)) die("Date in ident must be 'now': %s", buf); datestamp(&ident); break; } return strbuf_detach(&ident, NULL); } static void parse_and_store_blob( struct last_object *last, unsigned char *sha1out, uintmax_t mark) { static struct strbuf buf = STRBUF_INIT; uintmax_t len; if (parse_data(&buf, big_file_threshold, &len)) store_object(OBJ_BLOB, &buf, last, sha1out, mark); else { if (last) { strbuf_release(&last->data); last->offset = 0; last->depth = 0; } stream_blob(len, sha1out, mark); skip_optional_lf(); } } static void parse_new_blob(void) { read_next_command(); parse_mark(); parse_and_store_blob(&last_blob, NULL, next_mark); } static void unload_one_branch(void) { while (cur_active_branches && cur_active_branches >= max_active_branches) { uintmax_t min_commit = ULONG_MAX; struct branch *e, *l = NULL, *p = NULL; for (e = active_branches; e; e = e->active_next_branch) { if (e->last_commit < min_commit) { p = l; min_commit = e->last_commit; } l = e; } if (p) { e = p->active_next_branch; p->active_next_branch = e->active_next_branch; } else { e = active_branches; active_branches = e->active_next_branch; } e->active = 0; e->active_next_branch = NULL; if (e->branch_tree.tree) { release_tree_content_recursive(e->branch_tree.tree); e->branch_tree.tree = NULL; } cur_active_branches--; } } static void load_branch(struct branch *b) { load_tree(&b->branch_tree); if (!b->active) { b->active = 1; b->active_next_branch = active_branches; active_branches = b; cur_active_branches++; branch_load_count++; } } static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes) { unsigned char fanout = 0; while ((num_notes >>= 8)) fanout++; return fanout; } static void construct_path_with_fanout(const char *hex_sha1, unsigned char fanout, char *path) { unsigned int i = 0, j = 0; if (fanout >= 20) die("Too large fanout (%u)", fanout); while (fanout) { path[i++] = hex_sha1[j++]; path[i++] = hex_sha1[j++]; path[i++] = '/'; fanout--; } memcpy(path + i, hex_sha1 + j, 40 - j); path[i + 40 - j] = '\0'; } static uintmax_t do_change_note_fanout( struct tree_entry *orig_root, struct tree_entry *root, char *hex_sha1, unsigned int hex_sha1_len, char *fullpath, unsigned int fullpath_len, unsigned char fanout) { struct tree_content *t = root->tree; struct tree_entry *e, leaf; unsigned int i, tmp_hex_sha1_len, tmp_fullpath_len; uintmax_t num_notes = 0; unsigned char sha1[20]; char realpath[60]; for (i = 0; t && i < t->entry_count; i++) { e = t->entries[i]; tmp_hex_sha1_len = hex_sha1_len + e->name->str_len; tmp_fullpath_len = fullpath_len; /* * We're interested in EITHER existing note entries (entries * with exactly 40 hex chars in path, not including directory * separators), OR directory entries that may contain note * entries (with < 40 hex chars in path). * Also, each path component in a note entry must be a multiple * of 2 chars. */ if (!e->versions[1].mode || tmp_hex_sha1_len > 40 || e->name->str_len % 2) continue; /* This _may_ be a note entry, or a subdir containing notes */ memcpy(hex_sha1 + hex_sha1_len, e->name->str_dat, e->name->str_len); if (tmp_fullpath_len) fullpath[tmp_fullpath_len++] = '/'; memcpy(fullpath + tmp_fullpath_len, e->name->str_dat, e->name->str_len); tmp_fullpath_len += e->name->str_len; fullpath[tmp_fullpath_len] = '\0'; if (tmp_hex_sha1_len == 40 && !get_sha1_hex(hex_sha1, sha1)) { /* This is a note entry */ if (fanout == 0xff) { /* Counting mode, no rename */ num_notes++; continue; } construct_path_with_fanout(hex_sha1, fanout, realpath); if (!strcmp(fullpath, realpath)) { /* Note entry is in correct location */ num_notes++; continue; } /* Rename fullpath to realpath */ if (!tree_content_remove(orig_root, fullpath, &leaf, 0)) die("Failed to remove path %s", fullpath); tree_content_set(orig_root, realpath, leaf.versions[1].sha1, leaf.versions[1].mode, leaf.tree); } else if (S_ISDIR(e->versions[1].mode)) { /* This is a subdir that may contain note entries */ if (!e->tree) load_tree(e); num_notes += do_change_note_fanout(orig_root, e, hex_sha1, tmp_hex_sha1_len, fullpath, tmp_fullpath_len, fanout); } /* The above may have reallocated the current tree_content */ t = root->tree; } return num_notes; } static uintmax_t change_note_fanout(struct tree_entry *root, unsigned char fanout) { char hex_sha1[40], path[60]; return do_change_note_fanout(root, root, hex_sha1, 0, path, 0, fanout); } /* * Given a pointer into a string, parse a mark reference: * * idnum ::= ':' bigint; * * Return the first character after the value in *endptr. * * Complain if the following character is not what is expected, * either a space or end of the string. */ static uintmax_t parse_mark_ref(const char *p, char **endptr) { uintmax_t mark; assert(*p == ':'); p++; mark = strtoumax(p, endptr, 10); if (*endptr == p) die("No value after ':' in mark: %s", command_buf.buf); return mark; } /* * Parse the mark reference, and complain if this is not the end of * the string. */ static uintmax_t parse_mark_ref_eol(const char *p) { char *end; uintmax_t mark; mark = parse_mark_ref(p, &end); if (*end != '\0') die("Garbage after mark: %s", command_buf.buf); return mark; } /* * Parse the mark reference, demanding a trailing space. Return a * pointer to the space. */ static uintmax_t parse_mark_ref_space(const char **p) { uintmax_t mark; char *end; mark = parse_mark_ref(*p, &end); if (*end++ != ' ') die("Missing space after mark: %s", command_buf.buf); *p = end; return mark; } static void file_change_m(const char *p, struct branch *b) { static struct strbuf uq = STRBUF_INIT; const char *endp; struct object_entry *oe; unsigned char sha1[20]; uint16_t mode, inline_data = 0; p = get_mode(p, &mode); if (!p) die("Corrupt mode: %s", command_buf.buf); switch (mode) { case 0644: case 0755: mode |= S_IFREG; case S_IFREG | 0644: case S_IFREG | 0755: case S_IFLNK: case S_IFDIR: case S_IFGITLINK: /* ok */ break; default: die("Corrupt mode: %s", command_buf.buf); } if (*p == ':') { oe = find_mark(parse_mark_ref_space(&p)); hashcpy(sha1, oe->idx.sha1); } else if (skip_prefix(p, "inline ", &p)) { inline_data = 1; oe = NULL; /* not used with inline_data, but makes gcc happy */ } else { if (get_sha1_hex(p, sha1)) die("Invalid dataref: %s", command_buf.buf); oe = find_object(sha1); p += 40; if (*p++ != ' ') die("Missing space after SHA1: %s", command_buf.buf); } strbuf_reset(&uq); if (!unquote_c_style(&uq, p, &endp)) { if (*endp) die("Garbage after path in: %s", command_buf.buf); p = uq.buf; } /* Git does not track empty, non-toplevel directories. */ if (S_ISDIR(mode) && !hashcmp(sha1, EMPTY_TREE_SHA1_BIN) && *p) { tree_content_remove(&b->branch_tree, p, NULL, 0); return; } if (S_ISGITLINK(mode)) { if (inline_data) die("Git links cannot be specified 'inline': %s", command_buf.buf); else if (oe) { if (oe->type != OBJ_COMMIT) die("Not a commit (actually a %s): %s", typename(oe->type), command_buf.buf); } /* * Accept the sha1 without checking; it expected to be in * another repository. */ } else if (inline_data) { if (S_ISDIR(mode)) die("Directories cannot be specified 'inline': %s", command_buf.buf); if (p != uq.buf) { strbuf_addstr(&uq, p); p = uq.buf; } read_next_command(); parse_and_store_blob(&last_blob, sha1, 0); } else { enum object_type expected = S_ISDIR(mode) ? OBJ_TREE: OBJ_BLOB; enum object_type type = oe ? oe->type : sha1_object_info(sha1, NULL); if (type < 0) die("%s not found: %s", S_ISDIR(mode) ? "Tree" : "Blob", command_buf.buf); if (type != expected) die("Not a %s (actually a %s): %s", typename(expected), typename(type), command_buf.buf); } if (!*p) { tree_content_replace(&b->branch_tree, sha1, mode, NULL); return; } tree_content_set(&b->branch_tree, p, sha1, mode, NULL); } static void file_change_d(const char *p, struct branch *b) { static struct strbuf uq = STRBUF_INIT; const char *endp; strbuf_reset(&uq); if (!unquote_c_style(&uq, p, &endp)) { if (*endp) die("Garbage after path in: %s", command_buf.buf); p = uq.buf; } tree_content_remove(&b->branch_tree, p, NULL, 1); } static void file_change_cr(const char *s, struct branch *b, int rename) { const char *d; static struct strbuf s_uq = STRBUF_INIT; static struct strbuf d_uq = STRBUF_INIT; const char *endp; struct tree_entry leaf; strbuf_reset(&s_uq); if (!unquote_c_style(&s_uq, s, &endp)) { if (*endp != ' ') die("Missing space after source: %s", command_buf.buf); } else { endp = strchr(s, ' '); if (!endp) die("Missing space after source: %s", command_buf.buf); strbuf_add(&s_uq, s, endp - s); } s = s_uq.buf; endp++; if (!*endp) die("Missing dest: %s", command_buf.buf); d = endp; strbuf_reset(&d_uq); if (!unquote_c_style(&d_uq, d, &endp)) { if (*endp) die("Garbage after dest in: %s", command_buf.buf); d = d_uq.buf; } memset(&leaf, 0, sizeof(leaf)); if (rename) tree_content_remove(&b->branch_tree, s, &leaf, 1); else tree_content_get(&b->branch_tree, s, &leaf, 1); if (!leaf.versions[1].mode) die("Path %s not in branch", s); if (!*d) { /* C "path/to/subdir" "" */ tree_content_replace(&b->branch_tree, leaf.versions[1].sha1, leaf.versions[1].mode, leaf.tree); return; } tree_content_set(&b->branch_tree, d, leaf.versions[1].sha1, leaf.versions[1].mode, leaf.tree); } static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout) { static struct strbuf uq = STRBUF_INIT; struct object_entry *oe; struct branch *s; unsigned char sha1[20], commit_sha1[20]; char path[60]; uint16_t inline_data = 0; unsigned char new_fanout; /* * When loading a branch, we don't traverse its tree to count the real * number of notes (too expensive to do this for all non-note refs). * This means that recently loaded notes refs might incorrectly have * b->num_notes == 0, and consequently, old_fanout might be wrong. * * Fix this by traversing the tree and counting the number of notes * when b->num_notes == 0. If the notes tree is truly empty, the * calculation should not take long. */ if (b->num_notes == 0 && *old_fanout == 0) { /* Invoke change_note_fanout() in "counting mode". */ b->num_notes = change_note_fanout(&b->branch_tree, 0xff); *old_fanout = convert_num_notes_to_fanout(b->num_notes); } /* Now parse the notemodify command. */ /* <dataref> or 'inline' */ if (*p == ':') { oe = find_mark(parse_mark_ref_space(&p)); hashcpy(sha1, oe->idx.sha1); } else if (skip_prefix(p, "inline ", &p)) { inline_data = 1; oe = NULL; /* not used with inline_data, but makes gcc happy */ } else { if (get_sha1_hex(p, sha1)) die("Invalid dataref: %s", command_buf.buf); oe = find_object(sha1); p += 40; if (*p++ != ' ') die("Missing space after SHA1: %s", command_buf.buf); } /* <commit-ish> */ s = lookup_branch(p); if (s) { if (is_null_sha1(s->sha1)) die("Can't add a note on empty branch."); hashcpy(commit_sha1, s->sha1); } else if (*p == ':') { uintmax_t commit_mark = parse_mark_ref_eol(p); struct object_entry *commit_oe = find_mark(commit_mark); if (commit_oe->type != OBJ_COMMIT) die("Mark :%" PRIuMAX " not a commit", commit_mark); hashcpy(commit_sha1, commit_oe->idx.sha1); } else if (!get_sha1(p, commit_sha1)) { unsigned long size; char *buf = read_object_with_reference(commit_sha1, commit_type, &size, commit_sha1); if (!buf || size < 46) die("Not a valid commit: %s", p); free(buf); } else die("Invalid ref name or SHA1 expression: %s", p); if (inline_data) { if (p != uq.buf) { strbuf_addstr(&uq, p); p = uq.buf; } read_next_command(); parse_and_store_blob(&last_blob, sha1, 0); } else if (oe) { if (oe->type != OBJ_BLOB) die("Not a blob (actually a %s): %s", typename(oe->type), command_buf.buf); } else if (!is_null_sha1(sha1)) { enum object_type type = sha1_object_info(sha1, NULL); if (type < 0) die("Blob not found: %s", command_buf.buf); if (type != OBJ_BLOB) die("Not a blob (actually a %s): %s", typename(type), command_buf.buf); } construct_path_with_fanout(sha1_to_hex(commit_sha1), *old_fanout, path); if (tree_content_remove(&b->branch_tree, path, NULL, 0)) b->num_notes--; if (is_null_sha1(sha1)) return; /* nothing to insert */ b->num_notes++; new_fanout = convert_num_notes_to_fanout(b->num_notes); construct_path_with_fanout(sha1_to_hex(commit_sha1), new_fanout, path); tree_content_set(&b->branch_tree, path, sha1, S_IFREG | 0644, NULL); } static void file_change_deleteall(struct branch *b) { release_tree_content_recursive(b->branch_tree.tree); hashclr(b->branch_tree.versions[0].sha1); hashclr(b->branch_tree.versions[1].sha1); load_tree(&b->branch_tree); b->num_notes = 0; } static void parse_from_commit(struct branch *b, char *buf, unsigned long size) { if (!buf || size < 46) die("Not a valid commit: %s", sha1_to_hex(b->sha1)); if (memcmp("tree ", buf, 5) || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1)) die("The commit %s is corrupt", sha1_to_hex(b->sha1)); hashcpy(b->branch_tree.versions[0].sha1, b->branch_tree.versions[1].sha1); } static void parse_from_existing(struct branch *b) { if (is_null_sha1(b->sha1)) { hashclr(b->branch_tree.versions[0].sha1); hashclr(b->branch_tree.versions[1].sha1); } else { unsigned long size; char *buf; buf = read_object_with_reference(b->sha1, commit_type, &size, b->sha1); parse_from_commit(b, buf, size); free(buf); } } static int parse_from(struct branch *b) { const char *from; struct branch *s; unsigned char sha1[20]; if (!skip_prefix(command_buf.buf, "from ", &from)) return 0; hashcpy(sha1, b->branch_tree.versions[1].sha1); s = lookup_branch(from); if (b == s) die("Can't create a branch from itself: %s", b->name); else if (s) { unsigned char *t = s->branch_tree.versions[1].sha1; hashcpy(b->sha1, s->sha1); hashcpy(b->branch_tree.versions[0].sha1, t); hashcpy(b->branch_tree.versions[1].sha1, t); } else if (*from == ':') { uintmax_t idnum = parse_mark_ref_eol(from); struct object_entry *oe = find_mark(idnum); if (oe->type != OBJ_COMMIT) die("Mark :%" PRIuMAX " not a commit", idnum); if (hashcmp(b->sha1, oe->idx.sha1)) { hashcpy(b->sha1, oe->idx.sha1); if (oe->pack_id != MAX_PACK_ID) { unsigned long size; char *buf = gfi_unpack_entry(oe, &size); parse_from_commit(b, buf, size); free(buf); } else parse_from_existing(b); } } else if (!get_sha1(from, b->sha1)) { parse_from_existing(b); if (is_null_sha1(b->sha1)) b->delete = 1; } else die("Invalid ref name or SHA1 expression: %s", from); if (b->branch_tree.tree && hashcmp(sha1, b->branch_tree.versions[1].sha1)) { release_tree_content_recursive(b->branch_tree.tree); b->branch_tree.tree = NULL; } read_next_command(); return 1; } static struct hash_list *parse_merge(unsigned int *count) { struct hash_list *list = NULL, **tail = &list, *n; const char *from; struct branch *s; *count = 0; while (skip_prefix(command_buf.buf, "merge ", &from)) { n = xmalloc(sizeof(*n)); s = lookup_branch(from); if (s) hashcpy(n->sha1, s->sha1); else if (*from == ':') { uintmax_t idnum = parse_mark_ref_eol(from); struct object_entry *oe = find_mark(idnum); if (oe->type != OBJ_COMMIT) die("Mark :%" PRIuMAX " not a commit", idnum); hashcpy(n->sha1, oe->idx.sha1); } else if (!get_sha1(from, n->sha1)) { unsigned long size; char *buf = read_object_with_reference(n->sha1, commit_type, &size, n->sha1); if (!buf || size < 46) die("Not a valid commit: %s", from); free(buf); } else die("Invalid ref name or SHA1 expression: %s", from); n->next = NULL; *tail = n; tail = &n->next; (*count)++; read_next_command(); } return list; } static void parse_new_commit(const char *arg) { static struct strbuf msg = STRBUF_INIT; struct branch *b; char *author = NULL; char *committer = NULL; struct hash_list *merge_list = NULL; unsigned int merge_count; unsigned char prev_fanout, new_fanout; const char *v; b = lookup_branch(arg); if (!b) b = new_branch(arg); read_next_command(); parse_mark(); if (skip_prefix(command_buf.buf, "author ", &v)) { author = parse_ident(v); read_next_command(); } if (skip_prefix(command_buf.buf, "committer ", &v)) { committer = parse_ident(v); read_next_command(); } if (!committer) die("Expected committer but didn't get one"); parse_data(&msg, 0, NULL); read_next_command(); parse_from(b); merge_list = parse_merge(&merge_count); /* ensure the branch is active/loaded */ if (!b->branch_tree.tree || !max_active_branches) { unload_one_branch(); load_branch(b); } prev_fanout = convert_num_notes_to_fanout(b->num_notes); /* file_change* */ while (command_buf.len > 0) { if (skip_prefix(command_buf.buf, "M ", &v)) file_change_m(v, b); else if (skip_prefix(command_buf.buf, "D ", &v)) file_change_d(v, b); else if (skip_prefix(command_buf.buf, "R ", &v)) file_change_cr(v, b, 1); else if (skip_prefix(command_buf.buf, "C ", &v)) file_change_cr(v, b, 0); else if (skip_prefix(command_buf.buf, "N ", &v)) note_change_n(v, b, &prev_fanout); else if (!strcmp("deleteall", command_buf.buf)) file_change_deleteall(b); else if (skip_prefix(command_buf.buf, "ls ", &v)) parse_ls(v, b); else { unread_command_buf = 1; break; } if (read_next_command() == EOF) break; } new_fanout = convert_num_notes_to_fanout(b->num_notes); if (new_fanout != prev_fanout) b->num_notes = change_note_fanout(&b->branch_tree, new_fanout); /* build the tree and the commit */ store_tree(&b->branch_tree); hashcpy(b->branch_tree.versions[0].sha1, b->branch_tree.versions[1].sha1); strbuf_reset(&new_data); strbuf_addf(&new_data, "tree %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1)); if (!is_null_sha1(b->sha1)) strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1)); while (merge_list) { struct hash_list *next = merge_list->next; strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1)); free(merge_list); merge_list = next; } strbuf_addf(&new_data, "author %s\n" "committer %s\n" "\n", author ? author : committer, committer); strbuf_addbuf(&new_data, &msg); free(author); free(committer); if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark)) b->pack_id = pack_id; b->last_commit = object_count_by_type[OBJ_COMMIT]; } static void parse_new_tag(const char *arg) { static struct strbuf msg = STRBUF_INIT; const char *from; char *tagger; struct branch *s; struct tag *t; uintmax_t from_mark = 0; unsigned char sha1[20]; enum object_type type; const char *v; t = pool_alloc(sizeof(struct tag)); memset(t, 0, sizeof(struct tag)); t->name = pool_strdup(arg); if (last_tag) last_tag->next_tag = t; else first_tag = t; last_tag = t; read_next_command(); /* from ... */ if (!skip_prefix(command_buf.buf, "from ", &from)) die("Expected from command, got %s", command_buf.buf); s = lookup_branch(from); if (s) { if (is_null_sha1(s->sha1)) die("Can't tag an empty branch."); hashcpy(sha1, s->sha1); type = OBJ_COMMIT; } else if (*from == ':') { struct object_entry *oe; from_mark = parse_mark_ref_eol(from); oe = find_mark(from_mark); type = oe->type; hashcpy(sha1, oe->idx.sha1); } else if (!get_sha1(from, sha1)) { struct object_entry *oe = find_object(sha1); if (!oe) { type = sha1_object_info(sha1, NULL); if (type < 0) die("Not a valid object: %s", from); } else type = oe->type; } else die("Invalid ref name or SHA1 expression: %s", from); read_next_command(); /* tagger ... */ if (skip_prefix(command_buf.buf, "tagger ", &v)) { tagger = parse_ident(v); read_next_command(); } else tagger = NULL; /* tag payload/message */ parse_data(&msg, 0, NULL); /* build the tag object */ strbuf_reset(&new_data); strbuf_addf(&new_data, "object %s\n" "type %s\n" "tag %s\n", sha1_to_hex(sha1), typename(type), t->name); if (tagger) strbuf_addf(&new_data, "tagger %s\n", tagger); strbuf_addch(&new_data, '\n'); strbuf_addbuf(&new_data, &msg); free(tagger); if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0)) t->pack_id = MAX_PACK_ID; else t->pack_id = pack_id; } static void parse_reset_branch(const char *arg) { struct branch *b; b = lookup_branch(arg); if (b) { hashclr(b->sha1); hashclr(b->branch_tree.versions[0].sha1); hashclr(b->branch_tree.versions[1].sha1); if (b->branch_tree.tree) { release_tree_content_recursive(b->branch_tree.tree); b->branch_tree.tree = NULL; } } else b = new_branch(arg); read_next_command(); parse_from(b); if (command_buf.len > 0) unread_command_buf = 1; } static void cat_blob_write(const char *buf, unsigned long size) { if (write_in_full(cat_blob_fd, buf, size) != size) die_errno("Write to frontend failed"); } static void cat_blob(struct object_entry *oe, unsigned char sha1[20]) { struct strbuf line = STRBUF_INIT; unsigned long size; enum object_type type = 0; char *buf; if (!oe || oe->pack_id == MAX_PACK_ID) { buf = read_sha1_file(sha1, &type, &size); } else { type = oe->type; buf = gfi_unpack_entry(oe, &size); } /* * Output based on batch_one_object() from cat-file.c. */ if (type <= 0) { strbuf_reset(&line); strbuf_addf(&line, "%s missing\n", sha1_to_hex(sha1)); cat_blob_write(line.buf, line.len); strbuf_release(&line); free(buf); return; } if (!buf) die("Can't read object %s", sha1_to_hex(sha1)); if (type != OBJ_BLOB) die("Object %s is a %s but a blob was expected.", sha1_to_hex(sha1), typename(type)); strbuf_reset(&line); strbuf_addf(&line, "%s %s %lu\n", sha1_to_hex(sha1), typename(type), size); cat_blob_write(line.buf, line.len); strbuf_release(&line); cat_blob_write(buf, size); cat_blob_write("\n", 1); if (oe && oe->pack_id == pack_id) { last_blob.offset = oe->idx.offset; strbuf_attach(&last_blob.data, buf, size, size); last_blob.depth = oe->depth; } else free(buf); } static void parse_get_mark(const char *p) { struct object_entry *oe = oe; char output[42]; /* get-mark SP <object> LF */ if (*p != ':') die("Not a mark: %s", p); oe = find_mark(parse_mark_ref_eol(p)); if (!oe) die("Unknown mark: %s", command_buf.buf); snprintf(output, sizeof(output), "%s\n", sha1_to_hex(oe->idx.sha1)); cat_blob_write(output, 41); } static void parse_cat_blob(const char *p) { struct object_entry *oe = oe; unsigned char sha1[20]; /* cat-blob SP <object> LF */ if (*p == ':') { oe = find_mark(parse_mark_ref_eol(p)); if (!oe) die("Unknown mark: %s", command_buf.buf); hashcpy(sha1, oe->idx.sha1); } else { if (get_sha1_hex(p, sha1)) die("Invalid dataref: %s", command_buf.buf); if (p[40]) die("Garbage after SHA1: %s", command_buf.buf); oe = find_object(sha1); } cat_blob(oe, sha1); } static struct object_entry *dereference(struct object_entry *oe, unsigned char sha1[20]) { unsigned long size; char *buf = NULL; if (!oe) { enum object_type type = sha1_object_info(sha1, NULL); if (type < 0) die("object not found: %s", sha1_to_hex(sha1)); /* cache it! */ oe = insert_object(sha1); oe->type = type; oe->pack_id = MAX_PACK_ID; oe->idx.offset = 1; } switch (oe->type) { case OBJ_TREE: /* easy case. */ return oe; case OBJ_COMMIT: case OBJ_TAG: break; default: die("Not a tree-ish: %s", command_buf.buf); } if (oe->pack_id != MAX_PACK_ID) { /* in a pack being written */ buf = gfi_unpack_entry(oe, &size); } else { enum object_type unused; buf = read_sha1_file(sha1, &unused, &size); } if (!buf) die("Can't load object %s", sha1_to_hex(sha1)); /* Peel one layer. */ switch (oe->type) { case OBJ_TAG: if (size < 40 + strlen("object ") || get_sha1_hex(buf + strlen("object "), sha1)) die("Invalid SHA1 in tag: %s", command_buf.buf); break; case OBJ_COMMIT: if (size < 40 + strlen("tree ") || get_sha1_hex(buf + strlen("tree "), sha1)) die("Invalid SHA1 in commit: %s", command_buf.buf); } free(buf); return find_object(sha1); } static struct object_entry *parse_treeish_dataref(const char **p) { unsigned char sha1[20]; struct object_entry *e; if (**p == ':') { /* <mark> */ e = find_mark(parse_mark_ref_space(p)); if (!e) die("Unknown mark: %s", command_buf.buf); hashcpy(sha1, e->idx.sha1); } else { /* <sha1> */ if (get_sha1_hex(*p, sha1)) die("Invalid dataref: %s", command_buf.buf); e = find_object(sha1); *p += 40; if (*(*p)++ != ' ') die("Missing space after tree-ish: %s", command_buf.buf); } while (!e || e->type != OBJ_TREE) e = dereference(e, sha1); return e; } static void print_ls(int mode, const unsigned char *sha1, const char *path) { static struct strbuf line = STRBUF_INIT; /* See show_tree(). */ const char *type = S_ISGITLINK(mode) ? commit_type : S_ISDIR(mode) ? tree_type : blob_type; if (!mode) { /* missing SP path LF */ strbuf_reset(&line); strbuf_addstr(&line, "missing "); quote_c_style(path, &line, NULL, 0); strbuf_addch(&line, '\n'); } else { /* mode SP type SP object_name TAB path LF */ strbuf_reset(&line); strbuf_addf(&line, "%06o %s %s\t", mode & ~NO_DELTA, type, sha1_to_hex(sha1)); quote_c_style(path, &line, NULL, 0); strbuf_addch(&line, '\n'); } cat_blob_write(line.buf, line.len); } static void parse_ls(const char *p, struct branch *b) { struct tree_entry *root = NULL; struct tree_entry leaf = {NULL}; /* ls SP (<tree-ish> SP)? <path> */ if (*p == '"') { if (!b) die("Not in a commit: %s", command_buf.buf); root = &b->branch_tree; } else { struct object_entry *e = parse_treeish_dataref(&p); root = new_tree_entry(); hashcpy(root->versions[1].sha1, e->idx.sha1); if (!is_null_sha1(root->versions[1].sha1)) root->versions[1].mode = S_IFDIR; load_tree(root); } if (*p == '"') { static struct strbuf uq = STRBUF_INIT; const char *endp; strbuf_reset(&uq); if (unquote_c_style(&uq, p, &endp)) die("Invalid path: %s", command_buf.buf); if (*endp) die("Garbage after path in: %s", command_buf.buf); p = uq.buf; } tree_content_get(root, p, &leaf, 1); /* * A directory in preparation would have a sha1 of zero * until it is saved. Save, for simplicity. */ if (S_ISDIR(leaf.versions[1].mode)) store_tree(&leaf); print_ls(leaf.versions[1].mode, leaf.versions[1].sha1, p); if (leaf.tree) release_tree_content_recursive(leaf.tree); if (!b || root != &b->branch_tree) release_tree_entry(root); } static void checkpoint(void) { checkpoint_requested = 0; if (object_count) { cycle_packfile(); dump_branches(); dump_tags(); dump_marks(); } } static void parse_checkpoint(void) { checkpoint_requested = 1; skip_optional_lf(); } static void parse_progress(void) { fwrite(command_buf.buf, 1, command_buf.len, stdout); fputc('\n', stdout); fflush(stdout); skip_optional_lf(); } static char* make_fast_import_path(const char *path) { if (!relative_marks_paths || is_absolute_path(path)) return xstrdup(path); return xstrdup(git_path("info/fast-import/%s", path)); } static void option_import_marks(const char *marks, int from_stream, int ignore_missing) { if (import_marks_file) { if (from_stream) die("Only one import-marks command allowed per stream"); /* read previous mark file */ if(!import_marks_file_from_stream) read_marks(); } import_marks_file = make_fast_import_path(marks); safe_create_leading_directories_const(import_marks_file); import_marks_file_from_stream = from_stream; import_marks_file_ignore_missing = ignore_missing; } static void option_date_format(const char *fmt) { if (!strcmp(fmt, "raw")) whenspec = WHENSPEC_RAW; else if (!strcmp(fmt, "rfc2822")) whenspec = WHENSPEC_RFC2822; else if (!strcmp(fmt, "now")) whenspec = WHENSPEC_NOW; else die("unknown --date-format argument %s", fmt); } static unsigned long ulong_arg(const char *option, const char *arg) { char *endptr; unsigned long rv = strtoul(arg, &endptr, 0); if (strchr(arg, '-') || endptr == arg || *endptr) die("%s: argument must be a non-negative integer", option); return rv; } static void option_depth(const char *depth) { max_depth = ulong_arg("--depth", depth); if (max_depth > MAX_DEPTH) die("--depth cannot exceed %u", MAX_DEPTH); } static void option_active_branches(const char *branches) { max_active_branches = ulong_arg("--active-branches", branches); } static void option_export_marks(const char *marks) { export_marks_file = make_fast_import_path(marks); safe_create_leading_directories_const(export_marks_file); } static void option_cat_blob_fd(const char *fd) { unsigned long n = ulong_arg("--cat-blob-fd", fd); if (n > (unsigned long) INT_MAX) die("--cat-blob-fd cannot exceed %d", INT_MAX); cat_blob_fd = (int) n; } static void option_export_pack_edges(const char *edges) { if (pack_edges) fclose(pack_edges); pack_edges = fopen(edges, "a"); if (!pack_edges) die_errno("Cannot open '%s'", edges); } static int parse_one_option(const char *option) { if (skip_prefix(option, "max-pack-size=", &option)) { unsigned long v; if (!git_parse_ulong(option, &v)) return 0; if (v < 8192) { warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v); v *= 1024 * 1024; } else if (v < 1024 * 1024) { warning("minimum max-pack-size is 1 MiB"); v = 1024 * 1024; } max_packsize = v; } else if (skip_prefix(option, "big-file-threshold=", &option)) { unsigned long v; if (!git_parse_ulong(option, &v)) return 0; big_file_threshold = v; } else if (skip_prefix(option, "depth=", &option)) { option_depth(option); } else if (skip_prefix(option, "active-branches=", &option)) { option_active_branches(option); } else if (skip_prefix(option, "export-pack-edges=", &option)) { option_export_pack_edges(option); } else if (starts_with(option, "quiet")) { show_stats = 0; } else if (starts_with(option, "stats")) { show_stats = 1; } else { return 0; } return 1; } static int parse_one_feature(const char *feature, int from_stream) { const char *arg; if (skip_prefix(feature, "date-format=", &arg)) { option_date_format(arg); } else if (skip_prefix(feature, "import-marks=", &arg)) { option_import_marks(arg, from_stream, 0); } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) { option_import_marks(arg, from_stream, 1); } else if (skip_prefix(feature, "export-marks=", &arg)) { option_export_marks(arg); } else if (!strcmp(feature, "get-mark")) { ; /* Don't die - this feature is supported */ } else if (!strcmp(feature, "cat-blob")) { ; /* Don't die - this feature is supported */ } else if (!strcmp(feature, "relative-marks")) { relative_marks_paths = 1; } else if (!strcmp(feature, "no-relative-marks")) { relative_marks_paths = 0; } else if (!strcmp(feature, "done")) { require_explicit_termination = 1; } else if (!strcmp(feature, "force")) { force_update = 1; } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) { ; /* do nothing; we have the feature */ } else { return 0; } return 1; } static void parse_feature(const char *feature) { if (seen_data_command) die("Got feature command '%s' after data command", feature); if (parse_one_feature(feature, 1)) return; die("This version of fast-import does not support feature %s.", feature); } static void parse_option(const char *option) { if (seen_data_command) die("Got option command '%s' after data command", option); if (parse_one_option(option)) return; die("This version of fast-import does not support option: %s", option); } static void git_pack_config(void) { int indexversion_value; unsigned long packsizelimit_value; if (!git_config_get_ulong("pack.depth", &max_depth)) { if (max_depth > MAX_DEPTH) max_depth = MAX_DEPTH; } if (!git_config_get_int("pack.compression", &pack_compression_level)) { if (pack_compression_level == -1) pack_compression_level = Z_DEFAULT_COMPRESSION; else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION) git_die_config("pack.compression", "bad pack compression level %d", pack_compression_level); pack_compression_seen = 1; } if (!git_config_get_int("pack.indexversion", &indexversion_value)) { pack_idx_opts.version = indexversion_value; if (pack_idx_opts.version > 2) git_die_config("pack.indexversion", "bad pack.indexversion=%"PRIu32, pack_idx_opts.version); } if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value)) max_packsize = packsizelimit_value; git_config(git_default_config, NULL); } static const char fast_import_usage[] = "git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]"; static void parse_argv(void) { unsigned int i; for (i = 1; i < global_argc; i++) { const char *a = global_argv[i]; if (*a != '-' || !strcmp(a, "--")) break; if (!skip_prefix(a, "--", &a)) die("unknown option %s", a); if (parse_one_option(a)) continue; if (parse_one_feature(a, 0)) continue; if (skip_prefix(a, "cat-blob-fd=", &a)) { option_cat_blob_fd(a); continue; } die("unknown option --%s", a); } if (i != global_argc) usage(fast_import_usage); seen_data_command = 1; if (import_marks_file) read_marks(); } int main(int argc, char **argv) { unsigned int i; git_extract_argv0_path(argv[0]); git_setup_gettext(); if (argc == 2 && !strcmp(argv[1], "-h")) usage(fast_import_usage); setup_git_directory(); reset_pack_idx_option(&pack_idx_opts); git_pack_config(); if (!pack_compression_seen && core_compression_seen) pack_compression_level = core_compression_level; alloc_objects(object_entry_alloc); strbuf_init(&command_buf, 0); atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*)); branch_table = xcalloc(branch_table_sz, sizeof(struct branch*)); avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*)); marks = pool_calloc(1, sizeof(struct mark_set)); global_argc = argc; global_argv = argv; rc_free = pool_alloc(cmd_save * sizeof(*rc_free)); for (i = 0; i < (cmd_save - 1); i++) rc_free[i].next = &rc_free[i + 1]; rc_free[cmd_save - 1].next = NULL; prepare_packed_git(); start_packfile(); set_die_routine(die_nicely); set_checkpoint_signal(); while (read_next_command() != EOF) { const char *v; if (!strcmp("blob", command_buf.buf)) parse_new_blob(); else if (skip_prefix(command_buf.buf, "ls ", &v)) parse_ls(v, NULL); else if (skip_prefix(command_buf.buf, "commit ", &v)) parse_new_commit(v); else if (skip_prefix(command_buf.buf, "tag ", &v)) parse_new_tag(v); else if (skip_prefix(command_buf.buf, "reset ", &v)) parse_reset_branch(v); else if (!strcmp("checkpoint", command_buf.buf)) parse_checkpoint(); else if (!strcmp("done", command_buf.buf)) break; else if (starts_with(command_buf.buf, "progress ")) parse_progress(); else if (skip_prefix(command_buf.buf, "feature ", &v)) parse_feature(v); else if (skip_prefix(command_buf.buf, "option git ", &v)) parse_option(v); else if (starts_with(command_buf.buf, "option ")) /* ignore non-git options*/; else die("Unsupported command: %s", command_buf.buf); if (checkpoint_requested) checkpoint(); } /* argv hasn't been parsed yet, do so */ if (!seen_data_command) parse_argv(); if (require_explicit_termination && feof(stdin)) die("stream ends early"); end_packfile(); dump_branches(); dump_tags(); unkeep_all_packs(); dump_marks(); if (pack_edges) fclose(pack_edges); if (show_stats) { uintmax_t total_count = 0, duplicate_count = 0; for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++) total_count += object_count_by_type[i]; for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++) duplicate_count += duplicate_count_by_type[i]; fprintf(stderr, "%s statistics:\n", argv[0]); fprintf(stderr, "---------------------------------------------------------------------\n"); fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count); fprintf(stderr, "Total objects: %10" PRIuMAX " (%10" PRIuMAX " duplicates )\n", total_count, duplicate_count); fprintf(stderr, " blobs : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB], delta_count_attempts_by_type[OBJ_BLOB]); fprintf(stderr, " trees : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE], delta_count_attempts_by_type[OBJ_TREE]); fprintf(stderr, " commits: %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT], delta_count_attempts_by_type[OBJ_COMMIT]); fprintf(stderr, " tags : %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG], delta_count_attempts_by_type[OBJ_TAG]); fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count); fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count); fprintf(stderr, " atoms: %10u\n", atom_cnt); fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024); fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)(total_allocd/1024)); fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024); fprintf(stderr, "---------------------------------------------------------------------\n"); pack_report(); fprintf(stderr, "---------------------------------------------------------------------\n"); fprintf(stderr, "\n"); } return failure ? 1 : 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_4945_1
crossvul-cpp_data_bad_5662_0
/* * net/key/af_key.c An implementation of PF_KEYv2 sockets. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Authors: Maxim Giryaev <gem@asplinux.ru> * David S. Miller <davem@redhat.com> * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * Kazunori MIYAZAWA / USAGI Project <miyazawa@linux-ipv6.org> * Derek Atkins <derek@ihtfp.com> */ #include <linux/capability.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/socket.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/slab.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/xfrm.h> #include <net/sock.h> #define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x)) #define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x)) static int pfkey_net_id __read_mostly; struct netns_pfkey { /* List of all pfkey sockets. */ struct hlist_head table; atomic_t socks_nr; }; static DEFINE_MUTEX(pfkey_mutex); #define DUMMY_MARK 0 static struct xfrm_mark dummy_mark = {0, 0}; struct pfkey_sock { /* struct sock must be the first member of struct pfkey_sock */ struct sock sk; int registered; int promisc; struct { uint8_t msg_version; uint32_t msg_portid; int (*dump)(struct pfkey_sock *sk); void (*done)(struct pfkey_sock *sk); union { struct xfrm_policy_walk policy; struct xfrm_state_walk state; } u; struct sk_buff *skb; } dump; }; static inline struct pfkey_sock *pfkey_sk(struct sock *sk) { return (struct pfkey_sock *)sk; } static int pfkey_can_dump(const struct sock *sk) { if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf) return 1; return 0; } static void pfkey_terminate_dump(struct pfkey_sock *pfk) { if (pfk->dump.dump) { if (pfk->dump.skb) { kfree_skb(pfk->dump.skb); pfk->dump.skb = NULL; } pfk->dump.done(pfk); pfk->dump.dump = NULL; pfk->dump.done = NULL; } } static void pfkey_sock_destruct(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_terminate_dump(pfkey_sk(sk)); skb_queue_purge(&sk->sk_receive_queue); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive pfkey socket: %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); atomic_dec(&net_pfkey->socks_nr); } static const struct proto_ops pfkey_ops; static void pfkey_insert(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); mutex_lock(&pfkey_mutex); sk_add_node_rcu(sk, &net_pfkey->table); mutex_unlock(&pfkey_mutex); } static void pfkey_remove(struct sock *sk) { mutex_lock(&pfkey_mutex); sk_del_node_init_rcu(sk); mutex_unlock(&pfkey_mutex); } static struct proto key_proto = { .name = "KEY", .owner = THIS_MODULE, .obj_size = sizeof(struct pfkey_sock), }; static int pfkey_create(struct net *net, struct socket *sock, int protocol, int kern) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; int err; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (protocol != PF_KEY_V2) return -EPROTONOSUPPORT; err = -ENOMEM; sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto); if (sk == NULL) goto out; sock->ops = &pfkey_ops; sock_init_data(sock, sk); sk->sk_family = PF_KEY; sk->sk_destruct = pfkey_sock_destruct; atomic_inc(&net_pfkey->socks_nr); pfkey_insert(sk); return 0; out: return err; } static int pfkey_release(struct socket *sock) { struct sock *sk = sock->sk; if (!sk) return 0; pfkey_remove(sk); sock_orphan(sk); sock->sk = NULL; skb_queue_purge(&sk->sk_write_queue); synchronize_rcu(); sock_put(sk); return 0; } static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2, gfp_t allocation, struct sock *sk) { int err = -ENOBUFS; sock_hold(sk); if (*skb2 == NULL) { if (atomic_read(&skb->users) != 1) { *skb2 = skb_clone(skb, allocation); } else { *skb2 = skb; atomic_inc(&skb->users); } } if (*skb2 != NULL) { if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) { skb_set_owner_r(*skb2, sk); skb_queue_tail(&sk->sk_receive_queue, *skb2); sk->sk_data_ready(sk, (*skb2)->len); *skb2 = NULL; err = 0; } } sock_put(sk); return err; } /* Send SKB to all pfkey sockets matching selected criteria. */ #define BROADCAST_ALL 0 #define BROADCAST_ONE 1 #define BROADCAST_REGISTERED 2 #define BROADCAST_PROMISC_ONLY 4 static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation, int broadcast_flags, struct sock *one_sk, struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; struct hlist_node *node; struct sk_buff *skb2 = NULL; int err = -ESRCH; /* XXX Do we need something like netlink_overrun? I think * XXX PF_KEY socket apps will not mind current behavior. */ if (!skb) return -ENOMEM; rcu_read_lock(); sk_for_each_rcu(sk, node, &net_pfkey->table) { struct pfkey_sock *pfk = pfkey_sk(sk); int err2; /* Yes, it means that if you are meant to receive this * pfkey message you receive it twice as promiscuous * socket. */ if (pfk->promisc) pfkey_broadcast_one(skb, &skb2, allocation, sk); /* the exact target will be processed later */ if (sk == one_sk) continue; if (broadcast_flags != BROADCAST_ALL) { if (broadcast_flags & BROADCAST_PROMISC_ONLY) continue; if ((broadcast_flags & BROADCAST_REGISTERED) && !pfk->registered) continue; if (broadcast_flags & BROADCAST_ONE) continue; } err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk); /* Error is cleare after succecful sending to at least one * registered KM */ if ((broadcast_flags & BROADCAST_REGISTERED) && err) err = err2; } rcu_read_unlock(); if (one_sk != NULL) err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk); kfree_skb(skb2); kfree_skb(skb); return err; } static int pfkey_do_dump(struct pfkey_sock *pfk) { struct sadb_msg *hdr; int rc; rc = pfk->dump.dump(pfk); if (rc == -ENOBUFS) return 0; if (pfk->dump.skb) { if (!pfkey_can_dump(&pfk->sk)) return 0; hdr = (struct sadb_msg *) pfk->dump.skb->data; hdr->sadb_msg_seq = 0; hdr->sadb_msg_errno = rc; pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = NULL; } pfkey_terminate_dump(pfk); return rc; } static inline void pfkey_hdr_dup(struct sadb_msg *new, const struct sadb_msg *orig) { *new = *orig; } static int pfkey_error(const struct sadb_msg *orig, int err, struct sock *sk) { struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL); struct sadb_msg *hdr; if (!skb) return -ENOBUFS; /* Woe be to the platform trying to support PFKEY yet * having normal errnos outside the 1-255 range, inclusive. */ err = -err; if (err == ERESTARTSYS || err == ERESTARTNOHAND || err == ERESTARTNOINTR) err = EINTR; if (err >= 512) err = EINVAL; BUG_ON(err <= 0 || err >= 256); hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = (uint8_t) err; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static u8 sadb_ext_min_len[] = { [SADB_EXT_RESERVED] = (u8) 0, [SADB_EXT_SA] = (u8) sizeof(struct sadb_sa), [SADB_EXT_LIFETIME_CURRENT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_HARD] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_SOFT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_ADDRESS_SRC] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_DST] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_PROXY] = (u8) sizeof(struct sadb_address), [SADB_EXT_KEY_AUTH] = (u8) sizeof(struct sadb_key), [SADB_EXT_KEY_ENCRYPT] = (u8) sizeof(struct sadb_key), [SADB_EXT_IDENTITY_SRC] = (u8) sizeof(struct sadb_ident), [SADB_EXT_IDENTITY_DST] = (u8) sizeof(struct sadb_ident), [SADB_EXT_SENSITIVITY] = (u8) sizeof(struct sadb_sens), [SADB_EXT_PROPOSAL] = (u8) sizeof(struct sadb_prop), [SADB_EXT_SUPPORTED_AUTH] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SUPPORTED_ENCRYPT] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SPIRANGE] = (u8) sizeof(struct sadb_spirange), [SADB_X_EXT_KMPRIVATE] = (u8) sizeof(struct sadb_x_kmprivate), [SADB_X_EXT_POLICY] = (u8) sizeof(struct sadb_x_policy), [SADB_X_EXT_SA2] = (u8) sizeof(struct sadb_x_sa2), [SADB_X_EXT_NAT_T_TYPE] = (u8) sizeof(struct sadb_x_nat_t_type), [SADB_X_EXT_NAT_T_SPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_DPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_OA] = (u8) sizeof(struct sadb_address), [SADB_X_EXT_SEC_CTX] = (u8) sizeof(struct sadb_x_sec_ctx), [SADB_X_EXT_KMADDRESS] = (u8) sizeof(struct sadb_x_kmaddress), }; /* Verify sadb_address_{len,prefixlen} against sa_family. */ static int verify_address_len(const void *p) { const struct sadb_address *sp = p; const struct sockaddr *addr = (const struct sockaddr *)(sp + 1); const struct sockaddr_in *sin; #if IS_ENABLED(CONFIG_IPV6) const struct sockaddr_in6 *sin6; #endif int len; switch (addr->sa_family) { case AF_INET: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 32) return -EINVAL; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 128) return -EINVAL; break; #endif default: /* It is user using kernel to keep track of security * associations for another protocol, such as * OSPF/RSVP/RIPV2/MIP. It is user's job to verify * lengths. * * XXX Actually, association/policy database is not yet * XXX able to cope with arbitrary sockaddr families. * XXX When it can, remove this -EINVAL. -DaveM */ return -EINVAL; break; } return 0; } static inline int pfkey_sec_ctx_len(const struct sadb_x_sec_ctx *sec_ctx) { return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) + sec_ctx->sadb_x_ctx_len, sizeof(uint64_t)); } static inline int verify_sec_ctx_len(const void *p) { const struct sadb_x_sec_ctx *sec_ctx = p; int len = sec_ctx->sadb_x_ctx_len; if (len > PAGE_SIZE) return -EINVAL; len = pfkey_sec_ctx_len(sec_ctx); if (sec_ctx->sadb_x_sec_len != len) return -EINVAL; return 0; } static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(const struct sadb_x_sec_ctx *sec_ctx) { struct xfrm_user_sec_ctx *uctx = NULL; int ctx_size = sec_ctx->sadb_x_ctx_len; uctx = kmalloc((sizeof(*uctx)+ctx_size), GFP_KERNEL); if (!uctx) return NULL; uctx->len = pfkey_sec_ctx_len(sec_ctx); uctx->exttype = sec_ctx->sadb_x_sec_exttype; uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi; uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg; uctx->ctx_len = sec_ctx->sadb_x_ctx_len; memcpy(uctx + 1, sec_ctx + 1, uctx->ctx_len); return uctx; } static int present_and_same_family(const struct sadb_address *src, const struct sadb_address *dst) { const struct sockaddr *s_addr, *d_addr; if (!src || !dst) return 0; s_addr = (const struct sockaddr *)(src + 1); d_addr = (const struct sockaddr *)(dst + 1); if (s_addr->sa_family != d_addr->sa_family) return 0; if (s_addr->sa_family != AF_INET #if IS_ENABLED(CONFIG_IPV6) && s_addr->sa_family != AF_INET6 #endif ) return 0; return 1; } static int parse_exthdrs(struct sk_buff *skb, const struct sadb_msg *hdr, void **ext_hdrs) { const char *p = (char *) hdr; int len = skb->len; len -= sizeof(*hdr); p += sizeof(*hdr); while (len > 0) { const struct sadb_ext *ehdr = (const struct sadb_ext *) p; uint16_t ext_type; int ext_len; ext_len = ehdr->sadb_ext_len; ext_len *= sizeof(uint64_t); ext_type = ehdr->sadb_ext_type; if (ext_len < sizeof(uint64_t) || ext_len > len || ext_type == SADB_EXT_RESERVED) return -EINVAL; if (ext_type <= SADB_EXT_MAX) { int min = (int) sadb_ext_min_len[ext_type]; if (ext_len < min) return -EINVAL; if (ext_hdrs[ext_type-1] != NULL) return -EINVAL; if (ext_type == SADB_EXT_ADDRESS_SRC || ext_type == SADB_EXT_ADDRESS_DST || ext_type == SADB_EXT_ADDRESS_PROXY || ext_type == SADB_X_EXT_NAT_T_OA) { if (verify_address_len(p)) return -EINVAL; } if (ext_type == SADB_X_EXT_SEC_CTX) { if (verify_sec_ctx_len(p)) return -EINVAL; } ext_hdrs[ext_type-1] = (void *) p; } p += ext_len; len -= ext_len; } return 0; } static uint16_t pfkey_satype2proto(uint8_t satype) { switch (satype) { case SADB_SATYPE_UNSPEC: return IPSEC_PROTO_ANY; case SADB_SATYPE_AH: return IPPROTO_AH; case SADB_SATYPE_ESP: return IPPROTO_ESP; case SADB_X_SATYPE_IPCOMP: return IPPROTO_COMP; break; default: return 0; } /* NOTREACHED */ } static uint8_t pfkey_proto2satype(uint16_t proto) { switch (proto) { case IPPROTO_AH: return SADB_SATYPE_AH; case IPPROTO_ESP: return SADB_SATYPE_ESP; case IPPROTO_COMP: return SADB_X_SATYPE_IPCOMP; break; default: return 0; } /* NOTREACHED */ } /* BTW, this scheme means that there is no way with PFKEY2 sockets to * say specifically 'just raw sockets' as we encode them as 255. */ static uint8_t pfkey_proto_to_xfrm(uint8_t proto) { return proto == IPSEC_PROTO_ANY ? 0 : proto; } static uint8_t pfkey_proto_from_xfrm(uint8_t proto) { return proto ? proto : IPSEC_PROTO_ANY; } static inline int pfkey_sockaddr_len(sa_family_t family) { switch (family) { case AF_INET: return sizeof(struct sockaddr_in); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return sizeof(struct sockaddr_in6); #endif } return 0; } static int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr) { switch (sa->sa_family) { case AF_INET: xaddr->a4 = ((struct sockaddr_in *)sa)->sin_addr.s_addr; return AF_INET; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: memcpy(xaddr->a6, &((struct sockaddr_in6 *)sa)->sin6_addr, sizeof(struct in6_addr)); return AF_INET6; #endif } return 0; } static int pfkey_sadb_addr2xfrm_addr(const struct sadb_address *addr, xfrm_address_t *xaddr) { return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1), xaddr); } static struct xfrm_state *pfkey_xfrm_state_lookup(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs) { const struct sadb_sa *sa; const struct sadb_address *addr; uint16_t proto; unsigned short family; xfrm_address_t *xaddr; sa = ext_hdrs[SADB_EXT_SA - 1]; if (sa == NULL) return NULL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return NULL; /* sadb_address_len should be checked by caller */ addr = ext_hdrs[SADB_EXT_ADDRESS_DST - 1]; if (addr == NULL) return NULL; family = ((const struct sockaddr *)(addr + 1))->sa_family; switch (family) { case AF_INET: xaddr = (xfrm_address_t *)&((const struct sockaddr_in *)(addr + 1))->sin_addr; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: xaddr = (xfrm_address_t *)&((const struct sockaddr_in6 *)(addr + 1))->sin6_addr; break; #endif default: xaddr = NULL; } if (!xaddr) return NULL; return xfrm_state_lookup(net, DUMMY_MARK, xaddr, sa->sadb_sa_spi, proto, family); } #define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1))) static int pfkey_sockaddr_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family)); } static inline int pfkey_mode_from_xfrm(int mode) { switch(mode) { case XFRM_MODE_TRANSPORT: return IPSEC_MODE_TRANSPORT; case XFRM_MODE_TUNNEL: return IPSEC_MODE_TUNNEL; case XFRM_MODE_BEET: return IPSEC_MODE_BEET; default: return -1; } } static inline int pfkey_mode_to_xfrm(int mode) { switch(mode) { case IPSEC_MODE_ANY: /*XXX*/ case IPSEC_MODE_TRANSPORT: return XFRM_MODE_TRANSPORT; case IPSEC_MODE_TUNNEL: return XFRM_MODE_TUNNEL; case IPSEC_MODE_BEET: return XFRM_MODE_BEET; default: return -1; } } static unsigned int pfkey_sockaddr_fill(const xfrm_address_t *xaddr, __be16 port, struct sockaddr *sa, unsigned short family) { switch (family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)sa; sin->sin_family = AF_INET; sin->sin_port = port; sin->sin_addr.s_addr = xaddr->a4; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); return 32; } #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; sin6->sin6_family = AF_INET6; sin6->sin6_port = port; sin6->sin6_flowinfo = 0; sin6->sin6_addr = *(struct in6_addr *)xaddr->a6; sin6->sin6_scope_id = 0; return 128; } #endif } return 0; } static struct sk_buff *__pfkey_xfrm_state2msg(const struct xfrm_state *x, int add_keys, int hsc) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_lifetime *lifetime; struct sadb_address *addr; struct sadb_key *key; struct sadb_x_sa2 *sa2; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; int size; int auth_key_size = 0; int encrypt_key_size = 0; int sockaddr_size; struct xfrm_encap_tmpl *natt = NULL; int mode; /* address family check */ sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return ERR_PTR(-EINVAL); /* base, SA, (lifetime (HSC),) address(SD), (address(P),) key(AE), (identity(SD),) (sensitivity)> */ size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) + sizeof(struct sadb_lifetime) + ((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) + ((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) + sizeof(struct sadb_address)*2 + sockaddr_size*2 + sizeof(struct sadb_x_sa2); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } /* identity & sensitivity */ if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family)) size += sizeof(struct sadb_address) + sockaddr_size; if (add_keys) { if (x->aalg && x->aalg->alg_key_len) { auth_key_size = PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8); size += sizeof(struct sadb_key) + auth_key_size; } if (x->ealg && x->ealg->alg_key_len) { encrypt_key_size = PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8); size += sizeof(struct sadb_key) + encrypt_key_size; } } if (x->encap) natt = x->encap; if (natt && natt->encap_type) { size += sizeof(struct sadb_x_nat_t_type); size += sizeof(struct sadb_x_nat_t_port); size += sizeof(struct sadb_x_nat_t_port); } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ hdr->sadb_msg_len = size / sizeof(uint64_t); /* sa */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = x->props.replay_window; switch (x->km.state) { case XFRM_STATE_VALID: sa->sadb_sa_state = x->km.dying ? SADB_SASTATE_DYING : SADB_SASTATE_MATURE; break; case XFRM_STATE_ACQ: sa->sadb_sa_state = SADB_SASTATE_LARVAL; break; default: sa->sadb_sa_state = SADB_SASTATE_DEAD; break; } sa->sadb_sa_auth = 0; if (x->aalg) { struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0); sa->sadb_sa_auth = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_encrypt = 0; BUG_ON(x->ealg && x->calg); if (x->ealg) { struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0); sa->sadb_sa_encrypt = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } /* KAME compatible: sadb_sa_encrypt is overloaded with calg id */ if (x->calg) { struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0); sa->sadb_sa_encrypt = (a && a->pfkey_supported) ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_flags = 0; if (x->props.flags & XFRM_STATE_NOECN) sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN; if (x->props.flags & XFRM_STATE_DECAP_DSCP) sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP; if (x->props.flags & XFRM_STATE_NOPMTUDISC) sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC; /* hard time */ if (hsc & 2) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds; } /* soft time */ if (hsc & 1) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds; } /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = x->curlft.packets; lifetime->sadb_lifetime_bytes = x->curlft.bytes; lifetime->sadb_lifetime_addtime = x->curlft.add_time; lifetime->sadb_lifetime_usetime = x->curlft.use_time; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; /* "if the ports are non-zero, then the sadb_address_proto field, normally zero, MUST be filled in with the transport protocol's number." - RFC2367 */ addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family)) { addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY; addr->sadb_address_proto = pfkey_proto_from_xfrm(x->sel.proto); addr->sadb_address_prefixlen = x->sel.prefixlen_s; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport, (struct sockaddr *) (addr + 1), x->props.family); } /* auth key */ if (add_keys && auth_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+auth_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_AUTH; key->sadb_key_bits = x->aalg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8); } /* encrypt key */ if (add_keys && encrypt_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+encrypt_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + encrypt_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT; key->sadb_key_bits = x->ealg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->ealg->alg_key, (x->ealg->alg_key_len+7)/8); } /* sa */ sa2 = (struct sadb_x_sa2 *) skb_put(skb, sizeof(struct sadb_x_sa2)); sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t); sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2; if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) { kfree_skb(skb); return ERR_PTR(-EINVAL); } sa2->sadb_x_sa2_mode = mode; sa2->sadb_x_sa2_reserved1 = 0; sa2->sadb_x_sa2_reserved2 = 0; sa2->sadb_x_sa2_sequence = 0; sa2->sadb_x_sa2_reqid = x->props.reqid; if (natt && natt->encap_type) { struct sadb_x_nat_t_type *n_type; struct sadb_x_nat_t_port *n_port; /* type */ n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type)); n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t); n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE; n_type->sadb_x_nat_t_type_type = natt->encap_type; n_type->sadb_x_nat_t_type_reserved[0] = 0; n_type->sadb_x_nat_t_type_reserved[1] = 0; n_type->sadb_x_nat_t_type_reserved[2] = 0; /* source port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* dest port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = natt->encap_dport; n_port->sadb_x_nat_t_port_reserved = 0; } /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg(const struct xfrm_state *x) { struct sk_buff *skb; skb = __pfkey_xfrm_state2msg(x, 1, 3); return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg_expire(const struct xfrm_state *x, int hsc) { return __pfkey_xfrm_state2msg(x, 0, hsc); } static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct xfrm_state *x; const struct sadb_lifetime *lifetime; const struct sadb_sa *sa; const struct sadb_key *key; const struct sadb_x_sec_ctx *sec_ctx; uint16_t proto; int err; sa = ext_hdrs[SADB_EXT_SA - 1]; if (!sa || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_ESP && !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_AH && !ext_hdrs[SADB_EXT_KEY_AUTH-1]) return ERR_PTR(-EINVAL); if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] != !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) return ERR_PTR(-EINVAL); proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return ERR_PTR(-EINVAL); /* default error is no buffer space */ err = -ENOBUFS; /* RFC2367: Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message. SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state. Therefore, the sadb_sa_state field of all submitted SAs MUST be SADB_SASTATE_MATURE and the kernel MUST return an error if this is not true. However, KAME setkey always uses SADB_SASTATE_LARVAL. Hence, we have to _ignore_ sadb_sa_state, which is also reasonable. */ if (sa->sadb_sa_auth > SADB_AALG_MAX || (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP && sa->sadb_sa_encrypt > SADB_X_CALG_MAX) || sa->sadb_sa_encrypt > SADB_EALG_MAX) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; if (key != NULL && sa->sadb_sa_auth != SADB_X_AALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key != NULL && sa->sadb_sa_encrypt != SADB_EALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); x = xfrm_state_alloc(net); if (x == NULL) return ERR_PTR(-ENOBUFS); x->id.proto = proto; x->id.spi = sa->sadb_sa_spi; x->props.replay_window = sa->sadb_sa_replay; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN) x->props.flags |= XFRM_STATE_NOECN; if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP) x->props.flags |= XFRM_STATE_DECAP_DSCP; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC) x->props.flags |= XFRM_STATE_NOPMTUDISC; lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1]; if (lifetime != NULL) { x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1]; if (lifetime != NULL) { x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) goto out; err = security_xfrm_state_alloc(x, uctx); kfree(uctx); if (err) goto out; } key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; if (sa->sadb_sa_auth) { int keysize = 0; struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } if (key) keysize = (key->sadb_key_bits + 7) / 8; x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL); if (!x->aalg) goto out; strcpy(x->aalg->alg_name, a->name); x->aalg->alg_key_len = 0; if (key) { x->aalg->alg_key_len = key->sadb_key_bits; memcpy(x->aalg->alg_key, key+1, keysize); } x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits; x->props.aalgo = sa->sadb_sa_auth; /* x->algo.flags = sa->sadb_sa_flags; */ } if (sa->sadb_sa_encrypt) { if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) { struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL); if (!x->calg) goto out; strcpy(x->calg->alg_name, a->name); x->props.calgo = sa->sadb_sa_encrypt; } else { int keysize = 0; struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt); if (!a || !a->pfkey_supported) { err = -ENOSYS; goto out; } key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key) keysize = (key->sadb_key_bits + 7) / 8; x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL); if (!x->ealg) goto out; strcpy(x->ealg->alg_name, a->name); x->ealg->alg_key_len = 0; if (key) { x->ealg->alg_key_len = key->sadb_key_bits; memcpy(x->ealg->alg_key, key+1, keysize); } x->props.ealgo = sa->sadb_sa_encrypt; } } /* x->algo.flags = sa->sadb_sa_flags; */ x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1], &x->props.saddr); if (!x->props.family) { err = -EAFNOSUPPORT; goto out; } pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1], &x->id.daddr); if (ext_hdrs[SADB_X_EXT_SA2-1]) { const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1]; int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) { err = -EINVAL; goto out; } x->props.mode = mode; x->props.reqid = sa2->sadb_x_sa2_reqid; } if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) { const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]; /* Nobody uses this, but we try. */ x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr); x->sel.prefixlen_s = addr->sadb_address_prefixlen; } if (!x->sel.family) x->sel.family = x->props.family; if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) { const struct sadb_x_nat_t_type* n_type; struct xfrm_encap_tmpl *natt; x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL); if (!x->encap) goto out; natt = x->encap; n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]; natt->encap_type = n_type->sadb_x_nat_t_type_type; if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) { const struct sadb_x_nat_t_port *n_port = ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]; natt->encap_sport = n_port->sadb_x_nat_t_port_port; } if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) { const struct sadb_x_nat_t_port *n_port = ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]; natt->encap_dport = n_port->sadb_x_nat_t_port_port; } memset(&natt->encap_oa, 0, sizeof(natt->encap_oa)); } err = xfrm_init_state(x); if (err) goto out; x->km.seq = hdr->sadb_msg_seq; return x; out: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); return ERR_PTR(err); } static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { return -EOPNOTSUPP; } static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct sk_buff *resp_skb; struct sadb_x_sa2 *sa2; struct sadb_address *saddr, *daddr; struct sadb_msg *out_hdr; struct sadb_spirange *range; struct xfrm_state *x = NULL; int mode; int err; u32 min_spi, max_spi; u32 reqid; u8 proto; unsigned short family; xfrm_address_t *xsaddr = NULL, *xdaddr = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) { mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) return -EINVAL; reqid = sa2->sadb_x_sa2_reqid; } else { mode = 0; reqid = 0; } saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1]; daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1]; family = ((struct sockaddr *)(saddr + 1))->sa_family; switch (family) { case AF_INET: xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr; break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr; break; #endif } if (hdr->sadb_msg_seq) { x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x && !xfrm_addr_equal(&x->id.daddr, xdaddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, &dummy_mark, mode, reqid, proto, xdaddr, xsaddr, 1, family); if (x == NULL) return -ENOENT; min_spi = 0x100; max_spi = 0x0fffffff; range = ext_hdrs[SADB_EXT_SPIRANGE-1]; if (range) { min_spi = range->sadb_spirange_min; max_spi = range->sadb_spirange_max; } err = xfrm_alloc_spi(x, min_spi, max_spi); resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x); if (IS_ERR(resp_skb)) { xfrm_state_put(x); return PTR_ERR(resp_skb); } out_hdr = (struct sadb_msg *) resp_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GETSPI; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; xfrm_state_put(x); pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net); return 0; } static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8) return -EOPNOTSUPP; if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0) return 0; x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq); if (x == NULL) return 0; spin_lock_bh(&x->lock); if (x->km.state == XFRM_STATE_ACQ) { x->km.state = XFRM_STATE_ERROR; wake_up(&net->xfrm.km_waitq); } spin_unlock_bh(&x->lock); xfrm_state_put(x); return 0; } static inline int event2poltype(int event) { switch (event) { case XFRM_MSG_DELPOLICY: return SADB_X_SPDDELETE; case XFRM_MSG_NEWPOLICY: return SADB_X_SPDADD; case XFRM_MSG_UPDPOLICY: return SADB_X_SPDUPDATE; case XFRM_MSG_POLEXPIRE: // return SADB_X_SPDEXPIRE; default: pr_err("pfkey: Unknown policy event %d\n", event); break; } return 0; } static inline int event2keytype(int event) { switch (event) { case XFRM_MSG_DELSA: return SADB_DELETE; case XFRM_MSG_NEWSA: return SADB_ADD; case XFRM_MSG_UPDSA: return SADB_UPDATE; case XFRM_MSG_EXPIRE: return SADB_EXPIRE; default: pr_err("pfkey: Unknown SA event %d\n", event); break; } return 0; } /* ADD/UPD/DEL */ static int key_notify_sa(struct xfrm_state *x, const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = pfkey_xfrm_state2msg(x); if (IS_ERR(skb)) return PTR_ERR(skb); hdr = (struct sadb_msg *) skb->data; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = event2keytype(c->event); hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x)); return 0; } static int pfkey_add(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; int err; struct km_event c; x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs); if (IS_ERR(x)) return PTR_ERR(x); xfrm_state_hold(x); if (hdr->sadb_msg_type == SADB_ADD) err = xfrm_state_add(x); else err = xfrm_state_update(x); xfrm_audit_state_add(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } if (hdr->sadb_msg_type == SADB_ADD) c.event = XFRM_MSG_NEWSA; else c.event = XFRM_MSG_UPDSA; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static int pfkey_delete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; struct km_event c; int err; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; if ((err = security_xfrm_state_delete(x))) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.event = XFRM_MSG_DELSA; km_state_notify(x, &c); out: xfrm_audit_state_delete(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); xfrm_state_put(x); return err; } static int pfkey_get(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); __u8 proto; struct sk_buff *out_skb; struct sadb_msg *out_hdr; struct xfrm_state *x; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; out_skb = pfkey_xfrm_state2msg(x); proto = x->id.proto; xfrm_state_put(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GET; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static struct sk_buff *compose_sadb_supported(const struct sadb_msg *orig, gfp_t allocation) { struct sk_buff *skb; struct sadb_msg *hdr; int len, auth_len, enc_len, i; auth_len = xfrm_count_pfkey_auth_supported(); if (auth_len) { auth_len *= sizeof(struct sadb_alg); auth_len += sizeof(struct sadb_supported); } enc_len = xfrm_count_pfkey_enc_supported(); if (enc_len) { enc_len *= sizeof(struct sadb_alg); enc_len += sizeof(struct sadb_supported); } len = enc_len + auth_len + sizeof(struct sadb_msg); skb = alloc_skb(len + 16, allocation); if (!skb) goto out_put_algs; hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = 0; hdr->sadb_msg_len = len / sizeof(uint64_t); if (auth_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, auth_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = auth_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH; for (i = 0; ; i++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg->available) *ap++ = aalg->desc; } } if (enc_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, enc_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = enc_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT; for (i = 0; ; i++) { struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (ealg->available) *ap++ = ealg->desc; } } out_put_algs: return skb; } static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; } static int unicast_flush_resp(struct sock *sk, const struct sadb_msg *ihdr) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memcpy(hdr, ihdr, sizeof(struct sadb_msg)); hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); } static int key_notify_sa_flush(const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto); hdr->sadb_msg_type = SADB_FLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_flush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); unsigned int proto; struct km_event c; struct xfrm_audit audit_info; int err, err2; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_state_flush(net, proto, &audit_info); err2 = unicast_flush_resp(sk, hdr); if (err || err2) { if (err == -ESRCH) /* empty table - go quietly */ err = 0; return err ? err : err2; } c.data.proto = proto; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.event = XFRM_MSG_FLUSHSA; c.net = net; km_state_notify(NULL, &c); return 0; } static int dump_sa(struct xfrm_state *x, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_state2msg(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_DUMP; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_portid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sa(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk); } static void pfkey_dump_sa_done(struct pfkey_sock *pfk) { xfrm_state_walk_done(&pfk->dump.u.state); } static int pfkey_dump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { u8 proto; struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_portid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sa; pfk->dump.done = pfkey_dump_sa_done; xfrm_state_walk_init(&pfk->dump.u.state, proto); return pfkey_do_dump(pfk); } static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); int satype = hdr->sadb_msg_satype; bool reset_errno = false; if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) { reset_errno = true; if (satype != 0 && satype != 1) return -EINVAL; pfk->promisc = satype; } if (reset_errno && skb_cloned(skb)) skb = skb_copy(skb, GFP_KERNEL); else skb = skb_clone(skb, GFP_KERNEL); if (reset_errno && skb) { struct sadb_msg *new_hdr = (struct sadb_msg *) skb->data; new_hdr->sadb_msg_errno = 0; } pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk)); return 0; } static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr) { int i; u32 reqid = *(u32*)ptr; for (i=0; i<xp->xfrm_nr; i++) { if (xp->xfrm_vec[i].reqid == reqid) return -EEXIST; } return 0; } static u32 gen_reqid(struct net *net) { struct xfrm_policy_walk walk; u32 start; int rc; static u32 reqid = IPSEC_MANUAL_REQID_MAX; start = reqid; do { ++reqid; if (reqid == 0) reqid = IPSEC_MANUAL_REQID_MAX+1; xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN); rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid); xfrm_policy_walk_done(&walk); if (rc != -EEXIST) return reqid; } while (reqid != start); return 0; } static int parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq) { struct net *net = xp_net(xp); struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr; int mode; if (xp->xfrm_nr >= XFRM_MAX_DEPTH) return -ELOOP; if (rq->sadb_x_ipsecrequest_mode == 0) return -EINVAL; t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */ if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; t->mode = mode; if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE) t->optional = 1; else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) { t->reqid = rq->sadb_x_ipsecrequest_reqid; if (t->reqid > IPSEC_MANUAL_REQID_MAX) t->reqid = 0; if (!t->reqid && !(t->reqid = gen_reqid(net))) return -ENOBUFS; } /* addresses present only in tunnel mode */ if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (u8 *) (rq + 1); int family, socklen; family = pfkey_sockaddr_extract((struct sockaddr *)sa, &t->saddr); if (!family) return -EINVAL; socklen = pfkey_sockaddr_len(family); if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen), &t->id.daddr) != family) return -EINVAL; t->encap_family = family; } else t->encap_family = xp->family; /* No way to set this via kame pfkey */ t->allalgs = 1; xp->xfrm_nr++; return 0; } static int parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol) { int err; int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy); struct sadb_x_ipsecrequest *rq = (void*)(pol+1); if (pol->sadb_x_policy_len * 8 < sizeof(struct sadb_x_policy)) return -EINVAL; while (len >= sizeof(struct sadb_x_ipsecrequest)) { if ((err = parse_ipsecrequest(xp, rq)) < 0) return err; len -= rq->sadb_x_ipsecrequest_len; rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len); } return 0; } static inline int pfkey_xfrm_policy2sec_ctx_size(const struct xfrm_policy *xp) { struct xfrm_sec_ctx *xfrm_ctx = xp->security; if (xfrm_ctx) { int len = sizeof(struct sadb_x_sec_ctx); len += xfrm_ctx->ctx_len; return PFKEY_ALIGN8(len); } return 0; } static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp) { const struct xfrm_tmpl *t; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = 0; int i; for (i=0; i<xp->xfrm_nr; i++) { t = xp->xfrm_vec + i; socklen += pfkey_sockaddr_len(t->encap_family); } return sizeof(struct sadb_msg) + (sizeof(struct sadb_lifetime) * 3) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy) + (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) + (socklen * 2) + pfkey_xfrm_policy2sec_ctx_size(xp); } static struct sk_buff * pfkey_xfrm_policy2msg_prep(const struct xfrm_policy *xp) { struct sk_buff *skb; int size; size = pfkey_xfrm_policy2msg_size(xp); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); return skb; } static int pfkey_xfrm_policy2msg(struct sk_buff *skb, const struct xfrm_policy *xp, int dir) { struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_lifetime *lifetime; struct sadb_x_policy *pol; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int i; int size; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = pfkey_sockaddr_len(xp->family); size = pfkey_xfrm_policy2msg_size(xp); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_s; addr->sadb_address_reserved = 0; if (!pfkey_sockaddr_fill(&xp->selector.saddr, xp->selector.sport, (struct sockaddr *) (addr + 1), xp->family)) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_d; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport, (struct sockaddr *) (addr + 1), xp->family); /* hard time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds; /* soft time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds; /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = xp->curlft.packets; lifetime->sadb_lifetime_bytes = xp->curlft.bytes; lifetime->sadb_lifetime_addtime = xp->curlft.add_time; lifetime->sadb_lifetime_usetime = xp->curlft.use_time; pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD; if (xp->action == XFRM_POLICY_ALLOW) { if (xp->xfrm_nr) pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; else pol->sadb_x_policy_type = IPSEC_POLICY_NONE; } pol->sadb_x_policy_dir = dir+1; pol->sadb_x_policy_id = xp->index; pol->sadb_x_policy_priority = xp->priority; for (i=0; i<xp->xfrm_nr; i++) { const struct xfrm_tmpl *t = xp->xfrm_vec + i; struct sadb_x_ipsecrequest *rq; int req_size; int mode; req_size = sizeof(struct sadb_x_ipsecrequest); if (t->mode == XFRM_MODE_TUNNEL) { socklen = pfkey_sockaddr_len(t->encap_family); req_size += socklen * 2; } else { size -= 2*socklen; } rq = (void*)skb_put(skb, req_size); pol->sadb_x_policy_len += req_size/8; memset(rq, 0, sizeof(*rq)); rq->sadb_x_ipsecrequest_len = req_size; rq->sadb_x_ipsecrequest_proto = t->id.proto; if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0) return -EINVAL; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE; if (t->reqid) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE; if (t->optional) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE; rq->sadb_x_ipsecrequest_reqid = t->reqid; if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (void *)(rq + 1); pfkey_sockaddr_fill(&t->saddr, 0, (struct sockaddr *)sa, t->encap_family); pfkey_sockaddr_fill(&t->id.daddr, 0, (struct sockaddr *) (sa + socklen), t->encap_family); } } /* security context */ if ((xfrm_ctx = xp->security)) { int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp); sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size); sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_reserved = atomic_read(&xp->refcnt); return 0; } static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; if (c->data.byid && c->event == XFRM_MSG_DELPOLICY) out_hdr->sadb_msg_type = SADB_X_SPDDELETE2; else out_hdr->sadb_msg_type = event2poltype(c->event); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = c->seq; out_hdr->sadb_msg_pid = c->portid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp)); return 0; } static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); int err = 0; struct sadb_lifetime *lifetime; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC) return -EINVAL; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; xp = xfrm_policy_alloc(net, GFP_KERNEL); if (xp == NULL) return -ENOBUFS; xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->priority = pol->sadb_x_policy_priority; sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr); if (!xp->family) { err = -EINVAL; goto out; } xp->selector.family = xp->family; xp->selector.prefixlen_s = sa->sadb_address_prefixlen; xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.sport) xp->selector.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr); xp->selector.prefixlen_d = sa->sadb_address_prefixlen; /* Amusing, we set this twice. KAME apps appear to set same value * in both addresses. */ xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.dport) xp->selector.dport_mask = htons(0xffff); sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) { err = -ENOBUFS; goto out; } err = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (err) goto out; } xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) { xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) { xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (err = parse_ipsecrequests(xp, pol)) < 0) goto out; err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp, hdr->sadb_msg_type != SADB_X_SPDUPDATE); xfrm_audit_policy_add(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; if (hdr->sadb_msg_type == SADB_X_SPDUPDATE) c.event = XFRM_MSG_UPDPOLICY; else c.event = XFRM_MSG_NEWPOLICY; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); xfrm_pol_put(xp); return 0; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return err; } static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); int err; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct xfrm_selector sel; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *pol_ctx = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; memset(&sel, 0, sizeof(sel)); sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) return -ENOMEM; err = security_xfrm_policy_alloc(&pol_ctx, uctx); kfree(uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN, pol->sadb_x_policy_dir - 1, &sel, pol_ctx, 1, &err); security_xfrm_policy_free(pol_ctx); if (xp == NULL) return -ENOENT; xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.data.byid = 0; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); out: xfrm_pol_put(xp); return err; } static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, const struct sadb_msg *hdr, int dir) { int err; struct sk_buff *out_skb; struct sadb_msg *out_hdr; err = 0; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) { err = PTR_ERR(out_skb); goto out; } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) goto out; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = hdr->sadb_msg_type; out_hdr->sadb_msg_satype = 0; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp)); err = 0; out: return err; } #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_sockaddr_pair_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2); } static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len, xfrm_address_t *saddr, xfrm_address_t *daddr, u16 *family) { int af, socklen; if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family)) return -EINVAL; af = pfkey_sockaddr_extract(sa, saddr); if (!af) return -EINVAL; socklen = pfkey_sockaddr_len(af); if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen), daddr) != af) return -EINVAL; *family = af; return 0; } static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len, struct xfrm_migrate *m) { int err; struct sadb_x_ipsecrequest *rq2; int mode; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq1->sadb_x_ipsecrequest_len) return -EINVAL; /* old endoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1), rq1->sadb_x_ipsecrequest_len, &m->old_saddr, &m->old_daddr, &m->old_family); if (err) return err; rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len); len -= rq1->sadb_x_ipsecrequest_len; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq2->sadb_x_ipsecrequest_len) return -EINVAL; /* new endpoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1), rq2->sadb_x_ipsecrequest_len, &m->new_saddr, &m->new_daddr, &m->new_family); if (err) return err; if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto || rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode || rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid) return -EINVAL; m->proto = rq1->sadb_x_ipsecrequest_proto; if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; m->mode = mode; m->reqid = rq1->sadb_x_ipsecrequest_reqid; return ((int)(rq1->sadb_x_ipsecrequest_len + rq2->sadb_x_ipsecrequest_len)); } static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { int i, len, ret, err = -EINVAL; u8 dir; struct sadb_address *sa; struct sadb_x_kmaddress *kma; struct sadb_x_policy *pol; struct sadb_x_ipsecrequest *rq; struct xfrm_selector sel; struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress k; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1], ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) || !ext_hdrs[SADB_X_EXT_POLICY - 1]) { err = -EINVAL; goto out; } kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1]; pol = ext_hdrs[SADB_X_EXT_POLICY - 1]; if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) { err = -EINVAL; goto out; } if (kma) { /* convert sadb_x_kmaddress to xfrm_kmaddress */ k.reserved = kma->sadb_x_kmaddress_reserved; ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1), 8*(kma->sadb_x_kmaddress_len) - sizeof(*kma), &k.local, &k.remote, &k.family); if (ret < 0) { err = ret; goto out; } } dir = pol->sadb_x_policy_dir - 1; memset(&sel, 0, sizeof(sel)); /* set source address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1]; sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); /* set destination address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); rq = (struct sadb_x_ipsecrequest *)(pol + 1); /* extract ipsecrequests */ i = 0; len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy); while (len > 0 && i < XFRM_MAX_DEPTH) { ret = ipsecrequests_to_migrate(rq, len, &m[i]); if (ret < 0) { err = ret; goto out; } else { rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret); len -= ret; i++; } } if (!i || len > 0) { err = -EINVAL; goto out; } return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i, kma ? &k : NULL); out: return err; } #else static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { return -ENOPROTOOPT; } #endif static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); unsigned int dir; int err = 0, delete; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL) return -EINVAL; dir = xfrm_policy_id2dir(pol->sadb_x_policy_id); if (dir >= XFRM_POLICY_MAX) return -EINVAL; delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2); xp = xfrm_policy_byid(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN, dir, pol->sadb_x_policy_id, delete, &err); if (xp == NULL) return -ENOENT; if (delete) { xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.portid = hdr->sadb_msg_pid; c.data.byid = 1; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, dir, &c); } else { err = key_pol_get_resp(sk, xp, hdr, dir); } out: xfrm_pol_put(xp); return err; } static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_X_SPDDUMP; out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_portid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sp(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk); } static void pfkey_dump_sp_done(struct pfkey_sock *pfk) { xfrm_policy_walk_done(&pfk->dump.u.policy); } static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_portid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sp; pfk->dump.done = pfkey_dump_sp_done; xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN); return pfkey_do_dump(pfk); } static int key_notify_policy_flush(const struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs) { struct net *net = sock_net(sk); struct km_event c; struct xfrm_audit audit_info; int err, err2; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info); err2 = unicast_flush_resp(sk, hdr); if (err || err2) { if (err == -ESRCH) /* empty table - old silent behavior */ return 0; return err; } c.data.type = XFRM_POLICY_TYPE_MAIN; c.event = XFRM_MSG_FLUSHPOLICY; c.portid = hdr->sadb_msg_pid; c.seq = hdr->sadb_msg_seq; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs); static pfkey_handler pfkey_funcs[SADB_MAX + 1] = { [SADB_RESERVED] = pfkey_reserved, [SADB_GETSPI] = pfkey_getspi, [SADB_UPDATE] = pfkey_add, [SADB_ADD] = pfkey_add, [SADB_DELETE] = pfkey_delete, [SADB_GET] = pfkey_get, [SADB_ACQUIRE] = pfkey_acquire, [SADB_REGISTER] = pfkey_register, [SADB_EXPIRE] = NULL, [SADB_FLUSH] = pfkey_flush, [SADB_DUMP] = pfkey_dump, [SADB_X_PROMISC] = pfkey_promisc, [SADB_X_PCHANGE] = NULL, [SADB_X_SPDUPDATE] = pfkey_spdadd, [SADB_X_SPDADD] = pfkey_spdadd, [SADB_X_SPDDELETE] = pfkey_spddelete, [SADB_X_SPDGET] = pfkey_spdget, [SADB_X_SPDACQUIRE] = NULL, [SADB_X_SPDDUMP] = pfkey_spddump, [SADB_X_SPDFLUSH] = pfkey_spdflush, [SADB_X_SPDSETIDX] = pfkey_spdadd, [SADB_X_SPDDELETE2] = pfkey_spdget, [SADB_X_MIGRATE] = pfkey_migrate, }; static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr) { void *ext_hdrs[SADB_EXT_MAX]; int err; pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_PROMISC_ONLY, NULL, sock_net(sk)); memset(ext_hdrs, 0, sizeof(ext_hdrs)); err = parse_exthdrs(skb, hdr, ext_hdrs); if (!err) { err = -EOPNOTSUPP; if (pfkey_funcs[hdr->sadb_msg_type]) err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs); } return err; } static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp) { struct sadb_msg *hdr = NULL; if (skb->len < sizeof(*hdr)) { *errp = -EMSGSIZE; } else { hdr = (struct sadb_msg *) skb->data; if (hdr->sadb_msg_version != PF_KEY_V2 || hdr->sadb_msg_reserved != 0 || (hdr->sadb_msg_type <= SADB_RESERVED || hdr->sadb_msg_type > SADB_MAX)) { hdr = NULL; *errp = -EINVAL; } else if (hdr->sadb_msg_len != (skb->len / sizeof(uint64_t)) || hdr->sadb_msg_len < (sizeof(struct sadb_msg) / sizeof(uint64_t))) { hdr = NULL; *errp = -EMSGSIZE; } else { *errp = 0; } } return hdr; } static inline int aalg_tmpl_set(const struct xfrm_tmpl *t, const struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->aalgos) * 8) return 0; return (t->aalgos >> id) & 1; } static inline int ealg_tmpl_set(const struct xfrm_tmpl *t, const struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->ealgos) * 8) return 0; return (t->ealgos >> id) & 1; } static int count_ah_combs(const struct xfrm_tmpl *t) { int i, sz = 0; for (i = 0; ; i++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } return sz + sizeof(struct sadb_prop); } static int count_esp_combs(const struct xfrm_tmpl *t) { int i, k, sz = 0; for (i = 0; ; i++) { const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } } return sz + sizeof(struct sadb_prop); } static void dump_ah_combs(struct sk_buff *skb, const struct xfrm_tmpl *t) { struct sadb_prop *p; int i; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i = 0; ; i++) { const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (aalg_tmpl_set(t, aalg) && aalg->available) { struct sadb_comb *c; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static void dump_esp_combs(struct sk_buff *skb, const struct xfrm_tmpl *t) { struct sadb_prop *p; int i, k; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i=0; ; i++) { const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!ealg->pfkey_supported) continue; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { struct sadb_comb *c; const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!aalg->pfkey_supported) continue; if (!(aalg_tmpl_set(t, aalg) && aalg->available)) continue; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_encrypt = ealg->desc.sadb_alg_id; c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits; c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static int key_notify_policy_expire(struct xfrm_policy *xp, const struct km_event *c) { return 0; } static int key_notify_sa_expire(struct xfrm_state *x, const struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int hard; int hsc; hard = c->data.hard; if (hard) hsc = 2; else hsc = 1; out_skb = pfkey_xfrm_state2msg_expire(x, hsc); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; out_hdr->sadb_msg_type = SADB_EXPIRE; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = 0; out_hdr->sadb_msg_pid = 0; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); return 0; } static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = x ? xs_net(x) : c->net; struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); if (atomic_read(&net_pfkey->socks_nr) == 0) return 0; switch (c->event) { case XFRM_MSG_EXPIRE: return key_notify_sa_expire(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_NEWSA: case XFRM_MSG_UPDSA: return key_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return key_notify_sa_flush(c); case XFRM_MSG_NEWAE: /* not yet supported */ break; default: pr_err("pfkey: Unknown SA event %d\n", c->event); break; } return 0; } static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { if (xp && xp->type != XFRM_POLICY_TYPE_MAIN) return 0; switch (c->event) { case XFRM_MSG_POLEXPIRE: return key_notify_policy_expire(xp, c); case XFRM_MSG_DELPOLICY: case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: return key_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: if (c->data.type != XFRM_POLICY_TYPE_MAIN) break; return key_notify_policy_flush(c); default: pr_err("pfkey: Unknown policy event %d\n", c->event); break; } return 0; } static u32 get_acqseq(void) { u32 res; static atomic_t acqseq; do { res = atomic_inc_return(&acqseq); } while (!res); return res; } static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_x_policy *pol; int sockaddr_size; int size; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; size = sizeof(struct sadb_msg) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy); if (x->id.proto == IPPROTO_AH) size += count_ah_combs(t); else if (x->id.proto == IPPROTO_ESP) size += count_esp_combs(t); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_ACQUIRE; hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = XFRM_POLICY_OUT + 1; pol->sadb_x_policy_id = xp->index; /* Set sadb_comb's. */ if (x->id.proto == IPPROTO_AH) dump_ah_combs(skb, t); else if (x->id.proto == IPPROTO_ESP) dump_esp_combs(skb, t); /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_policy *xp; struct sadb_x_policy *pol = (struct sadb_x_policy*)data; struct sadb_x_sec_ctx *sec_ctx; switch (sk->sk_family) { case AF_INET: if (opt != IP_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: if (opt != IPV6_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(struct sadb_x_policy) || pol->sadb_x_policy_len*8 > len || pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS || (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND)) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; xp->family = sk->sk_family; xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (*dir = parse_ipsecrequests(xp, pol)) < 0) goto out; /* security context too */ if (len >= (pol->sadb_x_policy_len*8 + sizeof(struct sadb_x_sec_ctx))) { char *p = (char *)pol; struct xfrm_user_sec_ctx *uctx; p += pol->sadb_x_policy_len*8; sec_ctx = (struct sadb_x_sec_ctx *)p; if (len < pol->sadb_x_policy_len*8 + sec_ctx->sadb_x_sec_len) { *dir = -EINVAL; goto out; } if ((*dir = verify_sec_ctx_len(p))) goto out; uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); *dir = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (*dir) goto out; } *dir = pol->sadb_x_policy_dir-1; return xp; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_address *addr; struct sadb_x_nat_t_port *n_port; int sockaddr_size; int size; __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0); struct xfrm_encap_tmpl *natt = NULL; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; if (!satype) return -EINVAL; if (!x->encap) return -EINVAL; natt = x->encap; /* Build an SADB_X_NAT_T_NEW_MAPPING message: * * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) | * ADDRESS_DST (new addr) | NAT_T_DPORT (new port) */ size = sizeof(struct sadb_msg) + sizeof(struct sadb_sa) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + (sizeof(struct sadb_x_nat_t_port) * 2); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING; hdr->sadb_msg_satype = satype; hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* SA */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = 0; sa->sadb_sa_state = 0; sa->sadb_sa_auth = 0; sa->sadb_sa_encrypt = 0; sa->sadb_sa_flags = 0; /* ADDRESS_SRC (old addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_SPORT (old port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* ADDRESS_DST (new addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(ipaddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_DPORT (new port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = sport; n_port->sadb_x_nat_t_port_reserved = 0; return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } #ifdef CONFIG_NET_KEY_MIGRATE static int set_sadb_address(struct sk_buff *skb, int sasize, int type, const struct xfrm_selector *sel) { struct sadb_address *addr; addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize); addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8; addr->sadb_address_exttype = type; addr->sadb_address_proto = sel->proto; addr->sadb_address_reserved = 0; switch (type) { case SADB_EXT_ADDRESS_SRC: addr->sadb_address_prefixlen = sel->prefixlen_s; pfkey_sockaddr_fill(&sel->saddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; case SADB_EXT_ADDRESS_DST: addr->sadb_address_prefixlen = sel->prefixlen_d; pfkey_sockaddr_fill(&sel->daddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; default: return -EINVAL; } return 0; } static int set_sadb_kmaddress(struct sk_buff *skb, const struct xfrm_kmaddress *k) { struct sadb_x_kmaddress *kma; u8 *sa; int family = k->family; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = (sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(family)); kma = (struct sadb_x_kmaddress *)skb_put(skb, size_req); memset(kma, 0, size_req); kma->sadb_x_kmaddress_len = size_req / 8; kma->sadb_x_kmaddress_exttype = SADB_X_EXT_KMADDRESS; kma->sadb_x_kmaddress_reserved = k->reserved; sa = (u8 *)(kma + 1); if (!pfkey_sockaddr_fill(&k->local, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(&k->remote, 0, (struct sockaddr *)(sa+socklen), family)) return -EINVAL; return 0; } static int set_ipsecrequest(struct sk_buff *skb, uint8_t proto, uint8_t mode, int level, uint32_t reqid, uint8_t family, const xfrm_address_t *src, const xfrm_address_t *dst) { struct sadb_x_ipsecrequest *rq; u8 *sa; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(family); rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req); memset(rq, 0, size_req); rq->sadb_x_ipsecrequest_len = size_req; rq->sadb_x_ipsecrequest_proto = proto; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = level; rq->sadb_x_ipsecrequest_reqid = reqid; sa = (u8 *) (rq + 1); if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family)) return -EINVAL; return 0; } #endif #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_bundles, const struct xfrm_kmaddress *k) { int i; int sasize_sel; int size = 0; int size_pol = 0; struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_x_policy *pol; const struct xfrm_migrate *mp; if (type != XFRM_POLICY_TYPE_MAIN) return 0; if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH) return -EINVAL; if (k != NULL) { /* addresses for KM */ size += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(k->family)); } /* selector */ sasize_sel = pfkey_sockaddr_size(sel->family); if (!sasize_sel) return -EINVAL; size += (sizeof(struct sadb_address) + sasize_sel) * 2; /* policy info */ size_pol += sizeof(struct sadb_x_policy); /* ipsecrequests */ for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->old_family); /* new locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->new_family); } size += sizeof(struct sadb_msg) + size_pol; /* alloc buffer */ skb = alloc_skb(size, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_MIGRATE; hdr->sadb_msg_satype = pfkey_proto2satype(m->proto); hdr->sadb_msg_len = size / 8; hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = 0; hdr->sadb_msg_pid = 0; /* Addresses to be used by KM for negotiation, if ext is available */ if (k != NULL && (set_sadb_kmaddress(skb, k) < 0)) goto err; /* selector src */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel); /* selector dst */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel); /* policy information */ pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = size_pol / 8; pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = dir + 1; pol->sadb_x_policy_id = 0; pol->sadb_x_policy_priority = 0; for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old ipsecrequest */ int mode = pfkey_mode_from_xfrm(mp->mode); if (mode < 0) goto err; if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->old_family, &mp->old_saddr, &mp->old_daddr) < 0) goto err; /* new ipsecrequest */ if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->new_family, &mp->new_saddr, &mp->new_daddr) < 0) goto err; } /* broadcast migrate message to sockets */ pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net); return 0; err: kfree_skb(skb); return -EINVAL; } #else static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_bundles, const struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif static int pfkey_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct sk_buff *skb = NULL; struct sadb_msg *hdr = NULL; int err; err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) goto out; err = -EMSGSIZE; if ((unsigned int)len > sk->sk_sndbuf - 32) goto out; err = -ENOBUFS; skb = alloc_skb(len, GFP_KERNEL); if (skb == NULL) goto out; err = -EFAULT; if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) goto out; hdr = pfkey_get_base_msg(skb, &err); if (!hdr) goto out; mutex_lock(&xfrm_cfg_mutex); err = pfkey_process(sk, skb, hdr); mutex_unlock(&xfrm_cfg_mutex); out: if (err && hdr && pfkey_error(hdr, err, sk) == 0) err = 0; kfree_skb(skb); return err ? : len; } static int pfkey_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *skb; int copied, err; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT)) goto out; msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_ts_and_drops(msg, sk, skb); err = (flags & MSG_TRUNC) ? skb->len : copied; if (pfk->dump.dump != NULL && 3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) pfkey_do_dump(pfk); out_free: skb_free_datagram(sk, skb); out: return err; } static const struct proto_ops pfkey_ops = { .family = PF_KEY, .owner = THIS_MODULE, /* Operations that make no sense on pfkey sockets. */ .bind = sock_no_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, /* Now the operations that really occur. */ .release = pfkey_release, .poll = datagram_poll, .sendmsg = pfkey_sendmsg, .recvmsg = pfkey_recvmsg, }; static const struct net_proto_family pfkey_family_ops = { .family = PF_KEY, .create = pfkey_create, .owner = THIS_MODULE, }; #ifdef CONFIG_PROC_FS static int pfkey_seq_show(struct seq_file *f, void *v) { struct sock *s = sk_entry(v); if (v == SEQ_START_TOKEN) seq_printf(f ,"sk RefCnt Rmem Wmem User Inode\n"); else seq_printf(f, "%pK %-6d %-6u %-6u %-6u %-6lu\n", s, atomic_read(&s->sk_refcnt), sk_rmem_alloc_get(s), sk_wmem_alloc_get(s), from_kuid_munged(seq_user_ns(f), sock_i_uid(s)), sock_i_ino(s) ); return 0; } static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos) __acquires(rcu) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); rcu_read_lock(); return seq_hlist_start_head_rcu(&net_pfkey->table, *ppos); } static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); return seq_hlist_next_rcu(v, &net_pfkey->table, ppos); } static void pfkey_seq_stop(struct seq_file *f, void *v) __releases(rcu) { rcu_read_unlock(); } static const struct seq_operations pfkey_seq_ops = { .start = pfkey_seq_start, .next = pfkey_seq_next, .stop = pfkey_seq_stop, .show = pfkey_seq_show, }; static int pfkey_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &pfkey_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations pfkey_proc_ops = { .open = pfkey_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init pfkey_init_proc(struct net *net) { struct proc_dir_entry *e; e = proc_create("pfkey", 0, net->proc_net, &pfkey_proc_ops); if (e == NULL) return -ENOMEM; return 0; } static void __net_exit pfkey_exit_proc(struct net *net) { remove_proc_entry("pfkey", net->proc_net); } #else static inline int pfkey_init_proc(struct net *net) { return 0; } static inline void pfkey_exit_proc(struct net *net) { } #endif static struct xfrm_mgr pfkeyv2_mgr = { .id = "pfkeyv2", .notify = pfkey_send_notify, .acquire = pfkey_send_acquire, .compile_policy = pfkey_compile_policy, .new_mapping = pfkey_send_new_mapping, .notify_policy = pfkey_send_policy_notify, .migrate = pfkey_send_migrate, }; static int __net_init pfkey_net_init(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); int rv; INIT_HLIST_HEAD(&net_pfkey->table); atomic_set(&net_pfkey->socks_nr, 0); rv = pfkey_init_proc(net); return rv; } static void __net_exit pfkey_net_exit(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_exit_proc(net); BUG_ON(!hlist_empty(&net_pfkey->table)); } static struct pernet_operations pfkey_net_ops = { .init = pfkey_net_init, .exit = pfkey_net_exit, .id = &pfkey_net_id, .size = sizeof(struct netns_pfkey), }; static void __exit ipsec_pfkey_exit(void) { xfrm_unregister_km(&pfkeyv2_mgr); sock_unregister(PF_KEY); unregister_pernet_subsys(&pfkey_net_ops); proto_unregister(&key_proto); } static int __init ipsec_pfkey_init(void) { int err = proto_register(&key_proto, 0); if (err != 0) goto out; err = register_pernet_subsys(&pfkey_net_ops); if (err != 0) goto out_unregister_key_proto; err = sock_register(&pfkey_family_ops); if (err != 0) goto out_unregister_pernet; err = xfrm_register_km(&pfkeyv2_mgr); if (err != 0) goto out_sock_unregister; out: return err; out_sock_unregister: sock_unregister(PF_KEY); out_unregister_pernet: unregister_pernet_subsys(&pfkey_net_ops); out_unregister_key_proto: proto_unregister(&key_proto); goto out; } module_init(ipsec_pfkey_init); module_exit(ipsec_pfkey_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_KEY);
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5662_0
crossvul-cpp_data_bad_5409_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF X X % % F X X % % FFF X % % F X X % % F X X % % % % % % MagickCore Image Special Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/fx-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/transform.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define LeftShiftOperator 0xf5U #define RightShiftOperator 0xf6U #define LessThanEqualOperator 0xf7U #define GreaterThanEqualOperator 0xf8U #define EqualOperator 0xf9U #define NotEqualOperator 0xfaU #define LogicalAndOperator 0xfbU #define LogicalOrOperator 0xfcU #define ExponentialNotation 0xfdU struct _FxInfo { const Image *images; char *expression; FILE *file; SplayTreeInfo *colors, *symbols; CacheView **view; RandomInfo *random_info; ExceptionInfo *exception; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e F x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireFxInfo() allocates the FxInfo structure. % % The format of the AcquireFxInfo method is: % % FxInfo *AcquireFxInfo(Image *image,const char *expression, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o expression: the expression. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate FxInfo *AcquireFxInfo(const Image *image,const char *expression, ExceptionInfo *exception) { char fx_op[2]; const Image *next; FxInfo *fx_info; register ssize_t i; fx_info=(FxInfo *) AcquireMagickMemory(sizeof(*fx_info)); if (fx_info == (FxInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(fx_info,0,sizeof(*fx_info)); fx_info->exception=AcquireExceptionInfo(); fx_info->images=image; fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishAlignedMemory); fx_info->symbols=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishMagickMemory); fx_info->view=(CacheView **) AcquireQuantumMemory(GetImageListLength( fx_info->images),sizeof(*fx_info->view)); if (fx_info->view == (CacheView **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); i=0; next=GetFirstImageInList(fx_info->images); for ( ; next != (Image *) NULL; next=next->next) { fx_info->view[i]=AcquireVirtualCacheView(next,exception); i++; } fx_info->random_info=AcquireRandomInfo(); fx_info->expression=ConstantString(expression); fx_info->file=stderr; (void) SubstituteString(&fx_info->expression," ",""); /* compact string */ /* Force right-to-left associativity for unary negation. */ (void) SubstituteString(&fx_info->expression,"-","-1.0*"); (void) SubstituteString(&fx_info->expression,"^-1.0*","^-"); (void) SubstituteString(&fx_info->expression,"E-1.0*","E-"); (void) SubstituteString(&fx_info->expression,"e-1.0*","e-"); /* Convert compound to simple operators. */ fx_op[1]='\0'; *fx_op=(char) LeftShiftOperator; (void) SubstituteString(&fx_info->expression,"<<",fx_op); *fx_op=(char) RightShiftOperator; (void) SubstituteString(&fx_info->expression,">>",fx_op); *fx_op=(char) LessThanEqualOperator; (void) SubstituteString(&fx_info->expression,"<=",fx_op); *fx_op=(char) GreaterThanEqualOperator; (void) SubstituteString(&fx_info->expression,">=",fx_op); *fx_op=(char) EqualOperator; (void) SubstituteString(&fx_info->expression,"==",fx_op); *fx_op=(char) NotEqualOperator; (void) SubstituteString(&fx_info->expression,"!=",fx_op); *fx_op=(char) LogicalAndOperator; (void) SubstituteString(&fx_info->expression,"&&",fx_op); *fx_op=(char) LogicalOrOperator; (void) SubstituteString(&fx_info->expression,"||",fx_op); *fx_op=(char) ExponentialNotation; (void) SubstituteString(&fx_info->expression,"**",fx_op); return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d d N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddNoiseImage() adds random noise to the image. % % The format of the AddNoiseImage method is: % % Image *AddNoiseImage(const Image *image,const NoiseType noise_type, % const double attenuate,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o noise_type: The type of noise: Uniform, Gaussian, Multiplicative, % Impulse, Laplacian, or Poisson. % % o attenuate: attenuate the random distribution. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type, const double attenuate,ExceptionInfo *exception) { #define AddNoiseImageTag "AddNoise/Image" CacheView *image_view, *noise_view; Image *noise_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize noise image attributes. */ assert(image != (const 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); #if defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateAddNoiseImage(image,noise_type,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } /* Add noise in each row. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,noise_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel); if ((traits == UndefinedPixelTrait) || (noise_traits == UndefinedPixelTrait)) continue; if (((noise_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(noise_image,channel,p[i],q); continue; } SetPixelChannel(noise_image,channel,ClampToQuantum( GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)), q); } p+=GetPixelChannels(image); q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AddNoiseImage) #endif proceed=SetImageProgress(image,AddNoiseImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u e S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlueShiftImage() mutes the colors of the image to simulate a scene at % nighttime in the moonlight. % % The format of the BlueShiftImage method is: % % Image *BlueShiftImage(const Image *image,const double factor, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o factor: the shift factor. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlueShiftImage(const Image *image,const double factor, ExceptionInfo *exception) { #define BlueShiftImageTag "BlueShift/Image" CacheView *image_view, *shift_view; Image *shift_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate blue shift image. */ assert(image != (const 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); shift_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (shift_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse) { shift_image=DestroyImage(shift_image); return((Image *) NULL); } /* Blue-shift DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); shift_view=AcquireAuthenticCacheView(shift_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,shift_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; Quantum quantum; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) < quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) < quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum); pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum); pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum); quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) > quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) > quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(pixel.red+factor*quantum); pixel.green=0.5*(pixel.green+factor*quantum); pixel.blue=0.5*(pixel.blue+factor*quantum); SetPixelRed(shift_image,ClampToQuantum(pixel.red),q); SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q); SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q); p+=GetPixelChannels(image); q+=GetPixelChannels(shift_image); } sync=SyncCacheViewAuthenticPixels(shift_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlueShiftImage) #endif proceed=SetImageProgress(image,BlueShiftImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shift_view=DestroyCacheView(shift_view); if (status == MagickFalse) shift_image=DestroyImage(shift_image); return(shift_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a r c o a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CharcoalImage() creates a new image that is a copy of an existing one with % the edge highlighted. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the CharcoalImage method is: % % Image *CharcoalImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CharcoalImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *charcoal_image, *clone_image, *edge_image; 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); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); edge_image=EdgeImage(clone_image,radius,exception); clone_image=DestroyImage(clone_image); if (edge_image == (Image *) NULL) return((Image *) NULL); charcoal_image=BlurImage(edge_image,radius,sigma,exception); edge_image=DestroyImage(edge_image); if (charcoal_image == (Image *) NULL) return((Image *) NULL); (void) NormalizeImage(charcoal_image,exception); (void) NegateImage(charcoal_image,MagickFalse,exception); (void) GrayscaleImage(charcoal_image,image->intensity,exception); return(charcoal_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorizeImage() blends the fill color with each pixel in the image. % A percentage blend is specified with opacity. Control the application % of different color components by specifying a different percentage for % each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue). % % The format of the ColorizeImage method is: % % Image *ColorizeImage(const Image *image,const char *blend, % const PixelInfo *colorize,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A character string indicating the level of blending as a % percentage. % % o colorize: A color value. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorizeImage(const Image *image,const char *blend, const PixelInfo *colorize,ExceptionInfo *exception) { #define ColorizeImageTag "Colorize/Image" #define Colorize(pixel,blend_percentage,colorize) \ (((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0) CacheView *image_view; GeometryInfo geometry_info; Image *colorize_image; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; PixelInfo blend_percentage; ssize_t y; /* Allocate colorized image. */ assert(image != (const 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); colorize_image=CloneImage(image,0,0,MagickTrue,exception); if (colorize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse) { colorize_image=DestroyImage(colorize_image); return((Image *) NULL); } if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) || (IsPixelInfoGray(colorize) != MagickFalse)) (void) SetImageColorspace(colorize_image,sRGBColorspace,exception); if ((colorize_image->alpha_trait == UndefinedPixelTrait) && (colorize->alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(colorize_image,OpaqueAlpha,exception); if (blend == (const char *) NULL) return(colorize_image); GetPixelInfo(colorize_image,&blend_percentage); flags=ParseGeometry(blend,&geometry_info); blend_percentage.red=geometry_info.rho; blend_percentage.green=geometry_info.rho; blend_percentage.blue=geometry_info.rho; blend_percentage.black=geometry_info.rho; blend_percentage.alpha=(MagickRealType) TransparentAlpha; if ((flags & SigmaValue) != 0) blend_percentage.green=geometry_info.sigma; if ((flags & XiValue) != 0) blend_percentage.blue=geometry_info.xi; if ((flags & PsiValue) != 0) blend_percentage.alpha=geometry_info.psi; if (blend_percentage.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) blend_percentage.black=geometry_info.psi; if ((flags & ChiValue) != 0) blend_percentage.alpha=geometry_info.chi; } /* Colorize DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(colorize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(colorize_image,colorize_image,colorize_image->rows,1) #endif for (y=0; y < (ssize_t) colorize_image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) colorize_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++) { PixelTrait traits=GetPixelChannelTraits(colorize_image, (PixelChannel) i); if (traits == UndefinedPixelTrait) continue; if (((traits & CopyPixelTrait) != 0) || (GetPixelReadMask(colorize_image,q) == 0)) continue; SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum( Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i), GetPixelInfoChannel(colorize,(PixelChannel) i))),q); } q+=GetPixelChannels(colorize_image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorizeImage) #endif proceed=SetImageProgress(image,ColorizeImageTag,progress++, colorize_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) colorize_image=DestroyImage(colorize_image); return(colorize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r M a t r i x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorMatrixImage() applies color transformation to an image. This method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the ColorMatrixImage method is: % % Image *ColorMatrixImage(const Image *image, % const KernelInfo *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_matrix: the color matrix. % % o exception: return any errors or warnings in this structure. % */ /* FUTURE: modify to make use of a MagickMatrix Mutliply function That should be provided in "matrix.c" (ASIDE: actually distorts should do this too but currently doesn't) */ MagickExport Image *ColorMatrixImage(const Image *image, const KernelInfo *color_matrix,ExceptionInfo *exception) { #define ColorMatrixImageTag "ColorMatrix/Image" CacheView *color_view, *image_view; double ColorMatrix[6][6] = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 } }; Image *color_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t u, v, y; /* Map given color_matrix, into a 6x6 matrix RGBKA and a constant */ 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); i=0; for (v=0; v < (ssize_t) color_matrix->height; v++) for (u=0; u < (ssize_t) color_matrix->width; u++) { if ((v < 6) && (u < 6)) ColorMatrix[v][u]=color_matrix->values[i]; i++; } /* Initialize color image. */ color_image=CloneImage(image,0,0,MagickTrue,exception); if (color_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse) { color_image=DestroyImage(color_image); return((Image *) NULL); } if (image->debug != MagickFalse) { char format[MagickPathExtent], *message; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " ColorMatrix image with color matrix:"); message=AcquireString(""); for (v=0; v < 6; v++) { *message='\0'; (void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < 6; u++) { (void) FormatLocaleString(format,MagickPathExtent,"%+f ", ColorMatrix[v][u]); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } /* Apply the ColorMatrix to image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); color_view=AcquireAuthenticCacheView(color_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,color_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t v; size_t height; GetPixelInfoPixel(image,p,&pixel); height=color_matrix->height > 6 ? 6UL : color_matrix->height; for (v=0; v < (ssize_t) height; v++) { double sum; sum=ColorMatrix[v][0]*GetPixelRed(image,p)+ColorMatrix[v][1]* GetPixelGreen(image,p)+ColorMatrix[v][2]*GetPixelBlue(image,p); if (image->colorspace == CMYKColorspace) sum+=ColorMatrix[v][3]*GetPixelBlack(image,p); if (image->alpha_trait != UndefinedPixelTrait) sum+=ColorMatrix[v][4]*GetPixelAlpha(image,p); sum+=QuantumRange*ColorMatrix[v][5]; switch (v) { case 0: pixel.red=sum; break; case 1: pixel.green=sum; break; case 2: pixel.blue=sum; break; case 3: pixel.black=sum; break; case 4: pixel.alpha=sum; break; default: break; } } SetPixelViaPixelInfo(color_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(color_image); } if (SyncCacheViewAuthenticPixels(color_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorMatrixImage) #endif proceed=SetImageProgress(image,ColorMatrixImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } color_view=DestroyCacheView(color_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) color_image=DestroyImage(color_image); return(color_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y F x I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyFxInfo() deallocates memory associated with an FxInfo structure. % % The format of the DestroyFxInfo method is: % % ImageInfo *DestroyFxInfo(ImageInfo *fx_info) % % A description of each parameter follows: % % o fx_info: the fx info. % */ MagickPrivate FxInfo *DestroyFxInfo(FxInfo *fx_info) { register ssize_t i; fx_info->exception=DestroyExceptionInfo(fx_info->exception); fx_info->expression=DestroyString(fx_info->expression); fx_info->symbols=DestroySplayTree(fx_info->symbols); fx_info->colors=DestroySplayTree(fx_info->colors); for (i=(ssize_t) GetImageListLength(fx_info->images)-1; i >= 0; i--) fx_info->view[i]=DestroyCacheView(fx_info->view[i]); fx_info->view=(CacheView **) RelinquishMagickMemory(fx_info->view); fx_info->random_info=DestroyRandomInfo(fx_info->random_info); fx_info=(FxInfo *) RelinquishMagickMemory(fx_info); return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F x E v a l u a t e C h a n n e l E x p r e s s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FxEvaluateChannelExpression() evaluates an expression and returns the % results. % % The format of the FxEvaluateExpression method is: % % double FxEvaluateChannelExpression(FxInfo *fx_info, % const PixelChannel channel,const ssize_t x,const ssize_t y, % double *alpha,Exceptioninfo *exception) % double FxEvaluateExpression(FxInfo *fx_info, % double *alpha,Exceptioninfo *exception) % % A description of each parameter follows: % % o fx_info: the fx info. % % o channel: the channel. % % o x,y: the pixel position. % % o alpha: the result. % % o exception: return any errors or warnings in this structure. % */ static double FxChannelStatistics(FxInfo *fx_info,Image *image, PixelChannel channel,const char *symbol,ExceptionInfo *exception) { ChannelType channel_mask; char key[MagickPathExtent], statistic[MagickPathExtent]; const char *value; register const char *p; channel_mask=UndefinedChannel; for (p=symbol; (*p != '.') && (*p != '\0'); p++) ; if (*p == '.') { ssize_t option; option=ParseCommandOption(MagickPixelChannelOptions,MagickTrue,p+1); if (option >= 0) { channel=(PixelChannel) option; channel_mask=(ChannelType) (channel_mask | (1 << channel)); (void) SetPixelChannelMask(image,channel_mask); } } (void) FormatLocaleString(key,MagickPathExtent,"%p.%.20g.%s",(void *) image, (double) channel,symbol); value=(const char *) GetValueFromSplayTree(fx_info->symbols,key); if (value != (const char *) NULL) { if (channel_mask != UndefinedChannel) (void) SetPixelChannelMask(image,channel_mask); return(QuantumScale*StringToDouble(value,(char **) NULL)); } (void) DeleteNodeFromSplayTree(fx_info->symbols,key); if (LocaleNCompare(symbol,"depth",5) == 0) { size_t depth; depth=GetImageDepth(image,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%.20g",(double) depth); } if (LocaleNCompare(symbol,"kurtosis",8) == 0) { double kurtosis, skewness; (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%g",kurtosis); } if (LocaleNCompare(symbol,"maxima",6) == 0) { double maxima, minima; (void) GetImageRange(image,&minima,&maxima,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%g",maxima); } if (LocaleNCompare(symbol,"mean",4) == 0) { double mean, standard_deviation; (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%g",mean); } if (LocaleNCompare(symbol,"minima",6) == 0) { double maxima, minima; (void) GetImageRange(image,&minima,&maxima,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%g",minima); } if (LocaleNCompare(symbol,"skewness",8) == 0) { double kurtosis, skewness; (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%g",skewness); } if (LocaleNCompare(symbol,"standard_deviation",18) == 0) { double mean, standard_deviation; (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(statistic,MagickPathExtent,"%g", standard_deviation); } if (channel_mask != UndefinedChannel) (void) SetPixelChannelMask(image,channel_mask); (void) AddValueToSplayTree(fx_info->symbols,ConstantString(key), ConstantString(statistic)); return(QuantumScale*StringToDouble(statistic,(char **) NULL)); } static double FxEvaluateSubexpression(FxInfo *,const PixelChannel,const ssize_t, const ssize_t,const char *,size_t *,double *,ExceptionInfo *); static MagickOffsetType FxGCD(MagickOffsetType alpha,MagickOffsetType beta) { if (beta != 0) return(FxGCD(beta,alpha % beta)); return(alpha); } static inline const char *FxSubexpression(const char *expression, ExceptionInfo *exception) { const char *subexpression; register ssize_t level; level=0; subexpression=expression; while ((*subexpression != '\0') && ((level != 1) || (strchr(")",(int) *subexpression) == (char *) NULL))) { if (strchr("(",(int) *subexpression) != (char *) NULL) level++; else if (strchr(")",(int) *subexpression) != (char *) NULL) level--; subexpression++; } if (*subexpression == '\0') (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnbalancedParenthesis","`%s'",expression); return(subexpression); } static double FxGetSymbol(FxInfo *fx_info,const PixelChannel channel, const ssize_t x,const ssize_t y,const char *expression, ExceptionInfo *exception) { char *q, subexpression[MagickPathExtent], symbol[MagickPathExtent]; const char *p, *value; Image *image; PixelInfo pixel; double alpha, beta; PointInfo point; register ssize_t i; size_t depth, length, level; p=expression; i=GetImageIndexInList(fx_info->images); depth=0; level=0; point.x=(double) x; point.y=(double) y; if (isalpha((int) ((unsigned char) *(p+1))) == 0) { if (strchr("suv",(int) *p) != (char *) NULL) { switch (*p) { case 's': default: { i=GetImageIndexInList(fx_info->images); break; } case 'u': i=0; break; case 'v': i=1; break; } p++; if (*p == '[') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '[') level++; else if (*p == ']') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, &depth,&beta,exception); i=(ssize_t) (alpha+0.5); p++; } if (*p == '.') p++; } if ((*p == 'p') && (isalpha((int) ((unsigned char) *(p+1))) == 0)) { p++; if (*p == '{') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '{') level++; else if (*p == '}') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, &depth,&beta,exception); point.x=alpha; point.y=beta; p++; } else if (*p == '[') { level++; q=subexpression; for (p++; *p != '\0'; ) { if (*p == '[') level++; else if (*p == ']') { level--; if (level == 0) break; } *q++=(*p++); } *q='\0'; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression, &depth,&beta,exception); point.x+=alpha; point.y+=beta; p++; } if (*p == '.') p++; } } length=GetImageListLength(fx_info->images); while (i < 0) i+=(ssize_t) length; if (length != 0) i%=length; image=GetImageFromList(fx_info->images,i); if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "NoSuchImage","`%s'",expression); return(0.0); } GetPixelInfo(image,&pixel); (void) InterpolatePixelInfo(image,fx_info->view[i],image->interpolate, point.x,point.y,&pixel,exception); if ((strlen(p) > 2) && (LocaleCompare(p,"intensity") != 0) && (LocaleCompare(p,"luma") != 0) && (LocaleCompare(p,"luminance") != 0) && (LocaleCompare(p,"hue") != 0) && (LocaleCompare(p,"saturation") != 0) && (LocaleCompare(p,"lightness") != 0)) { char name[MagickPathExtent]; (void) CopyMagickString(name,p,MagickPathExtent); for (q=name+(strlen(name)-1); q > name; q--) { if (*q == ')') break; if (*q == '.') { *q='\0'; break; } } if ((strlen(name) > 2) && (GetValueFromSplayTree(fx_info->symbols,name) == (const char *) NULL)) { PixelInfo *color; color=(PixelInfo *) GetValueFromSplayTree(fx_info->colors,name); if (color != (PixelInfo *) NULL) { pixel=(*color); p+=strlen(name); } else { MagickBooleanType status; status=QueryColorCompliance(name,AllCompliance,&pixel, fx_info->exception); if (status != MagickFalse) { (void) AddValueToSplayTree(fx_info->colors,ConstantString( name),ClonePixelInfo(&pixel)); p+=strlen(name); } } } } (void) CopyMagickString(symbol,p,MagickPathExtent); StripString(symbol); if (*symbol == '\0') { switch (channel) { case RedPixelChannel: return(QuantumScale*pixel.red); case GreenPixelChannel: return(QuantumScale*pixel.green); case BluePixelChannel: return(QuantumScale*pixel.blue); case BlackPixelChannel: { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), ImageError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.black); } case AlphaPixelChannel: { if (pixel.alpha_trait == UndefinedPixelTrait) return(1.0); alpha=(double) (QuantumScale*pixel.alpha); return(alpha); } case IndexPixelChannel: return(0.0); case IntensityPixelChannel: { Quantum quantum_pixel[MaxPixelChannels]; SetPixelViaPixelInfo(image,&pixel,quantum_pixel); return(QuantumScale*GetPixelIntensity(image,quantum_pixel)); } default: break; } (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",p); return(0.0); } switch (*symbol) { case 'A': case 'a': { if (LocaleCompare(symbol,"a") == 0) return((QuantumScale*pixel.alpha)); break; } case 'B': case 'b': { if (LocaleCompare(symbol,"b") == 0) return(QuantumScale*pixel.blue); break; } case 'C': case 'c': { if (LocaleNCompare(symbol,"channel",7) == 0) { GeometryInfo channel_info; MagickStatusType flags; flags=ParseGeometry(symbol+7,&channel_info); if (image->colorspace == CMYKColorspace) switch (channel) { case CyanPixelChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case MagentaPixelChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case YellowPixelChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case BlackPixelChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } case AlphaPixelChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } default: return(0.0); } switch (channel) { case RedPixelChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case GreenPixelChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case BluePixelChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case BlackPixelChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } case AlphaPixelChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } default: return(0.0); } } if (LocaleCompare(symbol,"c") == 0) return(QuantumScale*pixel.red); break; } case 'D': case 'd': { if (LocaleNCompare(symbol,"depth",5) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); break; } case 'G': case 'g': { if (LocaleCompare(symbol,"g") == 0) return(QuantumScale*pixel.green); break; } case 'K': case 'k': { if (LocaleNCompare(symbol,"kurtosis",8) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleCompare(symbol,"k") == 0) { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.black); } break; } case 'H': case 'h': { if (LocaleCompare(symbol,"h") == 0) return(image->rows); if (LocaleCompare(symbol,"hue") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation, &lightness); return(hue); } break; } case 'I': case 'i': { if ((LocaleCompare(symbol,"image.depth") == 0) || (LocaleCompare(symbol,"image.minima") == 0) || (LocaleCompare(symbol,"image.maxima") == 0) || (LocaleCompare(symbol,"image.mean") == 0) || (LocaleCompare(symbol,"image.kurtosis") == 0) || (LocaleCompare(symbol,"image.skewness") == 0) || (LocaleCompare(symbol,"image.standard_deviation") == 0)) return(FxChannelStatistics(fx_info,image,channel,symbol+6,exception)); if (LocaleCompare(symbol,"image.resolution.x") == 0) return(image->resolution.x); if (LocaleCompare(symbol,"image.resolution.y") == 0) return(image->resolution.y); if (LocaleCompare(symbol,"intensity") == 0) { Quantum quantum_pixel[MaxPixelChannels]; SetPixelViaPixelInfo(image,&pixel,quantum_pixel); return(QuantumScale*GetPixelIntensity(image,quantum_pixel)); } if (LocaleCompare(symbol,"i") == 0) return(x); break; } case 'J': case 'j': { if (LocaleCompare(symbol,"j") == 0) return(y); break; } case 'L': case 'l': { if (LocaleCompare(symbol,"lightness") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation, &lightness); return(lightness); } if (LocaleCompare(symbol,"luma") == 0) { double luma; luma=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue; return(QuantumScale*luma); } if (LocaleCompare(symbol,"luminance") == 0) { double luminence; luminence=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue; return(QuantumScale*luminence); } break; } case 'M': case 'm': { if (LocaleNCompare(symbol,"maxima",6) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"mean",4) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"minima",6) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleCompare(symbol,"m") == 0) return(QuantumScale*pixel.green); break; } case 'N': case 'n': { if (LocaleCompare(symbol,"n") == 0) return(GetImageListLength(fx_info->images)); break; } case 'O': case 'o': { if (LocaleCompare(symbol,"o") == 0) return(QuantumScale*pixel.alpha); break; } case 'P': case 'p': { if (LocaleCompare(symbol,"page.height") == 0) return(image->page.height); if (LocaleCompare(symbol,"page.width") == 0) return(image->page.width); if (LocaleCompare(symbol,"page.x") == 0) return(image->page.x); if (LocaleCompare(symbol,"page.y") == 0) return(image->page.y); break; } case 'Q': case 'q': { if (LocaleCompare(symbol,"quality") == 0) return(image->quality); break; } case 'R': case 'r': { if (LocaleCompare(symbol,"resolution.x") == 0) return(image->resolution.x); if (LocaleCompare(symbol,"resolution.y") == 0) return(image->resolution.y); if (LocaleCompare(symbol,"r") == 0) return(QuantumScale*pixel.red); break; } case 'S': case 's': { if (LocaleCompare(symbol,"saturation") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(pixel.red,pixel.green,pixel.blue,&hue,&saturation, &lightness); return(saturation); } if (LocaleNCompare(symbol,"skewness",8) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); if (LocaleNCompare(symbol,"standard_deviation",18) == 0) return(FxChannelStatistics(fx_info,image,channel,symbol,exception)); break; } case 'T': case 't': { if (LocaleCompare(symbol,"t") == 0) return(GetImageIndexInList(fx_info->images)); break; } case 'W': case 'w': { if (LocaleCompare(symbol,"w") == 0) return(image->columns); break; } case 'Y': case 'y': { if (LocaleCompare(symbol,"y") == 0) return(QuantumScale*pixel.blue); break; } case 'Z': case 'z': { if (LocaleCompare(symbol,"z") == 0) return((double)GetImageDepth(image, fx_info->exception)); break; } default: break; } value=(const char *) GetValueFromSplayTree(fx_info->symbols,symbol); if (value != (const char *) NULL) return(StringToDouble(value,(char **) NULL)); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnableToParseExpression","`%s'",symbol); return(0.0); } static const char *FxOperatorPrecedence(const char *expression, ExceptionInfo *exception) { typedef enum { UndefinedPrecedence, NullPrecedence, BitwiseComplementPrecedence, ExponentPrecedence, ExponentialNotationPrecedence, MultiplyPrecedence, AdditionPrecedence, ShiftPrecedence, RelationalPrecedence, EquivalencyPrecedence, BitwiseAndPrecedence, BitwiseOrPrecedence, LogicalAndPrecedence, LogicalOrPrecedence, TernaryPrecedence, AssignmentPrecedence, CommaPrecedence, SeparatorPrecedence } FxPrecedence; FxPrecedence precedence, target; register const char *subexpression; register int c; size_t level; c=0; level=0; subexpression=(const char *) NULL; target=NullPrecedence; while (*expression != '\0') { precedence=UndefinedPrecedence; if ((isspace((int) ((unsigned char) *expression)) != 0) || (c == (int) '@')) { expression++; continue; } switch (*expression) { case 'A': case 'a': { #if defined(MAGICKCORE_HAVE_ACOSH) if (LocaleNCompare(expression,"acosh",5) == 0) { expression+=5; break; } #endif #if defined(MAGICKCORE_HAVE_ASINH) if (LocaleNCompare(expression,"asinh",5) == 0) { expression+=5; break; } #endif #if defined(MAGICKCORE_HAVE_ATANH) if (LocaleNCompare(expression,"atanh",5) == 0) { expression+=5; break; } #endif if (LocaleNCompare(expression,"atan2",5) == 0) { expression+=5; break; } break; } case 'E': case 'e': { if ((isdigit((int) ((unsigned char) c)) != 0) && ((LocaleNCompare(expression,"E+",2) == 0) || (LocaleNCompare(expression,"E-",2) == 0))) { expression+=2; /* scientific notation */ break; } } case 'J': case 'j': { if ((LocaleNCompare(expression,"j0",2) == 0) || (LocaleNCompare(expression,"j1",2) == 0)) { expression+=2; break; } break; } case '#': { while (isxdigit((int) ((unsigned char) *(expression+1))) != 0) expression++; break; } default: break; } if ((c == (int) '{') || (c == (int) '[')) level++; else if ((c == (int) '}') || (c == (int) ']')) level--; if (level == 0) switch ((unsigned char) *expression) { case '~': case '!': { precedence=BitwiseComplementPrecedence; break; } case '^': case '@': { precedence=ExponentPrecedence; break; } default: { if (((c != 0) && ((isdigit((int) ((unsigned char) c)) != 0) || (strchr(")",(int) ((unsigned char) c)) != (char *) NULL))) && (((islower((int) ((unsigned char) *expression)) != 0) || (strchr("(",(int) ((unsigned char) *expression)) != (char *) NULL)) || ((isdigit((int) ((unsigned char) c)) == 0) && (isdigit((int) ((unsigned char) *expression)) != 0))) && (strchr("xy",(int) ((unsigned char) *expression)) == (char *) NULL)) precedence=MultiplyPrecedence; break; } case '*': case '/': case '%': { precedence=MultiplyPrecedence; break; } case '+': case '-': { if ((strchr("(+-/*%:&^|<>~,",c) == (char *) NULL) || (isalpha(c) != 0)) precedence=AdditionPrecedence; break; } case LeftShiftOperator: case RightShiftOperator: { precedence=ShiftPrecedence; break; } case '<': case LessThanEqualOperator: case GreaterThanEqualOperator: case '>': { precedence=RelationalPrecedence; break; } case EqualOperator: case NotEqualOperator: { precedence=EquivalencyPrecedence; break; } case '&': { precedence=BitwiseAndPrecedence; break; } case '|': { precedence=BitwiseOrPrecedence; break; } case LogicalAndOperator: { precedence=LogicalAndPrecedence; break; } case LogicalOrOperator: { precedence=LogicalOrPrecedence; break; } case ExponentialNotation: { precedence=ExponentialNotationPrecedence; break; } case ':': case '?': { precedence=TernaryPrecedence; break; } case '=': { precedence=AssignmentPrecedence; break; } case ',': { precedence=CommaPrecedence; break; } case ';': { precedence=SeparatorPrecedence; break; } } if ((precedence == BitwiseComplementPrecedence) || (precedence == TernaryPrecedence) || (precedence == AssignmentPrecedence)) { if (precedence > target) { /* Right-to-left associativity. */ target=precedence; subexpression=expression; } } else if (precedence >= target) { /* Left-to-right associativity. */ target=precedence; subexpression=expression; } if (strchr("(",(int) *expression) != (char *) NULL) expression=FxSubexpression(expression,exception); c=(int) (*expression++); } return(subexpression); } static double FxEvaluateSubexpression(FxInfo *fx_info, const PixelChannel channel,const ssize_t x,const ssize_t y, const char *expression,size_t *depth,double *beta,ExceptionInfo *exception) { #define FxMaxParenthesisDepth 58 char *q, subexpression[MagickPathExtent]; double alpha, gamma; register const char *p; *beta=0.0; if (exception->severity >= ErrorException) return(0.0); while (isspace((int) ((unsigned char) *expression)) != 0) expression++; if (*expression == '\0') return(0.0); *subexpression='\0'; p=FxOperatorPrecedence(expression,exception); if (p != (const char *) NULL) { (void) CopyMagickString(subexpression,expression,(size_t) (p-expression+1)); alpha=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth, beta,exception); switch ((unsigned char) *p) { case '~': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); *beta=(double) (~(size_t) *beta); return(*beta); } case '!': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(*beta == 0.0 ? 1.0 : 0.0); } case '^': { *beta=pow(alpha,FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth, beta,exception)); return(*beta); } case '*': case ExponentialNotation: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha*(*beta)); } case '/': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); if (*beta == 0.0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"DivideByZero","`%s'",expression); return(0.0); } return(alpha/(*beta)); } case '%': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); *beta=fabs(floor((*beta)+0.5)); if (*beta == 0.0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"DivideByZero","`%s'",expression); return(0.0); } return(fmod(alpha,*beta)); } case '+': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha+(*beta)); } case '-': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha-(*beta)); } case LeftShiftOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); *beta=(double) ((size_t) (alpha+0.5) << (size_t) (gamma+0.5)); return(*beta); } case RightShiftOperator: { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); *beta=(double) ((size_t) (alpha+0.5) >> (size_t) (gamma+0.5)); return(*beta); } case '<': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha < *beta ? 1.0 : 0.0); } case LessThanEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha <= *beta ? 1.0 : 0.0); } case '>': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha > *beta ? 1.0 : 0.0); } case GreaterThanEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha >= *beta ? 1.0 : 0.0); } case EqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(fabs(alpha-(*beta)) < MagickEpsilon ? 1.0 : 0.0); } case NotEqualOperator: { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(fabs(alpha-(*beta)) >= MagickEpsilon ? 1.0 : 0.0); } case '&': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); *beta=(double) ((size_t) (alpha+0.5) & (size_t) (gamma+0.5)); return(*beta); } case '|': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); *beta=(double) ((size_t) (alpha+0.5) | (size_t) (gamma+0.5)); return(*beta); } case LogicalAndOperator: { p++; if (alpha <= 0.0) { *beta=0.0; return(*beta); } gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta, exception); *beta=(gamma > 0.0) ? 1.0 : 0.0; return(*beta); } case LogicalOrOperator: { p++; if (alpha > 0.0) { *beta=1.0; return(*beta); } gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta, exception); *beta=(gamma > 0.0) ? 1.0 : 0.0; return(*beta); } case '?': { (void) CopyMagickString(subexpression,++p,MagickPathExtent); q=subexpression; p=StringToken(":",&q); if (q == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnableToParseExpression","`%s'",subexpression); return(0.0); } if (fabs(alpha) >= MagickEpsilon) gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta, exception); else gamma=FxEvaluateSubexpression(fx_info,channel,x,y,q,depth,beta, exception); return(gamma); } case '=': { char numeric[MagickPathExtent]; q=subexpression; while (isalpha((int) ((unsigned char) *q)) != 0) q++; if (*q != '\0') { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnableToParseExpression","`%s'",subexpression); return(0.0); } ClearMagickException(exception); *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); (void) FormatLocaleString(numeric,MagickPathExtent,"%g",*beta); (void) DeleteNodeFromSplayTree(fx_info->symbols,subexpression); (void) AddValueToSplayTree(fx_info->symbols,ConstantString( subexpression),ConstantString(numeric)); return(*beta); } case ',': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(alpha); } case ';': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth,beta, exception); return(*beta); } default: { gamma=alpha*FxEvaluateSubexpression(fx_info,channel,x,y,p,depth,beta, exception); return(gamma); } } } if (strchr("(",(int) *expression) != (char *) NULL) { (*depth)++; if (*depth >= FxMaxParenthesisDepth) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "ParenthesisNestedTooDeeply","`%s'",expression); (void) CopyMagickString(subexpression,expression+1,MagickPathExtent); subexpression[strlen(subexpression)-1]='\0'; gamma=FxEvaluateSubexpression(fx_info,channel,x,y,subexpression,depth, beta,exception); (*depth)--; return(gamma); } switch (*expression) { case '+': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth,beta, exception); return(1.0*gamma); } case '-': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth,beta, exception); return(-1.0*gamma); } case '~': { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,expression+1,depth,beta, exception); return((~(size_t) (gamma+0.5))); } case 'A': case 'a': { if (LocaleNCompare(expression,"abs",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(fabs(alpha)); } #if defined(MAGICKCORE_HAVE_ACOSH) if (LocaleNCompare(expression,"acosh",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(acosh(alpha)); } #endif if (LocaleNCompare(expression,"acos",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(acos(alpha)); } #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"airy",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); if (alpha == 0.0) return(1.0); gamma=2.0*j1((MagickPI*alpha))/(MagickPI*alpha); return(gamma*gamma); } #endif #if defined(MAGICKCORE_HAVE_ASINH) if (LocaleNCompare(expression,"asinh",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(asinh(alpha)); } #endif if (LocaleNCompare(expression,"asin",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(asin(alpha)); } if (LocaleNCompare(expression,"alt",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0); } if (LocaleNCompare(expression,"atan2",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(atan2(alpha,*beta)); } #if defined(MAGICKCORE_HAVE_ATANH) if (LocaleNCompare(expression,"atanh",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(atanh(alpha)); } #endif if (LocaleNCompare(expression,"atan",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(atan(alpha)); } if (LocaleCompare(expression,"a") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'B': case 'b': { if (LocaleCompare(expression,"b") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'C': case 'c': { if (LocaleNCompare(expression,"ceil",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(ceil(alpha)); } if (LocaleNCompare(expression,"clamp",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); if (alpha < 0.0) return(0.0); if (alpha > 1.0) return(1.0); return(alpha); } if (LocaleNCompare(expression,"cosh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(cosh(alpha)); } if (LocaleNCompare(expression,"cos",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(cos(alpha)); } if (LocaleCompare(expression,"c") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'D': case 'd': { if (LocaleNCompare(expression,"debug",5) == 0) { const char *type; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); if (fx_info->images->colorspace == CMYKColorspace) switch (channel) { case CyanPixelChannel: type="cyan"; break; case MagentaPixelChannel: type="magenta"; break; case YellowPixelChannel: type="yellow"; break; case AlphaPixelChannel: type="opacity"; break; case BlackPixelChannel: type="black"; break; default: type="unknown"; break; } else switch (channel) { case RedPixelChannel: type="red"; break; case GreenPixelChannel: type="green"; break; case BluePixelChannel: type="blue"; break; case AlphaPixelChannel: type="opacity"; break; default: type="unknown"; break; } (void) CopyMagickString(subexpression,expression+6,MagickPathExtent); if (strlen(subexpression) > 1) subexpression[strlen(subexpression)-1]='\0'; if (fx_info->file != (FILE *) NULL) (void) FormatLocaleFile(fx_info->file,"%s[%.20g,%.20g].%s: " "%s=%.*g\n",fx_info->images->filename,(double) x,(double) y,type, subexpression,GetMagickPrecision(),alpha); return(0.0); } if (LocaleNCompare(expression,"drc",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return((alpha/(*beta*(alpha-1.0)+1.0))); } break; } case 'E': case 'e': { if (LocaleCompare(expression,"epsilon") == 0) return(MagickEpsilon); #if defined(MAGICKCORE_HAVE_ERF) if (LocaleNCompare(expression,"erf",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(erf(alpha)); } #endif if (LocaleNCompare(expression,"exp",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(exp(alpha)); } if (LocaleCompare(expression,"e") == 0) return(2.7182818284590452354); break; } case 'F': case 'f': { if (LocaleNCompare(expression,"floor",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(floor(alpha)); } break; } case 'G': case 'g': { if (LocaleNCompare(expression,"gauss",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); gamma=exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI); return(gamma); } if (LocaleNCompare(expression,"gcd",3) == 0) { MagickOffsetType gcd; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); gcd=FxGCD((MagickOffsetType) (alpha+0.5),(MagickOffsetType) (*beta+ 0.5)); return(gcd); } if (LocaleCompare(expression,"g") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'H': case 'h': { if (LocaleCompare(expression,"h") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleCompare(expression,"hue") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleNCompare(expression,"hypot",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(hypot(alpha,*beta)); } break; } case 'K': case 'k': { if (LocaleCompare(expression,"k") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'I': case 'i': { if (LocaleCompare(expression,"intensity") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleNCompare(expression,"int",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(floor(alpha)); } if (LocaleNCompare(expression,"isnan",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(!!IsNaN(alpha)); } if (LocaleCompare(expression,"i") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'J': case 'j': { if (LocaleCompare(expression,"j") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); #if defined(MAGICKCORE_HAVE_J0) if (LocaleNCompare(expression,"j0",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,depth, beta,exception); return(j0(alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"j1",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,depth, beta,exception); return(j1(alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (LocaleNCompare(expression,"jinc",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); if (alpha == 0.0) return(1.0); gamma=(2.0*j1((MagickPI*alpha))/(MagickPI*alpha)); return(gamma); } #endif break; } case 'L': case 'l': { if (LocaleNCompare(expression,"ln",2) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2,depth, beta,exception); return(log(alpha)); } if (LocaleNCompare(expression,"logtwo",6) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,depth, beta,exception); return(log10(alpha))/log10(2.0); } if (LocaleNCompare(expression,"log",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(log10(alpha)); } if (LocaleCompare(expression,"lightness") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'M': case 'm': { if (LocaleCompare(expression,"MaxRGB") == 0) return(QuantumRange); if (LocaleNCompare(expression,"maxima",6) == 0) break; if (LocaleNCompare(expression,"max",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(alpha > *beta ? alpha : *beta); } if (LocaleNCompare(expression,"minima",6) == 0) break; if (LocaleNCompare(expression,"min",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(alpha < *beta ? alpha : *beta); } if (LocaleNCompare(expression,"mod",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); gamma=alpha-floor((alpha/(*beta)))*(*beta); return(gamma); } if (LocaleCompare(expression,"m") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'N': case 'n': { if (LocaleNCompare(expression,"not",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return((alpha < MagickEpsilon)); } if (LocaleCompare(expression,"n") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'O': case 'o': { if (LocaleCompare(expression,"Opaque") == 0) return(1.0); if (LocaleCompare(expression,"o") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'P': case 'p': { if (LocaleCompare(expression,"phi") == 0) return(MagickPHI); if (LocaleCompare(expression,"pi") == 0) return(MagickPI); if (LocaleNCompare(expression,"pow",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(pow(alpha,*beta)); } if (LocaleCompare(expression,"p") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'Q': case 'q': { if (LocaleCompare(expression,"QuantumRange") == 0) return(QuantumRange); if (LocaleCompare(expression,"QuantumScale") == 0) return(QuantumScale); break; } case 'R': case 'r': { if (LocaleNCompare(expression,"rand",4) == 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FxEvaluateSubexpression) #endif alpha=GetPseudoRandomValue(fx_info->random_info); return(alpha); } if (LocaleNCompare(expression,"round",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); return(floor(alpha+0.5)); } if (LocaleCompare(expression,"r") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'S': case 's': { if (LocaleCompare(expression,"saturation") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); if (LocaleNCompare(expression,"sign",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(alpha < 0.0 ? -1.0 : 1.0); } if (LocaleNCompare(expression,"sinc",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); if (alpha == 0) return(1.0); gamma=sin((MagickPI*alpha))/(MagickPI*alpha); return(gamma); } if (LocaleNCompare(expression,"sinh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(sinh(alpha)); } if (LocaleNCompare(expression,"sin",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(sin(alpha)); } if (LocaleNCompare(expression,"sqrt",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(sqrt(alpha)); } if (LocaleNCompare(expression,"squish",6) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6,depth, beta,exception); return((1.0/(1.0+exp(-alpha)))); } if (LocaleCompare(expression,"s") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'T': case 't': { if (LocaleNCompare(expression,"tanh",4) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4,depth, beta,exception); return(tanh(alpha)); } if (LocaleNCompare(expression,"tan",3) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3,depth, beta,exception); return(tan(alpha)); } if (LocaleCompare(expression,"Transparent") == 0) return(0.0); if (LocaleNCompare(expression,"trunc",5) == 0) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5,depth, beta,exception); if (alpha >= 0.0) return(floor(alpha)); return(ceil(alpha)); } if (LocaleCompare(expression,"t") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'U': case 'u': { if (LocaleCompare(expression,"u") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'V': case 'v': { if (LocaleCompare(expression,"v") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'W': case 'w': { if (LocaleNCompare(expression,"while",5) == 0) { do { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth,beta,exception); } while (fabs(alpha) >= MagickEpsilon); return(*beta); } if (LocaleCompare(expression,"w") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'Y': case 'y': { if (LocaleCompare(expression,"y") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } case 'Z': case 'z': { if (LocaleCompare(expression,"z") == 0) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); break; } default: break; } q=(char *) expression; alpha=InterpretSiPrefixValue(expression,&q); if (q == expression) return(FxGetSymbol(fx_info,channel,x,y,expression,exception)); return(alpha); } MagickPrivate MagickBooleanType FxEvaluateExpression(FxInfo *fx_info, double *alpha,ExceptionInfo *exception) { MagickBooleanType status; status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha, exception); return(status); } MagickExport MagickBooleanType FxPreprocessExpression(FxInfo *fx_info, double *alpha,ExceptionInfo *exception) { FILE *file; MagickBooleanType status; file=fx_info->file; fx_info->file=(FILE *) NULL; status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,0,0,alpha, exception); fx_info->file=file; return(status); } MagickPrivate MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info, const PixelChannel channel,const ssize_t x,const ssize_t y, double *alpha,ExceptionInfo *exception) { double beta; size_t depth; depth=0; beta=0.0; *alpha=FxEvaluateSubexpression(fx_info,channel,x,y,fx_info->expression,&depth, &beta,exception); return(exception->severity == OptionError ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FxImage() applies a mathematical expression to the specified image. % % The format of the FxImage method is: % % Image *FxImage(const Image *image,const char *expression, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o expression: A mathematical expression. % % o exception: return any errors or warnings in this structure. % */ static FxInfo **DestroyFxThreadSet(FxInfo **fx_info) { register ssize_t i; assert(fx_info != (FxInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (fx_info[i] != (FxInfo *) NULL) fx_info[i]=DestroyFxInfo(fx_info[i]); fx_info=(FxInfo **) RelinquishMagickMemory(fx_info); return(fx_info); } static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression, ExceptionInfo *exception) { char *fx_expression; FxInfo **fx_info; double alpha; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info)); if (fx_info == (FxInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return((FxInfo **) NULL); } (void) ResetMagickMemory(fx_info,0,number_threads*sizeof(*fx_info)); if (*expression != '@') fx_expression=ConstantString(expression); else fx_expression=FileToString(expression+1,~0UL,exception); for (i=0; i < (ssize_t) number_threads; i++) { MagickBooleanType status; fx_info[i]=AcquireFxInfo(image,fx_expression,exception); if (fx_info[i] == (FxInfo *) NULL) break; status=FxPreprocessExpression(fx_info[i],&alpha,exception); if (status == MagickFalse) break; } fx_expression=DestroyString(fx_expression); if (i < (ssize_t) number_threads) fx_info=DestroyFxThreadSet(fx_info); return(fx_info); } MagickExport Image *FxImage(const Image *image,const char *expression, ExceptionInfo *exception) { #define FxImageTag "Fx/Image" CacheView *fx_view, *image_view; FxInfo **magick_restrict fx_info; Image *fx_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); fx_info=AcquireFxThreadSet(image,expression,exception); if (fx_info == (FxInfo **) NULL) return((Image *) NULL); fx_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (fx_image == (Image *) NULL) { fx_info=DestroyFxThreadSet(fx_info); return((Image *) NULL); } if (SetImageStorageClass(fx_image,DirectClass,exception) == MagickFalse) { fx_info=DestroyFxThreadSet(fx_info); fx_image=DestroyImage(fx_image); return((Image *) NULL); } /* Fx image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); fx_view=AcquireAuthenticCacheView(fx_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,fx_image,fx_image->rows,1) #endif for (y=0; y < (ssize_t) fx_image->rows; y++) { const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) fx_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait fx_traits=GetPixelChannelTraits(fx_image,channel); if ((traits == UndefinedPixelTrait) || (fx_traits == UndefinedPixelTrait)) continue; if (((fx_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(fx_image,channel,p[i],q); continue; } alpha=0.0; (void) FxEvaluateChannelExpression(fx_info[id],channel,x,y,&alpha, exception); q[i]=ClampToQuantum(QuantumRange*alpha); } p+=GetPixelChannels(image); q+=GetPixelChannels(fx_image); } if (SyncCacheViewAuthenticPixels(fx_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FxImage) #endif proceed=SetImageProgress(image,FxImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } fx_view=DestroyCacheView(fx_view); image_view=DestroyCacheView(image_view); fx_info=DestroyFxThreadSet(fx_info); if (status == MagickFalse) fx_image=DestroyImage(fx_image); return(fx_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p l o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImplodeImage() creates a new image that is a copy of an existing % one with the image pixels "implode" by the specified percentage. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ImplodeImage method is: % % Image *ImplodeImage(const Image *image,const double amount, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o implode_image: Method ImplodeImage returns a pointer to the image % after it is implode. A null image is returned if there is a memory % shortage. % % o image: the image. % % o amount: Define the extent of the implosion. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ImplodeImage(const Image *image,const double amount, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ImplodeImageTag "Implode/Image" CacheView *image_view, *implode_view, *interpolate_view; Image *implode_image; MagickBooleanType status; MagickOffsetType progress; double radius; PointInfo center, scale; ssize_t y; /* Initialize implode 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); implode_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (implode_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse) { implode_image=DestroyImage(implode_image); return((Image *) NULL); } if (implode_image->background_color.alpha != OpaqueAlpha) implode_image->alpha_trait=BlendPixelTrait; /* Compute scaling factor. */ scale.x=1.0; scale.y=1.0; center.x=0.5*image->columns; center.y=0.5*image->rows; radius=center.x; if (image->columns > image->rows) scale.y=(double) image->columns/(double) image->rows; else if (image->columns < image->rows) { scale.x=(double) image->rows/(double) image->columns; radius=center.y; } /* Implode image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); interpolate_view=AcquireVirtualCacheView(image,exception); implode_view=AcquireAuthenticCacheView(implode_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,implode_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double distance; PointInfo delta; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; /* Determine if the pixel is within an ellipse. */ if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(implode_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(implode_image); continue; } delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait implode_traits=GetPixelChannelTraits(implode_image, channel); if ((traits == UndefinedPixelTrait) || (implode_traits == UndefinedPixelTrait)) continue; SetPixelChannel(implode_image,channel,p[i],q); } else { double factor; /* Implode the pixel. */ factor=1.0; if (distance > 0.0) factor=pow(sin(MagickPI*sqrt((double) distance)/radius/2),-amount); status=InterpolatePixelChannels(image,interpolate_view,implode_image, method,(double) (factor*delta.x/scale.x+center.x),(double) (factor* delta.y/scale.y+center.y),q,exception); } p+=GetPixelChannels(image); q+=GetPixelChannels(implode_image); } if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ImplodeImage) #endif proceed=SetImageProgress(image,ImplodeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } implode_view=DestroyCacheView(implode_view); interpolate_view=DestroyCacheView(interpolate_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) implode_image=DestroyImage(implode_image); return(implode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The MorphImages() method requires a minimum of two images. The first % image is transformed into the second by a number of intervening images % as specified by frames. % % The format of the MorphImage method is: % % Image *MorphImages(const Image *image,const size_t number_frames, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_frames: Define the number of in-between image to generate. % The more in-between frames, the smoother the morph. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphImages(const Image *image,const size_t number_frames, ExceptionInfo *exception) { #define MorphImageTag "Morph/Image" double alpha, beta; Image *morph_image, *morph_images; MagickBooleanType status; MagickOffsetType scene; register const Image *next; register ssize_t n; ssize_t y; /* Clone first frame in sequence. */ 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); morph_images=CloneImage(image,0,0,MagickTrue,exception); if (morph_images == (Image *) NULL) return((Image *) NULL); if (GetNextImageInList(image) == (Image *) NULL) { /* Morph single image. */ for (n=1; n < (ssize_t) number_frames; n++) { morph_image=CloneImage(image,0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n, number_frames); if (proceed == MagickFalse) status=MagickFalse; } } return(GetFirstImageInList(morph_images)); } /* Morph image sequence. */ status=MagickTrue; scene=0; next=image; for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next)) { for (n=0; n < (ssize_t) number_frames; n++) { CacheView *image_view, *morph_view; beta=(double) (n+1.0)/(double) (number_frames+1.0); alpha=1.0-beta; morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta* GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta* GetNextImageInList(next)->rows+0.5),next->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } status=SetImageStorageClass(morph_image,DirectClass,exception); if (status == MagickFalse) { morph_image=DestroyImage(morph_image); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns, morph_images->rows,GetNextImageInList(next)->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } image_view=AcquireVirtualCacheView(morph_image,exception); morph_view=AcquireAuthenticCacheView(morph_images,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(morph_image,morph_image,morph_image->rows,1) #endif for (y=0; y < (ssize_t) morph_images->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1, exception); q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) morph_images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++) { PixelChannel channel=GetPixelChannelChannel(morph_image,i); PixelTrait traits=GetPixelChannelTraits(morph_image,channel); PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel); if ((traits == UndefinedPixelTrait) || (morph_traits == UndefinedPixelTrait)) continue; if (((morph_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(morph_images,p) == 0)) { SetPixelChannel(morph_image,channel,p[i],q); continue; } SetPixelChannel(morph_image,channel,ClampToQuantum(alpha* GetPixelChannel(morph_images,channel,q)+beta*p[i]),q); } p+=GetPixelChannels(morph_image); q+=GetPixelChannels(morph_images); } sync=SyncCacheViewAuthenticPixels(morph_view,exception); if (sync == MagickFalse) status=MagickFalse; } morph_view=DestroyCacheView(morph_view); image_view=DestroyCacheView(image_view); morph_image=DestroyImage(morph_image); } if (n < (ssize_t) number_frames) break; /* Clone last frame in sequence. */ morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MorphImages) #endif proceed=SetImageProgress(image,MorphImageTag,scene, GetImageListLength(image)); if (proceed == MagickFalse) status=MagickFalse; } scene++; } if (GetNextImageInList(next) != (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } return(GetFirstImageInList(morph_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P l a s m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PlasmaImage() initializes an image with plasma fractal values. The image % must be initialized with a base color and the random number generator % seeded before this method is called. % % The format of the PlasmaImage method is: % % MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment, % size_t attenuate,size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o segment: Define the region to apply plasma fractals values. % % o attenuate: Define the plasma attenuation factor. % % o depth: Limit the plasma recursion depth. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PlasmaPixel(RandomInfo *random_info, const double pixel,const double noise) { Quantum plasma; plasma=ClampToQuantum(pixel+noise*GetPseudoRandomValue(random_info)- noise/2.0); if (plasma <= 0) return((Quantum) 0); if (plasma >= QuantumRange) return(QuantumRange); return(plasma); } static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view, CacheView *u_view,CacheView *v_view,RandomInfo *random_info, const SegmentInfo *segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { double plasma; register const Quantum *magick_restrict u, *magick_restrict v; register Quantum *magick_restrict q; register ssize_t i; ssize_t x, x_mid, y, y_mid; if ((fabs(segment->x2-segment->x1) <= MagickEpsilon) && (fabs(segment->y2-segment->y1) <= MagickEpsilon)) return(MagickTrue); if (depth != 0) { MagickBooleanType status; SegmentInfo local_info; /* Divide the area into quadrants and recurse. */ depth--; attenuate++; x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); local_info=(*segment); local_info.x2=(double) x_mid; local_info.y2=(double) y_mid; (void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.y1=(double) y_mid; local_info.x2=(double) x_mid; (void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y2=(double) y_mid; (void) PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y1=(double) y_mid; status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); return(status); } x_mid=(ssize_t) ceil((segment->x1+segment->x2)/2-0.5); y_mid=(ssize_t) ceil((segment->y1+segment->y2)/2-0.5); if ((fabs(segment->x1-x_mid) < MagickEpsilon) && (fabs(segment->x2-x_mid) < MagickEpsilon) && (fabs(segment->y1-y_mid) < MagickEpsilon) && (fabs(segment->y2-y_mid) < MagickEpsilon)) return(MagickFalse); /* Average pixels and apply plasma. */ plasma=(double) QuantumRange/(2.0*attenuate); if ((fabs(segment->x1-x_mid) > MagickEpsilon) || (fabs(segment->x2-x_mid) > MagickEpsilon)) { /* Left pixel. */ x=(ssize_t) ceil(segment->x1-0.5); u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5),1,1, exception); v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5),1,1, exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma); } (void) SyncCacheViewAuthenticPixels(image_view,exception); if (fabs(segment->x1-segment->x2) > MagickEpsilon) { /* Right pixel. */ x=(ssize_t) ceil(segment->x2-0.5); u=GetCacheViewVirtualPixels(u_view,x,(ssize_t) ceil(segment->y1-0.5), 1,1,exception); v=GetCacheViewVirtualPixels(v_view,x,(ssize_t) ceil(segment->y2-0.5), 1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma); } (void) SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->y1-y_mid) > MagickEpsilon) || (fabs(segment->y2-y_mid) > MagickEpsilon)) { if ((fabs(segment->x1-x_mid) > MagickEpsilon) || (fabs(segment->y2-y_mid) > MagickEpsilon)) { /* Bottom pixel. */ y=(ssize_t) ceil(segment->y2-0.5); u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y, 1,1,exception); v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y, 1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma); } (void) SyncCacheViewAuthenticPixels(image_view,exception); } if (fabs(segment->y1-segment->y2) > MagickEpsilon) { /* Top pixel. */ y=(ssize_t) ceil(segment->y1-0.5); u=GetCacheViewVirtualPixels(u_view,(ssize_t) ceil(segment->x1-0.5),y, 1,1,exception); v=GetCacheViewVirtualPixels(v_view,(ssize_t) ceil(segment->x2-0.5),y, 1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma); } (void) SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->x1-segment->x2) > MagickEpsilon) || (fabs(segment->y1-segment->y2) > MagickEpsilon)) { /* Middle pixel. */ x=(ssize_t) ceil(segment->x1-0.5); y=(ssize_t) ceil(segment->y1-0.5); u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception); x=(ssize_t) ceil(segment->x2-0.5); y=(ssize_t) ceil(segment->y2-0.5); v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,(u[i]+v[i])/2.0,plasma); } (void) SyncCacheViewAuthenticPixels(image_view,exception); } if ((fabs(segment->x2-segment->x1) < 3.0) && (fabs(segment->y2-segment->y1) < 3.0)) return(MagickTrue); return(MagickFalse); } MagickExport MagickBooleanType PlasmaImage(Image *image, const SegmentInfo *segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { CacheView *image_view, *u_view, *v_view; MagickBooleanType status; RandomInfo *random_info; if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); u_view=AcquireVirtualCacheView(image,exception); v_view=AcquireVirtualCacheView(image,exception); random_info=AcquireRandomInfo(); status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment, attenuate,depth,exception); random_info=DestroyRandomInfo(random_info); v_view=DestroyCacheView(v_view); u_view=DestroyCacheView(u_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l a r o i d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolaroidImage() simulates a Polaroid picture. % % The format of the PolaroidImage method is: % % Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, % const char *caption,const double angle, % const PixelInterpolateMethod method,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o caption: the Polaroid caption. % % o angle: Apply the effect along this angle. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, const char *caption,const double angle,const PixelInterpolateMethod method, ExceptionInfo *exception) { Image *bend_image, *caption_image, *flop_image, *picture_image, *polaroid_image, *rotate_image, *trim_image; size_t height; ssize_t quantum; /* Simulate a Polaroid picture. */ 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); quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double) image->rows)/25.0,10.0); height=image->rows+2*quantum; caption_image=(Image *) NULL; if (caption != (const char *) NULL) { char geometry[MagickPathExtent], *text; DrawInfo *annotate_info; ImageInfo *image_info; MagickBooleanType status; ssize_t count; TypeMetric metrics; /* Generate caption image. */ caption_image=CloneImage(image,image->columns,1,MagickTrue,exception); if (caption_image == (Image *) NULL) return((Image *) NULL); image_info=AcquireImageInfo(); annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info); text=InterpretImageProperties(image_info,(Image *) image,caption, exception); image_info=DestroyImageInfo(image_info); (void) CloneString(&annotate_info->text,text); count=FormatMagickCaption(caption_image,annotate_info,MagickTrue,&metrics, &text,exception); status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)* (metrics.ascent-metrics.descent)+0.5),exception); if (status == MagickFalse) caption_image=DestroyImage(caption_image); else { caption_image->background_color=image->border_color; (void) SetImageBackgroundColor(caption_image,exception); (void) CloneString(&annotate_info->text,text); (void) FormatLocaleString(geometry,MagickPathExtent,"+0+%g", metrics.ascent); if (annotate_info->gravity == UndefinedGravity) (void) CloneString(&annotate_info->geometry,AcquireString( geometry)); (void) AnnotateImage(caption_image,annotate_info,exception); height+=caption_image->rows; } annotate_info=DestroyDrawInfo(annotate_info); text=DestroyString(text); } picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue, exception); if (picture_image == (Image *) NULL) { if (caption_image != (Image *) NULL) caption_image=DestroyImage(caption_image); return((Image *) NULL); } picture_image->background_color=image->border_color; (void) SetImageBackgroundColor(picture_image,exception); (void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum, quantum,exception); if (caption_image != (Image *) NULL) { (void) CompositeImage(picture_image,caption_image,OverCompositeOp, MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception); caption_image=DestroyImage(caption_image); } (void) QueryColorCompliance("none",AllCompliance, &picture_image->background_color,exception); (void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception); rotate_image=RotateImage(picture_image,90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0* picture_image->columns,method,exception); picture_image=DestroyImage(picture_image); if (bend_image == (Image *) NULL) return((Image *) NULL); picture_image=bend_image; rotate_image=RotateImage(picture_image,-90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; picture_image->background_color=image->background_color; polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3, exception); if (polaroid_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } flop_image=FlopImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (flop_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } polaroid_image=flop_image; (void) CompositeImage(polaroid_image,picture_image,OverCompositeOp, MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception); picture_image=DestroyImage(picture_image); (void) QueryColorCompliance("none",AllCompliance, &polaroid_image->background_color,exception); rotate_image=RotateImage(polaroid_image,angle,exception); polaroid_image=DestroyImage(polaroid_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); polaroid_image=rotate_image; trim_image=TrimImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (trim_image == (Image *) NULL) return((Image *) NULL); polaroid_image=trim_image; return(polaroid_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e p i a T o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSepiaToneImage() applies a special effect to the image, similar to the % effect achieved in a photo darkroom by sepia toning. Threshold ranges from % 0 to QuantumRange and is a measure of the extent of the sepia toning. A % threshold of 80% is a good starting point for a reasonable tone. % % The format of the SepiaToneImage method is: % % Image *SepiaToneImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: the tone threshold. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SepiaToneImage(const Image *image,const double threshold, ExceptionInfo *exception) { #define SepiaToneImageTag "SepiaTone/Image" CacheView *image_view, *sepia_view; Image *sepia_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize sepia-toned image attributes. */ assert(image != (const 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); sepia_image=CloneImage(image,0,0,MagickTrue,exception); if (sepia_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse) { sepia_image=DestroyImage(sepia_image); return((Image *) NULL); } /* Tone each row of the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sepia_view=AcquireAuthenticCacheView(sepia_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,sepia_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double intensity, tone; intensity=GetPixelIntensity(image,p); tone=intensity > threshold ? (double) QuantumRange : intensity+ (double) QuantumRange-threshold; SetPixelRed(sepia_image,ClampToQuantum(tone),q); tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange : intensity+(double) QuantumRange-7.0*threshold/6.0; SetPixelGreen(sepia_image,ClampToQuantum(tone),q); tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0; SetPixelBlue(sepia_image,ClampToQuantum(tone),q); tone=threshold/7.0; if ((double) GetPixelGreen(image,q) < tone) SetPixelGreen(sepia_image,ClampToQuantum(tone),q); if ((double) GetPixelBlue(image,q) < tone) SetPixelBlue(sepia_image,ClampToQuantum(tone),q); SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(sepia_image); } if (SyncCacheViewAuthenticPixels(sepia_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SepiaToneImage) #endif proceed=SetImageProgress(image,SepiaToneImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sepia_view=DestroyCacheView(sepia_view); image_view=DestroyCacheView(image_view); (void) NormalizeImage(sepia_image,exception); (void) ContrastImage(sepia_image,MagickTrue,exception); if (status == MagickFalse) sepia_image=DestroyImage(sepia_image); return(sepia_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d o w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadowImage() simulates a shadow from the specified image and returns it. % % The format of the ShadowImage method is: % % Image *ShadowImage(const Image *image,const double alpha, % const double sigma,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: percentage transparency. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x_offset: the shadow x-offset. % % o y_offset: the shadow y-offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadowImage(const Image *image,const double alpha, const double sigma,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define ShadowImageTag "Shadow/Image" CacheView *image_view; ChannelType channel_mask; Image *border_image, *clone_image, *shadow_image; MagickBooleanType status; PixelInfo background_color; RectangleInfo border_info; ssize_t y; 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); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(clone_image,sRGBColorspace,exception); (void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod, exception); border_info.width=(size_t) floor(2.0*sigma+0.5); border_info.height=(size_t) floor(2.0*sigma+0.5); border_info.x=0; border_info.y=0; (void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color, exception); clone_image->alpha_trait=BlendPixelTrait; border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception); clone_image=DestroyImage(clone_image); if (border_image == (Image *) NULL) return((Image *) NULL); if (border_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception); /* Shadow image. */ status=MagickTrue; background_color=border_image->background_color; background_color.alpha_trait=BlendPixelTrait; image_view=AcquireAuthenticCacheView(border_image,exception); for (y=0; y < (ssize_t) border_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) border_image->columns; x++) { if (border_image->alpha_trait != UndefinedPixelTrait) background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0; SetPixelViaPixelInfo(border_image,&background_color,q); q+=GetPixelChannels(border_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { border_image=DestroyImage(border_image); return((Image *) NULL); } channel_mask=SetImageChannelMask(border_image,AlphaChannel); shadow_image=BlurImage(border_image,0.0,sigma,exception); border_image=DestroyImage(border_image); if (shadow_image == (Image *) NULL) return((Image *) NULL); (void) SetPixelChannelMask(shadow_image,channel_mask); if (shadow_image->page.width == 0) shadow_image->page.width=shadow_image->columns; if (shadow_image->page.height == 0) shadow_image->page.height=shadow_image->rows; shadow_image->page.width+=x_offset-(ssize_t) border_info.width; shadow_image->page.height+=y_offset-(ssize_t) border_info.height; shadow_image->page.x+=x_offset-(ssize_t) border_info.width; shadow_image->page.y+=y_offset-(ssize_t) border_info.height; return(shadow_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S k e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SketchImage() simulates a pencil sketch. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SketchImage() selects a suitable radius for you. Angle gives the angle % of the sketch. % % The format of the SketchImage method is: % % Image *SketchImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the % center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SketchImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { CacheView *random_view; Image *blend_image, *blur_image, *dodge_image, *random_image, *sketch_image; MagickBooleanType status; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Sketch image. */ random_image=CloneImage(image,image->columns << 1,image->rows << 1, MagickTrue,exception); if (random_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; random_info=AcquireRandomInfoThreadSet(); random_view=AcquireAuthenticCacheView(random_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(random_image,random_image,random_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) random_image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) random_image->columns; x++) { double value; register ssize_t i; if (GetPixelReadMask(random_image,q) == 0) { q+=GetPixelChannels(random_image); continue; } value=GetPseudoRandomValue(random_info[id]); for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=ClampToQuantum(QuantumRange*value); } q+=GetPixelChannels(random_image); } if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse) status=MagickFalse; } random_view=DestroyCacheView(random_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) { random_image=DestroyImage(random_image); return(random_image); } blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception); random_image=DestroyImage(random_image); if (blur_image == (Image *) NULL) return((Image *) NULL); dodge_image=EdgeImage(blur_image,radius,exception); blur_image=DestroyImage(blur_image); if (dodge_image == (Image *) NULL) return((Image *) NULL); (void) NormalizeImage(dodge_image,exception); (void) NegateImage(dodge_image,MagickFalse,exception); (void) TransformImage(&dodge_image,(char *) NULL,"50%",exception); sketch_image=CloneImage(image,0,0,MagickTrue,exception); if (sketch_image == (Image *) NULL) { dodge_image=DestroyImage(dodge_image); return((Image *) NULL); } (void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp, MagickTrue,0,0,exception); dodge_image=DestroyImage(dodge_image); blend_image=CloneImage(image,0,0,MagickTrue,exception); if (blend_image == (Image *) NULL) { sketch_image=DestroyImage(sketch_image); return((Image *) NULL); } if (blend_image->alpha_trait != BlendPixelTrait) (void) SetImageAlpha(blend_image,TransparentAlpha,exception); (void) SetImageArtifact(blend_image,"compose:args","20x80"); (void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue, 0,0,exception); blend_image=DestroyImage(blend_image); return(sketch_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o l a r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SolarizeImage() applies a special effect to the image, similar to the effect % achieved in a photo darkroom by selectively exposing areas of photo % sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a % measure of the extent of the solarization. % % The format of the SolarizeImage method is: % % MagickBooleanType SolarizeImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the extent of the solarization. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SolarizeImage(Image *image, const double threshold,ExceptionInfo *exception) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if (image->storage_class == PseudoClass) { register ssize_t i; /* Solarize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((double) image->colormap[i].red > threshold) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((double) image->colormap[i].green > threshold) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((double) image->colormap[i].blue > threshold) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } } /* Solarize image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] > threshold) q[i]=QuantumRange-q[i]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SolarizeImage) #endif proceed=SetImageProgress(image,SolarizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e g a n o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SteganoImage() hides a digital watermark within the image. Recover % the hidden watermark later to prove that the authenticity of an image. % Offset defines the start position within the image to hide the watermark. % % The format of the SteganoImage method is: % % Image *SteganoImage(const Image *image,Image *watermark, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o watermark: the watermark image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SteganoImage(const Image *image,const Image *watermark, ExceptionInfo *exception) { #define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0) #define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \ | (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i))) #define SteganoImageTag "Stegano/Image" CacheView *stegano_view, *watermark_view; Image *stegano_image; int c; MagickBooleanType status; PixelInfo pixel; register Quantum *q; register ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize steganographic image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(watermark != (const Image *) NULL); assert(watermark->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1UL; stegano_image=CloneImage(image,0,0,MagickTrue,exception); if (stegano_image == (Image *) NULL) return((Image *) NULL); stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH; if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse) { stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } /* Hide watermark in low-order bits of image. */ c=0; i=0; j=0; depth=stegano_image->depth; k=stegano_image->offset; status=MagickTrue; watermark_view=AcquireVirtualCacheView(watermark,exception); stegano_view=AcquireAuthenticCacheView(stegano_image,exception); for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++) { for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++) { ssize_t offset; (void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel, exception); offset=k/(ssize_t) stegano_image->columns; if (offset >= (ssize_t) stegano_image->rows) break; q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t) stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1, exception); if (q == (Quantum *) NULL) break; switch (c) { case 0: { SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 1: { SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 2: { SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } } if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (stegano_image->columns*stegano_image->columns)) k=0; if (k == stegano_image->offset) j++; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType) (depth-i),depth); if (proceed == MagickFalse) status=MagickFalse; } } stegano_view=DestroyCacheView(stegano_view); watermark_view=DestroyCacheView(watermark_view); if (status == MagickFalse) stegano_image=DestroyImage(stegano_image); return(stegano_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e r e o A n a g l y p h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StereoAnaglyphImage() combines two images and produces a single image that % is the composite of a left and right image of a stereo pair. Special % red-green stereo glasses are required to view this effect. % % The format of the StereoAnaglyphImage method is: % % Image *StereoImage(const Image *left_image,const Image *right_image, % ExceptionInfo *exception) % Image *StereoAnaglyphImage(const Image *left_image, % const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o left_image: the left image. % % o right_image: the right image. % % o exception: return any errors or warnings in this structure. % % o x_offset: amount, in pixels, by which the left image is offset to the % right of the right image. % % o y_offset: amount, in pixels, by which the left image is offset to the % bottom of the right image. % % */ MagickExport Image *StereoImage(const Image *left_image, const Image *right_image,ExceptionInfo *exception) { return(StereoAnaglyphImage(left_image,right_image,0,0,exception)); } MagickExport Image *StereoAnaglyphImage(const Image *left_image, const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define StereoImageTag "Stereo/Image" const Image *image; Image *stereo_image; MagickBooleanType status; ssize_t y; assert(left_image != (const Image *) NULL); assert(left_image->signature == MagickCoreSignature); if (left_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", left_image->filename); assert(right_image != (const Image *) NULL); assert(right_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(right_image != (const Image *) NULL); image=left_image; if ((left_image->columns != right_image->columns) || (left_image->rows != right_image->rows)) ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer"); /* Initialize stereo image attributes. */ stereo_image=CloneImage(left_image,left_image->columns,left_image->rows, MagickTrue,exception); if (stereo_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse) { stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } (void) SetImageColorspace(stereo_image,sRGBColorspace,exception); /* Copy left image to red channel and right image to blue channel. */ status=MagickTrue; for (y=0; y < (ssize_t) stereo_image->rows; y++) { register const Quantum *magick_restrict p, *magick_restrict q; register ssize_t x; register Quantum *magick_restrict r; p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1, exception); q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception); r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) || (r == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) stereo_image->columns; x++) { SetPixelRed(image,GetPixelRed(left_image,p),r); SetPixelGreen(image,GetPixelGreen(right_image,q),r); SetPixelBlue(image,GetPixelBlue(right_image,q),r); if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0) SetPixelAlpha(image,(GetPixelAlpha(left_image,p)+ GetPixelAlpha(right_image,q))/2,r); p+=GetPixelChannels(left_image); q+=GetPixelChannels(right_image); r+=GetPixelChannels(stereo_image); } if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse) break; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y, stereo_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (status == MagickFalse) stereo_image=DestroyImage(stereo_image); return(stereo_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S w i r l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SwirlImage() swirls the pixels about the center of the image, where % degrees indicates the sweep of the arc through which each pixel is moved. % You get a more dramatic effect as the degrees move from 1 to 360. % % The format of the SwirlImage method is: % % Image *SwirlImage(const Image *image,double degrees, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o degrees: Define the tightness of the swirling effect. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SwirlImage(const Image *image,double degrees, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define SwirlImageTag "Swirl/Image" CacheView *image_view, *interpolate_view, *swirl_view; Image *swirl_image; MagickBooleanType status; MagickOffsetType progress; double radius; PointInfo center, scale; ssize_t y; /* Initialize swirl image attributes. */ assert(image != (const 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); swirl_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (swirl_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse) { swirl_image=DestroyImage(swirl_image); return((Image *) NULL); } if (swirl_image->background_color.alpha != OpaqueAlpha) swirl_image->alpha_trait=BlendPixelTrait; /* Compute scaling factor. */ center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; radius=MagickMax(center.x,center.y); scale.x=1.0; scale.y=1.0; if (image->columns > image->rows) scale.y=(double) image->columns/(double) image->rows; else if (image->columns < image->rows) scale.x=(double) image->rows/(double) image->columns; degrees=(double) DegreesToRadians(degrees); /* Swirl image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); interpolate_view=AcquireVirtualCacheView(image,exception); swirl_view=AcquireAuthenticCacheView(swirl_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,swirl_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double distance; PointInfo delta; register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) image->columns; x++) { /* Determine if the pixel is within an ellipse. */ if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(swirl_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(swirl_image); continue; } delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait swirl_traits=GetPixelChannelTraits(swirl_image,channel); if ((traits == UndefinedPixelTrait) || (swirl_traits == UndefinedPixelTrait)) continue; SetPixelChannel(swirl_image,channel,p[i],q); } } else { double cosine, factor, sine; /* Swirl the pixel. */ factor=1.0-sqrt((double) distance)/radius; sine=sin((double) (degrees*factor*factor)); cosine=cos((double) (degrees*factor*factor)); status=InterpolatePixelChannels(image,interpolate_view,swirl_image, method,((cosine*delta.x-sine*delta.y)/scale.x+center.x),(double) ((sine*delta.x+cosine*delta.y)/scale.y+center.y),q,exception); } p+=GetPixelChannels(image); q+=GetPixelChannels(swirl_image); } if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SwirlImage) #endif proceed=SetImageProgress(image,SwirlImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } swirl_view=DestroyCacheView(swirl_view); interpolate_view=DestroyCacheView(interpolate_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) swirl_image=DestroyImage(swirl_image); return(swirl_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TintImage() applies a color vector to each pixel in the image. The length % of the vector is 0 for black and white and at its maximum for the midtones. % The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))) % % The format of the TintImage method is: % % Image *TintImage(const Image *image,const char *blend, % const PixelInfo *tint,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A color value used for tinting. % % o tint: A color value used for tinting. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TintImage(const Image *image,const char *blend, const PixelInfo *tint,ExceptionInfo *exception) { #define TintImageTag "Tint/Image" CacheView *image_view, *tint_view; double intensity; GeometryInfo geometry_info; Image *tint_image; MagickBooleanType status; MagickOffsetType progress; PixelInfo color_vector; MagickStatusType flags; ssize_t y; /* Allocate tint image. */ assert(image != (const 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); tint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (tint_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse) { tint_image=DestroyImage(tint_image); return((Image *) NULL); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsPixelInfoGray(tint) == MagickFalse)) (void) SetImageColorspace(tint_image,sRGBColorspace,exception); if (blend == (const char *) NULL) return(tint_image); /* Determine RGB values of the color. */ GetPixelInfo(image,&color_vector); flags=ParseGeometry(blend,&geometry_info); color_vector.red=geometry_info.rho; color_vector.green=geometry_info.rho; color_vector.blue=geometry_info.rho; color_vector.alpha=(MagickRealType) OpaqueAlpha; if ((flags & SigmaValue) != 0) color_vector.green=geometry_info.sigma; if ((flags & XiValue) != 0) color_vector.blue=geometry_info.xi; if ((flags & PsiValue) != 0) color_vector.alpha=geometry_info.psi; if (image->colorspace == CMYKColorspace) { color_vector.black=geometry_info.rho; if ((flags & PsiValue) != 0) color_vector.black=geometry_info.psi; if ((flags & ChiValue) != 0) color_vector.alpha=geometry_info.chi; } intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint); color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity); color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity); color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity); color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity); color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity); /* Tint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); tint_view=AcquireAuthenticCacheView(tint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,tint_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel; double weight; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait tint_traits=GetPixelChannelTraits(tint_image,channel); if ((traits == UndefinedPixelTrait) || (tint_traits == UndefinedPixelTrait)) continue; if (((tint_traits & CopyPixelTrait) != 0) || (GetPixelReadMask(image,p) == 0)) { SetPixelChannel(tint_image,channel,p[i],q); continue; } } GetPixelInfo(image,&pixel); weight=QuantumScale*GetPixelRed(image,p)-0.5; pixel.red=(double) GetPixelRed(image,p)+color_vector.red*(1.0-(4.0* (weight*weight))); weight=QuantumScale*GetPixelGreen(image,p)-0.5; pixel.green=(double) GetPixelGreen(image,p)+color_vector.green*(1.0-(4.0* (weight*weight))); weight=QuantumScale*GetPixelBlue(image,p)-0.5; pixel.blue=(double) GetPixelBlue(image,p)+color_vector.blue*(1.0-(4.0* (weight*weight))); weight=QuantumScale*GetPixelBlack(image,p)-0.5; pixel.black=(double) GetPixelBlack(image,p)+color_vector.black*(1.0-(4.0* (weight*weight))); SetPixelViaPixelInfo(tint_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(tint_image); } if (SyncCacheViewAuthenticPixels(tint_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TintImage) #endif proceed=SetImageProgress(image,TintImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } tint_view=DestroyCacheView(tint_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) tint_image=DestroyImage(tint_image); return(tint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V i g n e t t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % VignetteImage() softens the edges of the image in vignette style. % % The format of the VignetteImage method is: % % Image *VignetteImage(const Image *image,const double radius, % const double sigma,const ssize_t x,const ssize_t y, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x, y: Define the x and y ellipse offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *VignetteImage(const Image *image,const double radius, const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) { char ellipse[MagickPathExtent]; DrawInfo *draw_info; Image *canvas_image, *blur_image, *oval_image, *vignette_image; 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); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(canvas_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } canvas_image->alpha_trait=BlendPixelTrait; oval_image=CloneImage(canvas_image,canvas_image->columns,canvas_image->rows, MagickTrue,exception); if (oval_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } (void) QueryColorCompliance("#000000",AllCompliance, &oval_image->background_color,exception); (void) SetImageBackgroundColor(oval_image,exception); draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke, exception); (void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g," "0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x, image->rows/2.0-y); draw_info->primitive=AcquireString(ellipse); (void) DrawImage(oval_image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); blur_image=BlurImage(oval_image,radius,sigma,exception); oval_image=DestroyImage(oval_image); if (blur_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } blur_image->alpha_trait=UndefinedPixelTrait; (void) CompositeImage(canvas_image,blur_image,IntensityCompositeOp,MagickTrue, 0,0,exception); blur_image=DestroyImage(blur_image); vignette_image=MergeImageLayers(canvas_image,FlattenLayer,exception); canvas_image=DestroyImage(canvas_image); if (vignette_image != (Image *) NULL) (void) TransformImageColorspace(vignette_image,image->colorspace,exception); return(vignette_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveImage() creates a "ripple" effect in the image by shifting the pixels % vertically along a sine wave whose amplitude and wavelength is specified % by the given parameters. % % The format of the WaveImage method is: % % Image *WaveImage(const Image *image,const double amplitude, % const double wave_length,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o amplitude, wave_length: Define the amplitude and wave length of the % sine wave. % % o interpolate: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *image_view, *wave_view; Image *wave_image; MagickBooleanType status; MagickOffsetType progress; double *sine_map; register ssize_t i; ssize_t y; /* Initialize wave 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); wave_image=CloneImage(image,image->columns,(size_t) (image->rows+2.0* fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse) { wave_image=DestroyImage(wave_image); return((Image *) NULL); } if (wave_image->background_color.alpha != OpaqueAlpha) wave_image->alpha_trait=BlendPixelTrait; /* Allocate sine map. */ sine_map=(double *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (double *) NULL) { wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/ wave_length)); /* Wave image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); wave_view=AcquireAuthenticCacheView(wave_image,exception); (void) SetCacheViewVirtualPixelMethod(image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,wave_image,wave_image->rows,1) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) wave_image->columns; x++) { status=InterpolatePixelChannels(image,image_view,wave_image,method, (double) x,(double) (y-sine_map[x]),q,exception); q+=GetPixelChannels(wave_image); } if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_WaveImage) #endif proceed=SetImageProgress(image,WaveImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); image_view=DestroyCacheView(image_view); sine_map=(double *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e l e t D e n o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveletDenoiseImage() removes noise from the image using a wavelet % transform. The wavelet transform is a fast hierarchical scheme for % processing an image using a set of consecutive lowpass and high_pass filters, % followed by a decimation. This results in a decomposition into different % scales which can be regarded as different “frequency bands”, determined by % the mother wavelet. Adapted from dcraw.c by David Coffin. % % The format of the WaveletDenoiseImage method is: % % Image *WaveletDenoiseImage(const Image *image,const double threshold, % const double softness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: set the threshold for smoothing. % % o softness: attenuate the smoothing threshold. % % o exception: return any errors or warnings in this structure. % */ static inline void HatTransform(const float *magick_restrict pixels, const size_t stride,const size_t extent,const size_t scale,float *kernel) { const float *magick_restrict p, *magick_restrict q, *magick_restrict r; register ssize_t i; p=pixels; q=pixels+scale*stride; r=pixels+scale*stride; for (i=0; i < (ssize_t) scale; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q-=stride; r+=stride; } for ( ; i < (ssize_t) (extent-scale); i++) { kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride)); p+=stride; } q=p-scale*stride; r=pixels+stride*(extent-2); for ( ; i < (ssize_t) extent; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q+=stride; r-=stride; } } MagickExport Image *WaveletDenoiseImage(const Image *image, const double threshold,const double softness,ExceptionInfo *exception) { CacheView *image_view, *noise_view; float *kernel, *pixels; Image *noise_image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixels_info; ssize_t channel; static const float noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f, 0.0080f, 0.0044f }; /* Initialize noise image attributes. */ assert(image != (const 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); #if defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); pixels_info=AcquireVirtualMemory(3*image->columns,image->rows* sizeof(*pixels)); kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns), GetOpenMPMaximumThreads()*sizeof(*kernel)); if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL)) { if (kernel != (float *) NULL) kernel=(float *) RelinquishMagickMemory(kernel); if (pixels_info != (MemoryInfo *) NULL) pixels_info=RelinquishVirtualMemory(pixels_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(float *) GetVirtualMemoryBlob(pixels_info); status=MagickTrue; number_pixels=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++) { register ssize_t i; size_t high_pass, low_pass; ssize_t level, y; PixelChannel pixel_channel; PixelTrait traits; if (status == MagickFalse) continue; traits=GetPixelChannelTraits(image,(PixelChannel) channel); if (traits == UndefinedPixelTrait) continue; pixel_channel=GetPixelChannelChannel(image,channel); if ((pixel_channel != RedPixelChannel) && (pixel_channel != GreenPixelChannel) && (pixel_channel != BluePixelChannel)) continue; /* Copy channel from image to wavelet pixel array. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { pixels[i++]=(float) p[channel]; p+=GetPixelChannels(image); } } /* Low pass filter outputs are called approximation kernel & high pass filters are referred to as detail kernel. The detail kernel have high values in the noisy parts of the signal. */ high_pass=0; for (level=0; level < 5; level++) { double magnitude; ssize_t x, y; low_pass=(size_t) (number_pixels*((level & 0x01)+1)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register float *magick_restrict p, *magick_restrict q; register ssize_t x; p=kernel+id*image->columns; q=pixels+y*image->columns; HatTransform(q+high_pass,1,image->columns,(size_t) (1 << level),p); q+=low_pass; for (x=0; x < (ssize_t) image->columns; x++) *q++=(*p++); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); register float *magick_restrict p, *magick_restrict q; register ssize_t y; p=kernel+id*image->rows; q=pixels+x+low_pass; HatTransform(q,image->columns,image->rows,(size_t) (1 << level),p); for (y=0; y < (ssize_t) image->rows; y++) { *q=(*p++); q+=image->columns; } } /* To threshold, each coefficient is compared to a threshold value and attenuated / shrunk by some factor. */ magnitude=threshold*noise_levels[level]; for (i=0; i < (ssize_t) number_pixels; ++i) { pixels[high_pass+i]-=pixels[low_pass+i]; if (pixels[high_pass+i] < -magnitude) pixels[high_pass+i]+=magnitude-softness*magnitude; else if (pixels[high_pass+i] > magnitude) pixels[high_pass+i]-=magnitude-softness*magnitude; else pixels[high_pass+i]*=softness; if (high_pass != 0) pixels[i]+=pixels[high_pass+i]; } high_pass=low_pass; } /* Reconstruct image from the thresholded wavelet kernel. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; ssize_t offset; q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } offset=GetPixelChannelOffset(noise_image,pixel_channel); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType pixel; pixel=(MagickRealType) pixels[i]+pixels[low_pass+i]; q[offset]=ClampToQuantum(pixel); i++; q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType) channel,GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); kernel=(float *) RelinquishMagickMemory(kernel); pixels_info=RelinquishVirtualMemory(pixels_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5409_0
crossvul-cpp_data_good_5658_1
/*- * Copyright 1998 Juniper Networks, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libradius/radlib.c,v 1.4.2.3 2002/06/17 02:24:57 brian Exp $ */ #include <sys/types.h> #ifndef PHP_WIN32 #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #else #include <process.h> #include "win32/time.h" #endif #include <errno.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef PHP_WIN32 #include <unistd.h> #endif #include "radlib_compat.h" #include "radlib_md5.h" #include "radlib_private.h" static void clear_password(struct rad_handle *); static void generr(struct rad_handle *, const char *, ...) __printflike(2, 3); static void insert_scrambled_password(struct rad_handle *, int); static void insert_request_authenticator(struct rad_handle *, int); static int is_valid_response(struct rad_handle *, int, const struct sockaddr_in *); static int put_password_attr(struct rad_handle *, int, const void *, size_t); static int put_raw_attr(struct rad_handle *, int, const void *, size_t); static int split(char *, char *[], int, char *, size_t); static void clear_password(struct rad_handle *h) { if (h->pass_len != 0) { memset(h->pass, 0, h->pass_len); h->pass_len = 0; } h->pass_pos = 0; } static void generr(struct rad_handle *h, const char *format, ...) { va_list ap; va_start(ap, format); vsnprintf(h->errmsg, ERRSIZE, format, ap); va_end(ap); } static void insert_scrambled_password(struct rad_handle *h, int srv) { MD5_CTX ctx; unsigned char md5[16]; const struct rad_server *srvp; int padded_len; int pos; srvp = &h->servers[srv]; padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf; memcpy(md5, &h->request[POS_AUTH], LEN_AUTH); for (pos = 0; pos < padded_len; pos += 16) { int i; /* Calculate the new scrambler */ MD5Init(&ctx); MD5Update(&ctx, srvp->secret, strlen(srvp->secret)); MD5Update(&ctx, md5, 16); MD5Final(md5, &ctx); /* * Mix in the current chunk of the password, and copy * the result into the right place in the request. Also * modify the scrambler in place, since we will use this * in calculating the scrambler for next time. */ for (i = 0; i < 16; i++) h->request[h->pass_pos + pos + i] = md5[i] ^= h->pass[pos + i]; } } static void insert_request_authenticator(struct rad_handle *h, int srv) { MD5_CTX ctx; const struct rad_server *srvp; srvp = &h->servers[srv]; /* Create the request authenticator */ MD5Init(&ctx); MD5Update(&ctx, &h->request[POS_CODE], POS_AUTH - POS_CODE); MD5Update(&ctx, memset(&h->request[POS_AUTH], 0, LEN_AUTH), LEN_AUTH); MD5Update(&ctx, &h->request[POS_ATTRS], h->req_len - POS_ATTRS); MD5Update(&ctx, srvp->secret, strlen(srvp->secret)); MD5Final(&h->request[POS_AUTH], &ctx); } /* * Return true if the current response is valid for a request to the * specified server. */ static int is_valid_response(struct rad_handle *h, int srv, const struct sockaddr_in *from) { MD5_CTX ctx; unsigned char md5[16]; const struct rad_server *srvp; int len; srvp = &h->servers[srv]; /* Check the source address */ if (from->sin_family != srvp->addr.sin_family || from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr || from->sin_port != srvp->addr.sin_port) return 0; /* Check the message length */ if (h->resp_len < POS_ATTRS) return 0; len = h->response[POS_LENGTH] << 8 | h->response[POS_LENGTH+1]; if (len > h->resp_len) return 0; /* Check the response authenticator */ MD5Init(&ctx); MD5Update(&ctx, &h->response[POS_CODE], POS_AUTH - POS_CODE); MD5Update(&ctx, &h->request[POS_AUTH], LEN_AUTH); MD5Update(&ctx, &h->response[POS_ATTRS], len - POS_ATTRS); MD5Update(&ctx, srvp->secret, strlen(srvp->secret)); MD5Final(md5, &ctx); if (memcmp(&h->response[POS_AUTH], md5, sizeof md5) != 0) return 0; return 1; } static int put_password_attr(struct rad_handle *h, int type, const void *value, size_t len) { int padded_len; int pad_len; if (h->pass_pos != 0) { generr(h, "Multiple User-Password attributes specified"); return -1; } if (len > PASSSIZE) len = PASSSIZE; padded_len = len == 0 ? 16 : (len+15) & ~0xf; pad_len = padded_len - len; /* * Put in a place-holder attribute containing all zeros, and * remember where it is so we can fill it in later. */ clear_password(h); put_raw_attr(h, type, h->pass, padded_len); h->pass_pos = h->req_len - padded_len; /* Save the cleartext password, padded as necessary */ memcpy(h->pass, value, len); h->pass_len = len; memset(h->pass + len, 0, pad_len); return 0; } static int put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len) { if (len > 253) { generr(h, "Attribute too long"); return -1; } if (h->req_len + 2 + len > MSGSIZE) { generr(h, "Maximum message length exceeded"); return -1; } h->request[h->req_len++] = type; h->request[h->req_len++] = len + 2; memcpy(&h->request[h->req_len], value, len); h->req_len += len; return 0; } int rad_add_server(struct rad_handle *h, const char *host, int port, const char *secret, int timeout, int tries) { struct rad_server *srvp; if (h->num_servers >= MAXSERVERS) { generr(h, "Too many RADIUS servers specified"); return -1; } srvp = &h->servers[h->num_servers]; memset(&srvp->addr, 0, sizeof srvp->addr); srvp->addr.sin_family = AF_INET; if (!inet_aton(host, &srvp->addr.sin_addr)) { struct hostent *hent; if ((hent = gethostbyname(host)) == NULL) { generr(h, "%s: host not found", host); return -1; } memcpy(&srvp->addr.sin_addr, hent->h_addr, sizeof srvp->addr.sin_addr); } if (port != 0) srvp->addr.sin_port = htons((short) port); else { struct servent *sent; if (h->type == RADIUS_AUTH) srvp->addr.sin_port = (sent = getservbyname("radius", "udp")) != NULL ? sent->s_port : htons(RADIUS_PORT); else srvp->addr.sin_port = (sent = getservbyname("radacct", "udp")) != NULL ? sent->s_port : htons(RADACCT_PORT); } if ((srvp->secret = strdup(secret)) == NULL) { generr(h, "Out of memory"); return -1; } srvp->timeout = timeout; srvp->max_tries = tries; srvp->num_tries = 0; h->num_servers++; return 0; } void rad_close(struct rad_handle *h) { int srv; if (h->fd != -1) close(h->fd); for (srv = 0; srv < h->num_servers; srv++) { memset(h->servers[srv].secret, 0, strlen(h->servers[srv].secret)); free(h->servers[srv].secret); } clear_password(h); free(h); } int rad_config(struct rad_handle *h, const char *path) { FILE *fp; char buf[MAXCONFLINE]; int linenum; int retval; if (path == NULL) path = PATH_RADIUS_CONF; if ((fp = fopen(path, "r")) == NULL) { generr(h, "Cannot open \"%s\": %s", path, strerror(errno)); return -1; } retval = 0; linenum = 0; while (fgets(buf, sizeof buf, fp) != NULL) { int len; char *fields[5]; int nfields; char msg[ERRSIZE]; char *type; char *host, *res; char *port_str; char *secret; char *timeout_str; char *maxtries_str; char *end; char *wanttype; unsigned long timeout; unsigned long maxtries; int port; int i; linenum++; len = strlen(buf); /* We know len > 0, else fgets would have returned NULL. */ if (buf[len - 1] != '\n' && !(buf[len - 2] != '\r' && buf[len - 1] != '\n')) { if (len == sizeof buf - 1) generr(h, "%s:%d: line too long", path, linenum); else generr(h, "%s:%d: missing newline", path, linenum); retval = -1; break; } buf[len - 1] = '\0'; /* Extract the fields from the line. */ nfields = split(buf, fields, 5, msg, sizeof msg); if (nfields == -1) { generr(h, "%s:%d: %s", path, linenum, msg); retval = -1; break; } if (nfields == 0) continue; /* * The first field should contain "auth" or "acct" for * authentication or accounting, respectively. But older * versions of the file didn't have that field. Default * it to "auth" for backward compatibility. */ if (strcmp(fields[0], "auth") != 0 && strcmp(fields[0], "acct") != 0) { if (nfields >= 5) { generr(h, "%s:%d: invalid service type", path, linenum); retval = -1; break; } nfields++; for (i = nfields; --i > 0; ) fields[i] = fields[i - 1]; fields[0] = "auth"; } if (nfields < 3) { generr(h, "%s:%d: missing shared secret", path, linenum); retval = -1; break; } type = fields[0]; host = fields[1]; secret = fields[2]; timeout_str = fields[3]; maxtries_str = fields[4]; /* Ignore the line if it is for the wrong service type. */ wanttype = h->type == RADIUS_AUTH ? "auth" : "acct"; if (strcmp(type, wanttype) != 0) continue; /* Parse and validate the fields. */ res = host; host = strsep(&res, ":"); port_str = strsep(&res, ":"); if (port_str != NULL) { port = strtoul(port_str, &end, 10); if (*end != '\0') { generr(h, "%s:%d: invalid port", path, linenum); retval = -1; break; } } else port = 0; if (timeout_str != NULL) { timeout = strtoul(timeout_str, &end, 10); if (*end != '\0') { generr(h, "%s:%d: invalid timeout", path, linenum); retval = -1; break; } } else timeout = TIMEOUT; if (maxtries_str != NULL) { maxtries = strtoul(maxtries_str, &end, 10); if (*end != '\0') { generr(h, "%s:%d: invalid maxtries", path, linenum); retval = -1; break; } } else maxtries = MAXTRIES; if (rad_add_server(h, host, port, secret, timeout, maxtries) == -1) { strcpy(msg, h->errmsg); generr(h, "%s:%d: %s", path, linenum, msg); retval = -1; break; } } /* Clear out the buffer to wipe a possible copy of a shared secret */ memset(buf, 0, sizeof buf); fclose(fp); return retval; } /* * rad_init_send_request() must have previously been called. * Returns: * 0 The application should select on *fd with a timeout of tv before * calling rad_continue_send_request again. * < 0 Failure * > 0 Success */ int rad_continue_send_request(struct rad_handle *h, int selected, int *fd, struct timeval *tv) { int n; if (selected) { struct sockaddr_in from; int fromlen; fromlen = sizeof from; h->resp_len = recvfrom(h->fd, h->response, MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen); if (h->resp_len == -1) { #ifdef PHP_WIN32 generr(h, "recfrom: %d", WSAGetLastError()); #else generr(h, "recvfrom: %s", strerror(errno)); #endif return -1; } if (is_valid_response(h, h->srv, &from)) { h->resp_len = h->response[POS_LENGTH] << 8 | h->response[POS_LENGTH+1]; h->resp_pos = POS_ATTRS; return h->response[POS_CODE]; } } if (h->try == h->total_tries) { generr(h, "No valid RADIUS responses received"); return -1; } /* * Scan round-robin to the next server that has some * tries left. There is guaranteed to be one, or we * would have exited this loop by now. */ while (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) if (++h->srv >= h->num_servers) h->srv = 0; if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST) /* Insert the request authenticator into the request */ insert_request_authenticator(h, h->srv); else /* Insert the scrambled password into the request */ if (h->pass_pos != 0) insert_scrambled_password(h, h->srv); /* Send the request */ n = sendto(h->fd, h->request, h->req_len, 0, (const struct sockaddr *)&h->servers[h->srv].addr, sizeof h->servers[h->srv].addr); if (n != h->req_len) { if (n == -1) #ifdef PHP_WIN32 generr(h, "sendto: %d", WSAGetLastError()); #else generr(h, "sendto: %s", strerror(errno)); #endif else generr(h, "sendto: short write"); return -1; } h->try++; h->servers[h->srv].num_tries++; tv->tv_sec = h->servers[h->srv].timeout; tv->tv_usec = 0; *fd = h->fd; return 0; } int rad_create_request(struct rad_handle *h, int code) { int i; h->request[POS_CODE] = code; h->request[POS_IDENT] = ++h->ident; /* Create a random authenticator */ for (i = 0; i < LEN_AUTH; i += 2) { long r; TSRMLS_FETCH(); r = php_rand(TSRMLS_C); h->request[POS_AUTH+i] = (unsigned char) r; h->request[POS_AUTH+i+1] = (unsigned char) (r >> 8); } h->req_len = POS_ATTRS; h->request_created = 1; clear_password(h); return 0; } struct in_addr rad_cvt_addr(const void *data) { struct in_addr value; memcpy(&value.s_addr, data, sizeof value.s_addr); return value; } u_int32_t rad_cvt_int(const void *data) { u_int32_t value; memcpy(&value, data, sizeof value); return ntohl(value); } char * rad_cvt_string(const void *data, size_t len) { char *s; s = malloc(len + 1); if (s != NULL) { memcpy(s, data, len); s[len] = '\0'; } return s; } /* * Returns the attribute type. If none are left, returns 0. On failure, * returns -1. */ int rad_get_attr(struct rad_handle *h, const void **value, size_t *len) { int type; if (h->resp_pos >= h->resp_len) return 0; if (h->resp_pos + 2 > h->resp_len) { generr(h, "Malformed attribute in response"); return -1; } type = h->response[h->resp_pos++]; *len = h->response[h->resp_pos++] - 2; if (h->resp_pos + (int) *len > h->resp_len) { generr(h, "Malformed attribute in response"); return -1; } *value = &h->response[h->resp_pos]; h->resp_pos += *len; return type; } /* * Returns -1 on error, 0 to indicate no event and >0 for success */ int rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv) { int srv; /* Make sure we have a socket to use */ if (h->fd == -1) { struct sockaddr_in sin; if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { #ifdef PHP_WIN32 generr(h, "Cannot create socket: %d", WSAGetLastError()); #else generr(h, "Cannot create socket: %s", strerror(errno)); #endif return -1; } memset(&sin, 0, sizeof sin); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(0); if (bind(h->fd, (const struct sockaddr *)&sin, sizeof sin) == -1) { #ifdef PHP_WIN32 generr(h, "bind: %d", WSAGetLastError()); #else generr(h, "bind: %s", strerror(errno)); #endif close(h->fd); h->fd = -1; return -1; } } if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST) { /* Make sure no password given */ if (h->pass_pos || h->chap_pass) { generr(h, "User or Chap Password in accounting request"); return -1; } } else { /* Make sure the user gave us a password */ if (h->pass_pos == 0 && !h->chap_pass) { generr(h, "No User or Chap Password attributes given"); return -1; } if (h->pass_pos != 0 && h->chap_pass) { generr(h, "Both User and Chap Password attributes given"); return -1; } } /* Fill in the length field in the message */ h->request[POS_LENGTH] = h->req_len >> 8; h->request[POS_LENGTH+1] = h->req_len; /* * Count the total number of tries we will make, and zero the * counter for each server. */ h->total_tries = 0; for (srv = 0; srv < h->num_servers; srv++) { h->total_tries += h->servers[srv].max_tries; h->servers[srv].num_tries = 0; } if (h->total_tries == 0) { generr(h, "No RADIUS servers specified"); return -1; } h->try = h->srv = 0; return rad_continue_send_request(h, 0, fd, tv); } /* * Create and initialize a rad_handle structure, and return it to the * caller. Can fail only if the necessary memory cannot be allocated. * In that case, it returns NULL. */ struct rad_handle * rad_auth_open(void) { struct rad_handle *h; h = (struct rad_handle *)malloc(sizeof(struct rad_handle)); if (h != NULL) { TSRMLS_FETCH(); php_srand(time(NULL) * getpid() * (unsigned long) (php_combined_lcg(TSRMLS_C) * 10000.0) TSRMLS_CC); h->fd = -1; h->num_servers = 0; h->ident = php_rand(TSRMLS_C); h->errmsg[0] = '\0'; memset(h->pass, 0, sizeof h->pass); h->pass_len = 0; h->pass_pos = 0; h->chap_pass = 0; h->type = RADIUS_AUTH; h->request_created = 0; } return h; } struct rad_handle * rad_acct_open(void) { struct rad_handle *h; h = rad_open(); if (h != NULL) h->type = RADIUS_ACCT; return h; } struct rad_handle * rad_open(void) { return rad_auth_open(); } int rad_put_addr(struct rad_handle *h, int type, struct in_addr addr) { return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr); } int rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len) { int result; if (!h->request_created) { generr(h, "Please call rad_create_request()"); return -1; } if (type == RAD_USER_PASSWORD) result = put_password_attr(h, type, value, len); else { result = put_raw_attr(h, type, value, len); if (result == 0 && type == RAD_CHAP_PASSWORD) h->chap_pass = 1; } return result; } int rad_put_int(struct rad_handle *h, int type, u_int32_t value) { u_int32_t nvalue; nvalue = htonl(value); return rad_put_attr(h, type, &nvalue, sizeof nvalue); } int rad_put_string(struct rad_handle *h, int type, const char *str) { return rad_put_attr(h, type, str, strlen(str)); } /* * Returns the response type code on success, or -1 on failure. */ int rad_send_request(struct rad_handle *h) { struct timeval timelimit; struct timeval tv; int fd; int n; n = rad_init_send_request(h, &fd, &tv); if (n != 0) return n; gettimeofday(&timelimit, NULL); timeradd(&tv, &timelimit, &timelimit); for ( ; ; ) { fd_set readfds; FD_ZERO(&readfds); FD_SET(fd, &readfds); n = select(fd + 1, &readfds, NULL, NULL, &tv); if (n == -1) { generr(h, "select: %s", strerror(errno)); return -1; } if (!FD_ISSET(fd, &readfds)) { /* Compute a new timeout */ gettimeofday(&tv, NULL); timersub(&timelimit, &tv, &tv); if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0)) /* Continue the select */ continue; } n = rad_continue_send_request(h, n, &fd, &tv); if (n != 0) return n; gettimeofday(&timelimit, NULL); timeradd(&tv, &timelimit, &timelimit); } } const char * rad_strerror(struct rad_handle *h) { return h->errmsg; } /* * Destructively split a string into fields separated by white space. * `#' at the beginning of a field begins a comment that extends to the * end of the string. Fields may be quoted with `"'. Inside quoted * strings, the backslash escapes `\"' and `\\' are honored. * * Pointers to up to the first maxfields fields are stored in the fields * array. Missing fields get NULL pointers. * * The return value is the actual number of fields parsed, and is always * <= maxfields. * * On a syntax error, places a message in the msg string, and returns -1. */ static int split(char *str, char *fields[], int maxfields, char *msg, size_t msglen) { char *p; int i; static const char ws[] = " \t"; for (i = 0; i < maxfields; i++) fields[i] = NULL; p = str; i = 0; while (*p != '\0') { p += strspn(p, ws); if (*p == '#' || *p == '\0') break; if (i >= maxfields) { snprintf(msg, msglen, "line has too many fields"); return -1; } if (*p == '"') { char *dst; dst = ++p; fields[i] = dst; while (*p != '"') { if (*p == '\\') { p++; if (*p != '"' && *p != '\\' && *p != '\0') { snprintf(msg, msglen, "invalid `\\' escape"); return -1; } } if (*p == '\0') { snprintf(msg, msglen, "unterminated quoted string"); return -1; } *dst++ = *p++; } *dst = '\0'; p++; if (*fields[i] == '\0') { snprintf(msg, msglen, "empty quoted string not permitted"); return -1; } if (*p != '\0' && strspn(p, ws) == 0) { snprintf(msg, msglen, "quoted string not" " followed by white space"); return -1; } } else { fields[i] = p; p += strcspn(p, ws); if (*p != '\0') *p++ = '\0'; } i++; } return i; } int rad_get_vendor_attr(u_int32_t *vendor, unsigned char *type, const void **data, size_t *len, const void *raw, size_t raw_len) { struct vendor_attribute *attr; if (raw_len < sizeof(struct vendor_attribute)) { return -1; } attr = (struct vendor_attribute *) raw; *vendor = ntohl(attr->vendor_value); *type = attr->attrib_type; *data = attr->attrib_data; *len = attr->attrib_len - 2; if ((attr->attrib_len + 4) > raw_len) { return -1; } return (attr->attrib_type); } int rad_put_vendor_addr(struct rad_handle *h, int vendor, int type, struct in_addr addr) { return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr, sizeof addr.s_addr)); } int rad_put_vendor_attr(struct rad_handle *h, int vendor, int type, const void *value, size_t len) { struct vendor_attribute *attr; int res; if (!h->request_created) { generr(h, "Please call rad_create_request()"); return -1; } if ((attr = malloc(len + 6)) == NULL) { generr(h, "malloc failure (%d bytes)", len + 6); return -1; } attr->vendor_value = htonl(vendor); attr->attrib_type = type; attr->attrib_len = len + 2; memcpy(attr->attrib_data, value, len); res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6); free(attr); if (res == 0 && vendor == RAD_VENDOR_MICROSOFT && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) { h->chap_pass = 1; } return (res); } int rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i) { u_int32_t value; value = htonl(i); return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value)); } int rad_put_vendor_string(struct rad_handle *h, int vendor, int type, const char *str) { return (rad_put_vendor_attr(h, vendor, type, str, strlen(str))); } ssize_t rad_request_authenticator(struct rad_handle *h, char *buf, size_t len) { if (len < LEN_AUTH) return (-1); memcpy(buf, h->request + POS_AUTH, LEN_AUTH); if (len > LEN_AUTH) buf[LEN_AUTH] = '\0'; return (LEN_AUTH); } const char * rad_server_secret(struct rad_handle *h) { if (h->srv >= h->num_servers) { generr(h, "No RADIUS servers specified"); return NULL; } return (h->servers[h->srv].secret); } int rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen, u_char *demangled) { char R[LEN_AUTH]; const char *S; int i, Ppos; MD5_CTX Context; u_char b[16], *C; if ((mlen % 16 != 0) || (mlen > 128)) { generr(h, "Cannot interpret mangled data of length %ld", (u_long)mlen); return -1; } C = (u_char *)mangled; /* We need the shared secret as Salt */ S = rad_server_secret(h); /* We need the request authenticator */ if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) { generr(h, "Cannot obtain the RADIUS request authenticator"); return -1; } MD5Init(&Context); MD5Update(&Context, S, strlen(S)); MD5Update(&Context, R, LEN_AUTH); MD5Final(b, &Context); Ppos = 0; while (mlen) { mlen -= 16; for (i = 0; i < 16; i++) demangled[Ppos++] = C[i] ^ b[i]; if (mlen) { MD5Init(&Context); MD5Update(&Context, S, strlen(S)); MD5Update(&Context, C, 16); MD5Final(b, &Context); } C += 16; } return 0; } int rad_demangle_mppe_key(struct rad_handle *h, const void *mangled, size_t mlen, u_char *demangled, size_t *len) { char R[LEN_AUTH]; /* variable names as per rfc2548 */ const char *S; u_char b[16]; const u_char *A, *C; MD5_CTX Context; int Slen, i, Clen, Ppos; u_char *P; if (mlen % 16 != SALT_LEN) { generr(h, "Cannot interpret mangled data of length %ld", (u_long)mlen); return -1; } /* We need the RADIUS Request-Authenticator */ if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) { generr(h, "Cannot obtain the RADIUS request authenticator"); return -1; } A = (const u_char *)mangled; /* Salt comes first */ C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */ Clen = mlen - SALT_LEN; S = rad_server_secret(h); /* We need the RADIUS secret */ Slen = strlen(S); P = alloca(Clen); /* We derive our plaintext */ MD5Init(&Context); MD5Update(&Context, S, Slen); MD5Update(&Context, R, LEN_AUTH); MD5Update(&Context, A, SALT_LEN); MD5Final(b, &Context); Ppos = 0; while (Clen) { Clen -= 16; for (i = 0; i < 16; i++) P[Ppos++] = C[i] ^ b[i]; if (Clen) { MD5Init(&Context); MD5Update(&Context, S, Slen); MD5Update(&Context, C, 16); MD5Final(b, &Context); } C += 16; } /* * The resulting plain text consists of a one-byte length, the text and * maybe some padding. */ *len = *P; if (*len > mlen - 1) { generr(h, "Mangled data seems to be garbage %d %d", *len, mlen-1); return -1; } if (*len > MPPE_KEY_LEN) { generr(h, "Key to long (%d) for me max. %d", *len, MPPE_KEY_LEN); return -1; } memcpy(demangled, P + 1, *len); return 0; } /* vim: set ts=8 sw=8 noet: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5658_1
crossvul-cpp_data_good_2131_3
/* * HID driver for some monterey "special" devices * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2007 Jiri Kosina * Copyright (c) 2008 Jiri Slaby */ /* * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "hid-ids.h" static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 31 && rdesc[29] == 0x05 && rdesc[30] == 0x09) { hid_info(hdev, "fixing up button/consumer in HID report descriptor\n"); rdesc[30] = 0x0c; } return rdesc; } #define mr_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \ EV_KEY, (c)) static int mr_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER) return 0; switch (usage->hid & HID_USAGE) { case 0x156: mr_map_key_clear(KEY_WORDPROCESSOR); break; case 0x157: mr_map_key_clear(KEY_SPREADSHEET); break; case 0x158: mr_map_key_clear(KEY_PRESENTATION); break; case 0x15c: mr_map_key_clear(KEY_STOP); break; default: return 0; } return 1; } static const struct hid_device_id mr_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_MONTEREY, USB_DEVICE_ID_GENIUS_KB29E) }, { } }; MODULE_DEVICE_TABLE(hid, mr_devices); static struct hid_driver mr_driver = { .name = "monterey", .id_table = mr_devices, .report_fixup = mr_report_fixup, .input_mapping = mr_input_mapping, }; module_hid_driver(mr_driver); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/good_2131_3
crossvul-cpp_data_good_936_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* 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 PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; 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; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,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; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,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; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",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 ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ 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; 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+=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; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; 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); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_936_0
crossvul-cpp_data_good_404_1
/* vsprintf with automatic memory allocation. Copyright (C) 1999, 2002-2018 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <https://www.gnu.org/licenses/>. */ /* This file can be parametrized with the following macros: VASNPRINTF The name of the function being defined. FCHAR_T The element type of the format string. DCHAR_T The element type of the destination (result) string. FCHAR_T_ONLY_ASCII Set to 1 to enable verification that all characters in the format string are ASCII. MUST be set if FCHAR_T and DCHAR_T are not the same type. DIRECTIVE Structure denoting a format directive. Depends on FCHAR_T. DIRECTIVES Structure denoting the set of format directives of a format string. Depends on FCHAR_T. PRINTF_PARSE Function that parses a format string. Depends on FCHAR_T. DCHAR_CPY memcpy like function for DCHAR_T[] arrays. DCHAR_SET memset like function for DCHAR_T[] arrays. DCHAR_MBSNLEN mbsnlen like function for DCHAR_T[] arrays. SNPRINTF The system's snprintf (or similar) function. This may be either snprintf or swprintf. TCHAR_T The element type of the argument and result string of the said SNPRINTF function. This may be either char or wchar_t. The code exploits that sizeof (TCHAR_T) | sizeof (DCHAR_T) and alignof (TCHAR_T) <= alignof (DCHAR_T). DCHAR_IS_TCHAR Set to 1 if DCHAR_T and TCHAR_T are the same type. DCHAR_CONV_FROM_ENCODING A function to convert from char[] to DCHAR[]. DCHAR_IS_UINT8_T Set to 1 if DCHAR_T is uint8_t. DCHAR_IS_UINT16_T Set to 1 if DCHAR_T is uint16_t. DCHAR_IS_UINT32_T Set to 1 if DCHAR_T is uint32_t. */ /* Tell glibc's <stdio.h> to provide a prototype for snprintf(). This must come before <config.h> because <config.h> may include <features.h>, and once <features.h> has been included, it's too late. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif #ifndef VASNPRINTF # include <config.h> #endif #ifndef IN_LIBINTL # include <alloca.h> #endif /* Specification. */ #ifndef VASNPRINTF # if WIDE_CHAR_VERSION # include "vasnwprintf.h" # else # include "vasnprintf.h" # endif #endif #include <locale.h> /* localeconv() */ #include <stdio.h> /* snprintf(), sprintf() */ #include <stdlib.h> /* abort(), malloc(), realloc(), free() */ #include <string.h> /* memcpy(), strlen() */ #include <errno.h> /* errno */ #include <limits.h> /* CHAR_BIT */ #include <float.h> /* DBL_MAX_EXP, LDBL_MAX_EXP */ #if HAVE_NL_LANGINFO # include <langinfo.h> #endif #ifndef VASNPRINTF # if WIDE_CHAR_VERSION # include "wprintf-parse.h" # else # include "printf-parse.h" # endif #endif /* Checked size_t computations. */ #include "xsize.h" #include "verify.h" #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL # include <math.h> # include "float+.h" #endif #if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL # include <math.h> # include "isnand-nolibm.h" #endif #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) && !defined IN_LIBINTL # include <math.h> # include "isnanl-nolibm.h" # include "fpucw.h" #endif #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL # include <math.h> # include "isnand-nolibm.h" # include "printf-frexp.h" #endif #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL # include <math.h> # include "isnanl-nolibm.h" # include "printf-frexpl.h" # include "fpucw.h" #endif #ifndef FALLTHROUGH # if __GNUC__ < 7 # define FALLTHROUGH ((void) 0) # else # define FALLTHROUGH __attribute__ ((__fallthrough__)) # endif #endif /* Default parameters. */ #ifndef VASNPRINTF # if WIDE_CHAR_VERSION # define VASNPRINTF vasnwprintf # define FCHAR_T wchar_t # define DCHAR_T wchar_t # define TCHAR_T wchar_t # define DCHAR_IS_TCHAR 1 # define DIRECTIVE wchar_t_directive # define DIRECTIVES wchar_t_directives # define PRINTF_PARSE wprintf_parse # define DCHAR_CPY wmemcpy # define DCHAR_SET wmemset # else # define VASNPRINTF vasnprintf # define FCHAR_T char # define DCHAR_T char # define TCHAR_T char # define DCHAR_IS_TCHAR 1 # define DIRECTIVE char_directive # define DIRECTIVES char_directives # define PRINTF_PARSE printf_parse # define DCHAR_CPY memcpy # define DCHAR_SET memset # endif #endif #if WIDE_CHAR_VERSION /* TCHAR_T is wchar_t. */ # define USE_SNPRINTF 1 # if HAVE_DECL__SNWPRINTF /* On Windows, the function swprintf() has a different signature than on Unix; we use the function _snwprintf() or - on mingw - snwprintf() instead. The mingw function snwprintf() has fewer bugs than the MSVCRT function _snwprintf(), so prefer that. */ # if defined __MINGW32__ # define SNPRINTF snwprintf # else # define SNPRINTF _snwprintf # define USE_MSVC__SNPRINTF 1 # endif # else /* Unix. */ # define SNPRINTF swprintf # endif #else /* TCHAR_T is char. */ /* Use snprintf if it exists under the name 'snprintf' or '_snprintf'. But don't use it on BeOS, since BeOS snprintf produces no output if the size argument is >= 0x3000000. Also don't use it on Linux libc5, since there snprintf with size = 1 writes any output without bounds, like sprintf. */ # if (HAVE_DECL__SNPRINTF || HAVE_SNPRINTF) && !defined __BEOS__ && !(__GNU_LIBRARY__ == 1) # define USE_SNPRINTF 1 # else # define USE_SNPRINTF 0 # endif # if HAVE_DECL__SNPRINTF /* Windows. The mingw function snprintf() has fewer bugs than the MSVCRT function _snprintf(), so prefer that. */ # if defined __MINGW32__ # define SNPRINTF snprintf /* Here we need to call the native snprintf, not rpl_snprintf. */ # undef snprintf # else /* MSVC versions < 14 did not have snprintf, only _snprintf. */ # define SNPRINTF _snprintf # define USE_MSVC__SNPRINTF 1 # endif # else /* Unix. */ # define SNPRINTF snprintf /* Here we need to call the native snprintf, not rpl_snprintf. */ # undef snprintf # endif #endif /* Here we need to call the native sprintf, not rpl_sprintf. */ #undef sprintf /* GCC >= 4.0 with -Wall emits unjustified "... may be used uninitialized" warnings in this file. Use -Dlint to suppress them. */ #if defined GCC_LINT || defined lint # define IF_LINT(Code) Code #else # define IF_LINT(Code) /* empty */ #endif /* Avoid some warnings from "gcc -Wshadow". This file doesn't use the exp() and remainder() functions. */ #undef exp #define exp expo #undef remainder #define remainder rem #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && !WIDE_CHAR_VERSION # if (HAVE_STRNLEN && !defined _AIX) # define local_strnlen strnlen # else # ifndef local_strnlen_defined # define local_strnlen_defined 1 static size_t local_strnlen (const char *string, size_t maxlen) { const char *end = memchr (string, '\0', maxlen); return end ? (size_t) (end - string) : maxlen; } # endif # endif #endif #if (((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && WIDE_CHAR_VERSION) || ((!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && !WIDE_CHAR_VERSION && DCHAR_IS_TCHAR)) && HAVE_WCHAR_T # if HAVE_WCSLEN # define local_wcslen wcslen # else /* Solaris 2.5.1 has wcslen() in a separate library libw.so. To avoid a dependency towards this library, here is a local substitute. Define this substitute only once, even if this file is included twice in the same compilation unit. */ # ifndef local_wcslen_defined # define local_wcslen_defined 1 static size_t local_wcslen (const wchar_t *s) { const wchar_t *ptr; for (ptr = s; *ptr != (wchar_t) 0; ptr++) ; return ptr - s; } # endif # endif #endif #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF) && HAVE_WCHAR_T && WIDE_CHAR_VERSION # if HAVE_WCSNLEN # define local_wcsnlen wcsnlen # else # ifndef local_wcsnlen_defined # define local_wcsnlen_defined 1 static size_t local_wcsnlen (const wchar_t *s, size_t maxlen) { const wchar_t *ptr; for (ptr = s; maxlen > 0 && *ptr != (wchar_t) 0; ptr++, maxlen--) ; return ptr - s; } # endif # endif #endif #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && !defined IN_LIBINTL /* Determine the decimal-point character according to the current locale. */ # ifndef decimal_point_char_defined # define decimal_point_char_defined 1 static char decimal_point_char (void) { const char *point; /* Determine it in a multithread-safe way. We know nl_langinfo is multithread-safe on glibc systems and Mac OS X systems, but is not required to be multithread-safe by POSIX. sprintf(), however, is multithread-safe. localeconv() is rarely multithread-safe. */ # if HAVE_NL_LANGINFO && (__GLIBC__ || defined __UCLIBC__ || (defined __APPLE__ && defined __MACH__)) point = nl_langinfo (RADIXCHAR); # elif 1 char pointbuf[5]; sprintf (pointbuf, "%#.0f", 1.0); point = &pointbuf[1]; # else point = localeconv () -> decimal_point; # endif /* The decimal point is always a single byte: either '.' or ','. */ return (point[0] != '\0' ? point[0] : '.'); } # endif #endif #if NEED_PRINTF_INFINITE_DOUBLE && !NEED_PRINTF_DOUBLE && !defined IN_LIBINTL /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */ static int is_infinite_or_zero (double x) { return isnand (x) || x + x == x; } #endif #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL /* Equivalent to !isfinite(x) || x == 0, but does not require libm. */ static int is_infinite_or_zerol (long double x) { return isnanl (x) || x + x == x; } #endif #if (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL /* Converting 'long double' to decimal without rare rounding bugs requires real bignums. We use the naming conventions of GNU gmp, but vastly simpler (and slower) algorithms. */ typedef unsigned int mp_limb_t; # define GMP_LIMB_BITS 32 verify (sizeof (mp_limb_t) * CHAR_BIT == GMP_LIMB_BITS); typedef unsigned long long mp_twolimb_t; # define GMP_TWOLIMB_BITS 64 verify (sizeof (mp_twolimb_t) * CHAR_BIT == GMP_TWOLIMB_BITS); /* Representation of a bignum >= 0. */ typedef struct { size_t nlimbs; mp_limb_t *limbs; /* Bits in little-endian order, allocated with malloc(). */ } mpn_t; /* Compute the product of two bignums >= 0. Return the allocated memory in case of success, NULL in case of memory allocation failure. */ static void * multiply (mpn_t src1, mpn_t src2, mpn_t *dest) { const mp_limb_t *p1; const mp_limb_t *p2; size_t len1; size_t len2; if (src1.nlimbs <= src2.nlimbs) { len1 = src1.nlimbs; p1 = src1.limbs; len2 = src2.nlimbs; p2 = src2.limbs; } else { len1 = src2.nlimbs; p1 = src2.limbs; len2 = src1.nlimbs; p2 = src1.limbs; } /* Now 0 <= len1 <= len2. */ if (len1 == 0) { /* src1 or src2 is zero. */ dest->nlimbs = 0; dest->limbs = (mp_limb_t *) malloc (1); } else { /* Here 1 <= len1 <= len2. */ size_t dlen; mp_limb_t *dp; size_t k, i, j; dlen = len1 + len2; dp = (mp_limb_t *) malloc (dlen * sizeof (mp_limb_t)); if (dp == NULL) return NULL; for (k = len2; k > 0; ) dp[--k] = 0; for (i = 0; i < len1; i++) { mp_limb_t digit1 = p1[i]; mp_twolimb_t carry = 0; for (j = 0; j < len2; j++) { mp_limb_t digit2 = p2[j]; carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2; carry += dp[i + j]; dp[i + j] = (mp_limb_t) carry; carry = carry >> GMP_LIMB_BITS; } dp[i + len2] = (mp_limb_t) carry; } /* Normalise. */ while (dlen > 0 && dp[dlen - 1] == 0) dlen--; dest->nlimbs = dlen; dest->limbs = dp; } return dest->limbs; } /* Compute the quotient of a bignum a >= 0 and a bignum b > 0. a is written as a = q * b + r with 0 <= r < b. q is the quotient, r the remainder. Finally, round-to-even is performed: If r > b/2 or if r = b/2 and q is odd, q is incremented. Return the allocated memory in case of success, NULL in case of memory allocation failure. */ static void * divide (mpn_t a, mpn_t b, mpn_t *q) { /* Algorithm: First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]] with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS). If m<n, then q:=0 and r:=a. If m>=n=1, perform a single-precision division: r:=0, j:=m, while j>0 do {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j = = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r<b[0]<beta} j:=j-1, r:=r*beta+a[j], q[j]:=floor(r/b[0]), r:=r-b[0]*q[j]. Normalise [q[m-1],...,q[0]], yields q. If m>=n>1, perform a multiple-precision division: We have a/b < beta^(m-n+1). s:=intDsize-1-(highest bit in b[n-1]), 0<=s<intDsize. Shift a and b left by s bits, copying them. r:=a. r=[r[m],...,r[0]], b=[b[n-1],...,b[0]] with b[n-1]>=beta/2. For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).} Compute q* : q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]). In case of overflow (q* >= beta) set q* := beta-1. Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2] and c3 := b[n-2] * q*. {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow occurred. Furthermore 0 <= c3 < beta^2. If there was overflow and r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2, the next test can be skipped.} While c3 > c2, {Here 0 <= c2 < c3 < beta^2} Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2]. If q* > 0: Put r := r - b * q* * beta^j. In detail: [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]]. hence: u:=0, for i:=0 to n-1 do u := u + q* * b[i], r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry), u:=u div beta (+ 1, if carry in subtraction) r[n+j]:=r[n+j]-u. {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1 < q* + 1 <= beta, the carry u does not overflow.} If a negative carry occurs, put q* := q* - 1 and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]]. Set q[j] := q*. Normalise [q[m-n],..,q[0]]; this yields the quotient q. Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the rest r. The room for q[j] can be allocated at the memory location of r[n+j]. Finally, round-to-even: Shift r left by 1 bit. If r > b or if r = b and q[0] is odd, q := q+1. */ const mp_limb_t *a_ptr = a.limbs; size_t a_len = a.nlimbs; const mp_limb_t *b_ptr = b.limbs; size_t b_len = b.nlimbs; mp_limb_t *roomptr; mp_limb_t *tmp_roomptr = NULL; mp_limb_t *q_ptr; size_t q_len; mp_limb_t *r_ptr; size_t r_len; /* Allocate room for a_len+2 digits. (Need a_len+1 digits for the real division and 1 more digit for the final rounding of q.) */ roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t)); if (roomptr == NULL) return NULL; /* Normalise a. */ while (a_len > 0 && a_ptr[a_len - 1] == 0) a_len--; /* Normalise b. */ for (;;) { if (b_len == 0) /* Division by zero. */ abort (); if (b_ptr[b_len - 1] == 0) b_len--; else break; } /* Here m = a_len >= 0 and n = b_len > 0. */ if (a_len < b_len) { /* m<n: trivial case. q=0, r := copy of a. */ r_ptr = roomptr; r_len = a_len; memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t)); q_ptr = roomptr + a_len; q_len = 0; } else if (b_len == 1) { /* n=1: single precision division. beta^(m-1) <= a < beta^m ==> beta^(m-2) <= a/b < beta^m */ r_ptr = roomptr; q_ptr = roomptr + 1; { mp_limb_t den = b_ptr[0]; mp_limb_t remainder = 0; const mp_limb_t *sourceptr = a_ptr + a_len; mp_limb_t *destptr = q_ptr + a_len; size_t count; for (count = a_len; count > 0; count--) { mp_twolimb_t num = ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr; *--destptr = num / den; remainder = num % den; } /* Normalise and store r. */ if (remainder > 0) { r_ptr[0] = remainder; r_len = 1; } else r_len = 0; /* Normalise q. */ q_len = a_len; if (q_ptr[q_len - 1] == 0) q_len--; } } else { /* n>1: multiple precision division. beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==> beta^(m-n-1) <= a/b < beta^(m-n+1). */ /* Determine s. */ size_t s; { mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */ /* Determine s = GMP_LIMB_BITS - integer_length (msd). Code copied from gnulib's integer_length.c. */ # if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) s = __builtin_clz (msd); # else # if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT if (GMP_LIMB_BITS <= DBL_MANT_BIT) { /* Use 'double' operations. Assumes an IEEE 754 'double' implementation. */ # define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7) # define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1) # define NWORDS \ ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int)) union { double value; unsigned int word[NWORDS]; } m; /* Use a single integer to floating-point conversion. */ m.value = msd; s = GMP_LIMB_BITS - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK) - DBL_EXP_BIAS); } else # undef NWORDS # endif { s = 31; if (msd >= 0x10000) { msd = msd >> 16; s -= 16; } if (msd >= 0x100) { msd = msd >> 8; s -= 8; } if (msd >= 0x10) { msd = msd >> 4; s -= 4; } if (msd >= 0x4) { msd = msd >> 2; s -= 2; } if (msd >= 0x2) { msd = msd >> 1; s -= 1; } } # endif } /* 0 <= s < GMP_LIMB_BITS. Copy b, shifting it left by s bits. */ if (s > 0) { tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t)); if (tmp_roomptr == NULL) { free (roomptr); return NULL; } { const mp_limb_t *sourceptr = b_ptr; mp_limb_t *destptr = tmp_roomptr; mp_twolimb_t accu = 0; size_t count; for (count = b_len; count > 0; count--) { accu += (mp_twolimb_t) *sourceptr++ << s; *destptr++ = (mp_limb_t) accu; accu = accu >> GMP_LIMB_BITS; } /* accu must be zero, since that was how s was determined. */ if (accu != 0) abort (); } b_ptr = tmp_roomptr; } /* Copy a, shifting it left by s bits, yields r. Memory layout: At the beginning: r = roomptr[0..a_len], at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */ r_ptr = roomptr; if (s == 0) { memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t)); r_ptr[a_len] = 0; } else { const mp_limb_t *sourceptr = a_ptr; mp_limb_t *destptr = r_ptr; mp_twolimb_t accu = 0; size_t count; for (count = a_len; count > 0; count--) { accu += (mp_twolimb_t) *sourceptr++ << s; *destptr++ = (mp_limb_t) accu; accu = accu >> GMP_LIMB_BITS; } *destptr++ = (mp_limb_t) accu; } q_ptr = roomptr + b_len; q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */ { size_t j = a_len - b_len; /* m-n */ mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */ mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */ mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */ ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd; /* Division loop, traversed m-n+1 times. j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */ for (;;) { mp_limb_t q_star; mp_limb_t c1; if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */ { /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */ mp_twolimb_t num = ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS) | r_ptr[j + b_len - 1]; q_star = num / b_msd; c1 = num % b_msd; } else { /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */ q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */ /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) {<= beta !}. If yes, jump directly to the subtraction loop. (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */ if (r_ptr[j + b_len] > b_msd || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd) /* r[j+n] >= b[n-1]+1 or r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a carry. */ goto subtract; } /* q_star = q*, c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, <beta). */ { mp_twolimb_t c2 = /* c1*beta+r[j+n-2] */ ((mp_twolimb_t) c1 << GMP_LIMB_BITS) | r_ptr[j + b_len - 2]; mp_twolimb_t c3 = /* b[n-2] * q* */ (mp_twolimb_t) b_2msd * (mp_twolimb_t) q_star; /* While c2 < c3, increase c2 and decrease c3. Consider c3-c2. While it is > 0, decrease it by b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2 this can happen only twice. */ if (c3 > c2) { q_star = q_star - 1; /* q* := q* - 1 */ if (c3 - c2 > b_msdd) q_star = q_star - 1; /* q* := q* - 1 */ } } if (q_star > 0) subtract: { /* Subtract r := r - b * q* * beta^j. */ mp_limb_t cr; { const mp_limb_t *sourceptr = b_ptr; mp_limb_t *destptr = r_ptr + j; mp_twolimb_t carry = 0; size_t count; for (count = b_len; count > 0; count--) { /* Here 0 <= carry <= q*. */ carry = carry + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++ + (mp_limb_t) ~(*destptr); /* Here 0 <= carry <= beta*q* + beta-1. */ *destptr++ = ~(mp_limb_t) carry; carry = carry >> GMP_LIMB_BITS; /* <= q* */ } cr = (mp_limb_t) carry; } /* Subtract cr from r_ptr[j + b_len], then forget about r_ptr[j + b_len]. */ if (cr > r_ptr[j + b_len]) { /* Subtraction gave a carry. */ q_star = q_star - 1; /* q* := q* - 1 */ /* Add b back. */ { const mp_limb_t *sourceptr = b_ptr; mp_limb_t *destptr = r_ptr + j; mp_limb_t carry = 0; size_t count; for (count = b_len; count > 0; count--) { mp_limb_t source1 = *sourceptr++; mp_limb_t source2 = *destptr; *destptr++ = source1 + source2 + carry; carry = (carry ? source1 >= (mp_limb_t) ~source2 : source1 > (mp_limb_t) ~source2); } } /* Forget about the carry and about r[j+n]. */ } } /* q* is determined. Store it as q[j]. */ q_ptr[j] = q_star; if (j == 0) break; j--; } } r_len = b_len; /* Normalise q. */ if (q_ptr[q_len - 1] == 0) q_len--; # if 0 /* Not needed here, since we need r only to compare it with b/2, and b is shifted left by s bits. */ /* Shift r right by s bits. */ if (s > 0) { mp_limb_t ptr = r_ptr + r_len; mp_twolimb_t accu = 0; size_t count; for (count = r_len; count > 0; count--) { accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS; accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s); *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS); } } # endif /* Normalise r. */ while (r_len > 0 && r_ptr[r_len - 1] == 0) r_len--; } /* Compare r << 1 with b. */ if (r_len > b_len) goto increment_q; { size_t i; for (i = b_len;;) { mp_limb_t r_i = (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0) | (i < r_len ? r_ptr[i] << 1 : 0); mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0); if (r_i > b_i) goto increment_q; if (r_i < b_i) goto keep_q; if (i == 0) break; i--; } } if (q_len > 0 && ((q_ptr[0] & 1) != 0)) /* q is odd. */ increment_q: { size_t i; for (i = 0; i < q_len; i++) if (++(q_ptr[i]) != 0) goto keep_q; q_ptr[q_len++] = 1; } keep_q: if (tmp_roomptr != NULL) free (tmp_roomptr); q->limbs = q_ptr; q->nlimbs = q_len; return roomptr; } /* Convert a bignum a >= 0, multiplied with 10^extra_zeroes, to decimal representation. Destroys the contents of a. Return the allocated memory - containing the decimal digits in low-to-high order, terminated with a NUL character - in case of success, NULL in case of memory allocation failure. */ static char * convert_to_decimal (mpn_t a, size_t extra_zeroes) { mp_limb_t *a_ptr = a.limbs; size_t a_len = a.nlimbs; /* 0.03345 is slightly larger than log(2)/(9*log(10)). */ size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1); /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the digits of a, followed by 1 byte for the terminating NUL. */ char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1)); if (c_ptr != NULL) { char *d_ptr = c_ptr; for (; extra_zeroes > 0; extra_zeroes--) *d_ptr++ = '0'; while (a_len > 0) { /* Divide a by 10^9, in-place. */ mp_limb_t remainder = 0; mp_limb_t *ptr = a_ptr + a_len; size_t count; for (count = a_len; count > 0; count--) { mp_twolimb_t num = ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr; *ptr = num / 1000000000; remainder = num % 1000000000; } /* Store the remainder as 9 decimal digits. */ for (count = 9; count > 0; count--) { *d_ptr++ = '0' + (remainder % 10); remainder = remainder / 10; } /* Normalize a. */ if (a_ptr[a_len - 1] == 0) a_len--; } /* Remove leading zeroes. */ while (d_ptr > c_ptr && d_ptr[-1] == '0') d_ptr--; /* But keep at least one zero. */ if (d_ptr == c_ptr) *d_ptr++ = '0'; /* Terminate the string. */ *d_ptr = '\0'; } return c_ptr; } # if NEED_PRINTF_LONG_DOUBLE /* Assuming x is finite and >= 0: write x as x = 2^e * m, where m is a bignum. Return the allocated memory in case of success, NULL in case of memory allocation failure. */ static void * decode_long_double (long double x, int *ep, mpn_t *mp) { mpn_t m; int exp; long double y; size_t i; /* Allocate memory for result. */ m.nlimbs = (LDBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS; m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t)); if (m.limbs == NULL) return NULL; /* Split into exponential part and mantissa. */ y = frexpl (x, &exp); if (!(y >= 0.0L && y < 1.0L)) abort (); /* x = 2^exp * y = 2^(exp - LDBL_MANT_BIT) * (y * 2^LDBL_MANT_BIT), and the latter is an integer. */ /* Convert the mantissa (y * 2^LDBL_MANT_BIT) to a sequence of limbs. I'm not sure whether it's safe to cast a 'long double' value between 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only 'long double' values between 0 and 2^16 (to 'unsigned int' or 'int', doesn't matter). */ # if (LDBL_MANT_BIT % GMP_LIMB_BITS) != 0 # if (LDBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2 { mp_limb_t hi, lo; y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % (GMP_LIMB_BITS / 2)); hi = (int) y; y -= hi; if (!(y >= 0.0L && y < 1.0L)) abort (); y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2); lo = (int) y; y -= lo; if (!(y >= 0.0L && y < 1.0L)) abort (); m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo; } # else { mp_limb_t d; y *= (mp_limb_t) 1 << (LDBL_MANT_BIT % GMP_LIMB_BITS); d = (int) y; y -= d; if (!(y >= 0.0L && y < 1.0L)) abort (); m.limbs[LDBL_MANT_BIT / GMP_LIMB_BITS] = d; } # endif # endif for (i = LDBL_MANT_BIT / GMP_LIMB_BITS; i > 0; ) { mp_limb_t hi, lo; y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2); hi = (int) y; y -= hi; if (!(y >= 0.0L && y < 1.0L)) abort (); y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2); lo = (int) y; y -= lo; if (!(y >= 0.0L && y < 1.0L)) abort (); m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo; } # if 0 /* On FreeBSD 6.1/x86, 'long double' numbers sometimes have excess precision. */ if (!(y == 0.0L)) abort (); # endif /* Normalise. */ while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0) m.nlimbs--; *mp = m; *ep = exp - LDBL_MANT_BIT; return m.limbs; } # endif # if NEED_PRINTF_DOUBLE /* Assuming x is finite and >= 0: write x as x = 2^e * m, where m is a bignum. Return the allocated memory in case of success, NULL in case of memory allocation failure. */ static void * decode_double (double x, int *ep, mpn_t *mp) { mpn_t m; int exp; double y; size_t i; /* Allocate memory for result. */ m.nlimbs = (DBL_MANT_BIT + GMP_LIMB_BITS - 1) / GMP_LIMB_BITS; m.limbs = (mp_limb_t *) malloc (m.nlimbs * sizeof (mp_limb_t)); if (m.limbs == NULL) return NULL; /* Split into exponential part and mantissa. */ y = frexp (x, &exp); if (!(y >= 0.0 && y < 1.0)) abort (); /* x = 2^exp * y = 2^(exp - DBL_MANT_BIT) * (y * 2^DBL_MANT_BIT), and the latter is an integer. */ /* Convert the mantissa (y * 2^DBL_MANT_BIT) to a sequence of limbs. I'm not sure whether it's safe to cast a 'double' value between 2^31 and 2^32 to 'unsigned int', therefore play safe and cast only 'double' values between 0 and 2^16 (to 'unsigned int' or 'int', doesn't matter). */ # if (DBL_MANT_BIT % GMP_LIMB_BITS) != 0 # if (DBL_MANT_BIT % GMP_LIMB_BITS) > GMP_LIMB_BITS / 2 { mp_limb_t hi, lo; y *= (mp_limb_t) 1 << (DBL_MANT_BIT % (GMP_LIMB_BITS / 2)); hi = (int) y; y -= hi; if (!(y >= 0.0 && y < 1.0)) abort (); y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2); lo = (int) y; y -= lo; if (!(y >= 0.0 && y < 1.0)) abort (); m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = (hi << (GMP_LIMB_BITS / 2)) | lo; } # else { mp_limb_t d; y *= (mp_limb_t) 1 << (DBL_MANT_BIT % GMP_LIMB_BITS); d = (int) y; y -= d; if (!(y >= 0.0 && y < 1.0)) abort (); m.limbs[DBL_MANT_BIT / GMP_LIMB_BITS] = d; } # endif # endif for (i = DBL_MANT_BIT / GMP_LIMB_BITS; i > 0; ) { mp_limb_t hi, lo; y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2); hi = (int) y; y -= hi; if (!(y >= 0.0 && y < 1.0)) abort (); y *= (mp_limb_t) 1 << (GMP_LIMB_BITS / 2); lo = (int) y; y -= lo; if (!(y >= 0.0 && y < 1.0)) abort (); m.limbs[--i] = (hi << (GMP_LIMB_BITS / 2)) | lo; } if (!(y == 0.0)) abort (); /* Normalise. */ while (m.nlimbs > 0 && m.limbs[m.nlimbs - 1] == 0) m.nlimbs--; *mp = m; *ep = exp - DBL_MANT_BIT; return m.limbs; } # endif /* Assuming x = 2^e * m is finite and >= 0, and n is an integer: Returns the decimal representation of round (x * 10^n). Return the allocated memory - containing the decimal digits in low-to-high order, terminated with a NUL character - in case of success, NULL in case of memory allocation failure. */ static char * scale10_round_decimal_decoded (int e, mpn_t m, void *memory, int n) { int s; size_t extra_zeroes; unsigned int abs_n; unsigned int abs_s; mp_limb_t *pow5_ptr; size_t pow5_len; unsigned int s_limbs; unsigned int s_bits; mpn_t pow5; mpn_t z; void *z_memory; char *digits; if (memory == NULL) return NULL; /* x = 2^e * m, hence y = round (2^e * 10^n * m) = round (2^(e+n) * 5^n * m) = round (2^s * 5^n * m). */ s = e + n; extra_zeroes = 0; /* Factor out a common power of 10 if possible. */ if (s > 0 && n > 0) { extra_zeroes = (s < n ? s : n); s -= extra_zeroes; n -= extra_zeroes; } /* Here y = round (2^s * 5^n * m) * 10^extra_zeroes. Before converting to decimal, we need to compute z = round (2^s * 5^n * m). */ /* Compute 5^|n|, possibly shifted by |s| bits if n and s have the same sign. 2.322 is slightly larger than log(5)/log(2). */ abs_n = (n >= 0 ? n : -n); abs_s = (s >= 0 ? s : -s); pow5_ptr = (mp_limb_t *) malloc (((int)(abs_n * (2.322f / GMP_LIMB_BITS)) + 1 + abs_s / GMP_LIMB_BITS + 1) * sizeof (mp_limb_t)); if (pow5_ptr == NULL) { free (memory); return NULL; } /* Initialize with 1. */ pow5_ptr[0] = 1; pow5_len = 1; /* Multiply with 5^|n|. */ if (abs_n > 0) { static mp_limb_t const small_pow5[13 + 1] = { 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625, 1220703125 }; unsigned int n13; for (n13 = 0; n13 <= abs_n; n13 += 13) { mp_limb_t digit1 = small_pow5[n13 + 13 <= abs_n ? 13 : abs_n - n13]; size_t j; mp_twolimb_t carry = 0; for (j = 0; j < pow5_len; j++) { mp_limb_t digit2 = pow5_ptr[j]; carry += (mp_twolimb_t) digit1 * (mp_twolimb_t) digit2; pow5_ptr[j] = (mp_limb_t) carry; carry = carry >> GMP_LIMB_BITS; } if (carry > 0) pow5_ptr[pow5_len++] = (mp_limb_t) carry; } } s_limbs = abs_s / GMP_LIMB_BITS; s_bits = abs_s % GMP_LIMB_BITS; if (n >= 0 ? s >= 0 : s <= 0) { /* Multiply with 2^|s|. */ if (s_bits > 0) { mp_limb_t *ptr = pow5_ptr; mp_twolimb_t accu = 0; size_t count; for (count = pow5_len; count > 0; count--) { accu += (mp_twolimb_t) *ptr << s_bits; *ptr++ = (mp_limb_t) accu; accu = accu >> GMP_LIMB_BITS; } if (accu > 0) { *ptr = (mp_limb_t) accu; pow5_len++; } } if (s_limbs > 0) { size_t count; for (count = pow5_len; count > 0;) { count--; pow5_ptr[s_limbs + count] = pow5_ptr[count]; } for (count = s_limbs; count > 0;) { count--; pow5_ptr[count] = 0; } pow5_len += s_limbs; } pow5.limbs = pow5_ptr; pow5.nlimbs = pow5_len; if (n >= 0) { /* Multiply m with pow5. No division needed. */ z_memory = multiply (m, pow5, &z); } else { /* Divide m by pow5 and round. */ z_memory = divide (m, pow5, &z); } } else { pow5.limbs = pow5_ptr; pow5.nlimbs = pow5_len; if (n >= 0) { /* n >= 0, s < 0. Multiply m with pow5, then divide by 2^|s|. */ mpn_t numerator; mpn_t denominator; void *tmp_memory; tmp_memory = multiply (m, pow5, &numerator); if (tmp_memory == NULL) { free (pow5_ptr); free (memory); return NULL; } /* Construct 2^|s|. */ { mp_limb_t *ptr = pow5_ptr + pow5_len; size_t i; for (i = 0; i < s_limbs; i++) ptr[i] = 0; ptr[s_limbs] = (mp_limb_t) 1 << s_bits; denominator.limbs = ptr; denominator.nlimbs = s_limbs + 1; } z_memory = divide (numerator, denominator, &z); free (tmp_memory); } else { /* n < 0, s > 0. Multiply m with 2^s, then divide by pow5. */ mpn_t numerator; mp_limb_t *num_ptr; num_ptr = (mp_limb_t *) malloc ((m.nlimbs + s_limbs + 1) * sizeof (mp_limb_t)); if (num_ptr == NULL) { free (pow5_ptr); free (memory); return NULL; } { mp_limb_t *destptr = num_ptr; { size_t i; for (i = 0; i < s_limbs; i++) *destptr++ = 0; } if (s_bits > 0) { const mp_limb_t *sourceptr = m.limbs; mp_twolimb_t accu = 0; size_t count; for (count = m.nlimbs; count > 0; count--) { accu += (mp_twolimb_t) *sourceptr++ << s_bits; *destptr++ = (mp_limb_t) accu; accu = accu >> GMP_LIMB_BITS; } if (accu > 0) *destptr++ = (mp_limb_t) accu; } else { const mp_limb_t *sourceptr = m.limbs; size_t count; for (count = m.nlimbs; count > 0; count--) *destptr++ = *sourceptr++; } numerator.limbs = num_ptr; numerator.nlimbs = destptr - num_ptr; } z_memory = divide (numerator, pow5, &z); free (num_ptr); } } free (pow5_ptr); free (memory); /* Here y = round (x * 10^n) = z * 10^extra_zeroes. */ if (z_memory == NULL) return NULL; digits = convert_to_decimal (z, extra_zeroes); free (z_memory); return digits; } # if NEED_PRINTF_LONG_DOUBLE /* Assuming x is finite and >= 0, and n is an integer: Returns the decimal representation of round (x * 10^n). Return the allocated memory - containing the decimal digits in low-to-high order, terminated with a NUL character - in case of success, NULL in case of memory allocation failure. */ static char * scale10_round_decimal_long_double (long double x, int n) { int e IF_LINT(= 0); mpn_t m; void *memory = decode_long_double (x, &e, &m); return scale10_round_decimal_decoded (e, m, memory, n); } # endif # if NEED_PRINTF_DOUBLE /* Assuming x is finite and >= 0, and n is an integer: Returns the decimal representation of round (x * 10^n). Return the allocated memory - containing the decimal digits in low-to-high order, terminated with a NUL character - in case of success, NULL in case of memory allocation failure. */ static char * scale10_round_decimal_double (double x, int n) { int e IF_LINT(= 0); mpn_t m; void *memory = decode_double (x, &e, &m); return scale10_round_decimal_decoded (e, m, memory, n); } # endif # if NEED_PRINTF_LONG_DOUBLE /* Assuming x is finite and > 0: Return an approximation for n with 10^n <= x < 10^(n+1). The approximation is usually the right n, but may be off by 1 sometimes. */ static int floorlog10l (long double x) { int exp; long double y; double z; double l; /* Split into exponential part and mantissa. */ y = frexpl (x, &exp); if (!(y >= 0.0L && y < 1.0L)) abort (); if (y == 0.0L) return INT_MIN; if (y < 0.5L) { while (y < (1.0L / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2)))) { y *= 1.0L * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2)); exp -= GMP_LIMB_BITS; } if (y < (1.0L / (1 << 16))) { y *= 1.0L * (1 << 16); exp -= 16; } if (y < (1.0L / (1 << 8))) { y *= 1.0L * (1 << 8); exp -= 8; } if (y < (1.0L / (1 << 4))) { y *= 1.0L * (1 << 4); exp -= 4; } if (y < (1.0L / (1 << 2))) { y *= 1.0L * (1 << 2); exp -= 2; } if (y < (1.0L / (1 << 1))) { y *= 1.0L * (1 << 1); exp -= 1; } } if (!(y >= 0.5L && y < 1.0L)) abort (); /* Compute an approximation for l = log2(x) = exp + log2(y). */ l = exp; z = y; if (z < 0.70710678118654752444) { z *= 1.4142135623730950488; l -= 0.5; } if (z < 0.8408964152537145431) { z *= 1.1892071150027210667; l -= 0.25; } if (z < 0.91700404320467123175) { z *= 1.0905077326652576592; l -= 0.125; } if (z < 0.9576032806985736469) { z *= 1.0442737824274138403; l -= 0.0625; } /* Now 0.95 <= z <= 1.01. */ z = 1 - z; /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...) Four terms are enough to get an approximation with error < 10^-7. */ l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25))); /* Finally multiply with log(2)/log(10), yields an approximation for log10(x). */ l *= 0.30102999566398119523; /* Round down to the next integer. */ return (int) l + (l < 0 ? -1 : 0); } # endif # if NEED_PRINTF_DOUBLE /* Assuming x is finite and > 0: Return an approximation for n with 10^n <= x < 10^(n+1). The approximation is usually the right n, but may be off by 1 sometimes. */ static int floorlog10 (double x) { int exp; double y; double z; double l; /* Split into exponential part and mantissa. */ y = frexp (x, &exp); if (!(y >= 0.0 && y < 1.0)) abort (); if (y == 0.0) return INT_MIN; if (y < 0.5) { while (y < (1.0 / (1 << (GMP_LIMB_BITS / 2)) / (1 << (GMP_LIMB_BITS / 2)))) { y *= 1.0 * (1 << (GMP_LIMB_BITS / 2)) * (1 << (GMP_LIMB_BITS / 2)); exp -= GMP_LIMB_BITS; } if (y < (1.0 / (1 << 16))) { y *= 1.0 * (1 << 16); exp -= 16; } if (y < (1.0 / (1 << 8))) { y *= 1.0 * (1 << 8); exp -= 8; } if (y < (1.0 / (1 << 4))) { y *= 1.0 * (1 << 4); exp -= 4; } if (y < (1.0 / (1 << 2))) { y *= 1.0 * (1 << 2); exp -= 2; } if (y < (1.0 / (1 << 1))) { y *= 1.0 * (1 << 1); exp -= 1; } } if (!(y >= 0.5 && y < 1.0)) abort (); /* Compute an approximation for l = log2(x) = exp + log2(y). */ l = exp; z = y; if (z < 0.70710678118654752444) { z *= 1.4142135623730950488; l -= 0.5; } if (z < 0.8408964152537145431) { z *= 1.1892071150027210667; l -= 0.25; } if (z < 0.91700404320467123175) { z *= 1.0905077326652576592; l -= 0.125; } if (z < 0.9576032806985736469) { z *= 1.0442737824274138403; l -= 0.0625; } /* Now 0.95 <= z <= 1.01. */ z = 1 - z; /* log2(1-z) = 1/log(2) * (- z - z^2/2 - z^3/3 - z^4/4 - ...) Four terms are enough to get an approximation with error < 10^-7. */ l -= 1.4426950408889634074 * z * (1.0 + z * (0.5 + z * ((1.0 / 3) + z * 0.25))); /* Finally multiply with log(2)/log(10), yields an approximation for log10(x). */ l *= 0.30102999566398119523; /* Round down to the next integer. */ return (int) l + (l < 0 ? -1 : 0); } # endif /* Tests whether a string of digits consists of exactly PRECISION zeroes and a single '1' digit. */ static int is_borderline (const char *digits, size_t precision) { for (; precision > 0; precision--, digits++) if (*digits != '0') return 0; if (*digits != '1') return 0; digits++; return *digits == '\0'; } #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF /* Use a different function name, to make it possible that the 'wchar_t' parametrization and the 'char' parametrization get compiled in the same translation unit. */ # if WIDE_CHAR_VERSION # define MAX_ROOM_NEEDED wmax_room_needed # else # define MAX_ROOM_NEEDED max_room_needed # endif /* Returns the number of TCHAR_T units needed as temporary space for the result of sprintf or SNPRINTF of a single conversion directive. */ static size_t MAX_ROOM_NEEDED (const arguments *ap, size_t arg_index, FCHAR_T conversion, arg_type type, int flags, size_t width, int has_precision, size_t precision, int pad_ourselves) { size_t tmp_length; switch (conversion) { case 'd': case 'i': case 'u': # if HAVE_LONG_LONG_INT if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT) tmp_length = (unsigned int) (sizeof (unsigned long long) * CHAR_BIT * 0.30103 /* binary -> decimal */ ) + 1; /* turn floor into ceil */ else # endif if (type == TYPE_LONGINT || type == TYPE_ULONGINT) tmp_length = (unsigned int) (sizeof (unsigned long) * CHAR_BIT * 0.30103 /* binary -> decimal */ ) + 1; /* turn floor into ceil */ else tmp_length = (unsigned int) (sizeof (unsigned int) * CHAR_BIT * 0.30103 /* binary -> decimal */ ) + 1; /* turn floor into ceil */ if (tmp_length < precision) tmp_length = precision; /* Multiply by 2, as an estimate for FLAG_GROUP. */ tmp_length = xsum (tmp_length, tmp_length); /* Add 1, to account for a leading sign. */ tmp_length = xsum (tmp_length, 1); break; case 'o': # if HAVE_LONG_LONG_INT if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT) tmp_length = (unsigned int) (sizeof (unsigned long long) * CHAR_BIT * 0.333334 /* binary -> octal */ ) + 1; /* turn floor into ceil */ else # endif if (type == TYPE_LONGINT || type == TYPE_ULONGINT) tmp_length = (unsigned int) (sizeof (unsigned long) * CHAR_BIT * 0.333334 /* binary -> octal */ ) + 1; /* turn floor into ceil */ else tmp_length = (unsigned int) (sizeof (unsigned int) * CHAR_BIT * 0.333334 /* binary -> octal */ ) + 1; /* turn floor into ceil */ if (tmp_length < precision) tmp_length = precision; /* Add 1, to account for a leading sign. */ tmp_length = xsum (tmp_length, 1); break; case 'x': case 'X': # if HAVE_LONG_LONG_INT if (type == TYPE_LONGLONGINT || type == TYPE_ULONGLONGINT) tmp_length = (unsigned int) (sizeof (unsigned long long) * CHAR_BIT * 0.25 /* binary -> hexadecimal */ ) + 1; /* turn floor into ceil */ else # endif if (type == TYPE_LONGINT || type == TYPE_ULONGINT) tmp_length = (unsigned int) (sizeof (unsigned long) * CHAR_BIT * 0.25 /* binary -> hexadecimal */ ) + 1; /* turn floor into ceil */ else tmp_length = (unsigned int) (sizeof (unsigned int) * CHAR_BIT * 0.25 /* binary -> hexadecimal */ ) + 1; /* turn floor into ceil */ if (tmp_length < precision) tmp_length = precision; /* Add 2, to account for a leading sign or alternate form. */ tmp_length = xsum (tmp_length, 2); break; case 'f': case 'F': if (type == TYPE_LONGDOUBLE) tmp_length = (unsigned int) (LDBL_MAX_EXP * 0.30103 /* binary -> decimal */ * 2 /* estimate for FLAG_GROUP */ ) + 1 /* turn floor into ceil */ + 10; /* sign, decimal point etc. */ else tmp_length = (unsigned int) (DBL_MAX_EXP * 0.30103 /* binary -> decimal */ * 2 /* estimate for FLAG_GROUP */ ) + 1 /* turn floor into ceil */ + 10; /* sign, decimal point etc. */ tmp_length = xsum (tmp_length, precision); break; case 'e': case 'E': case 'g': case 'G': tmp_length = 12; /* sign, decimal point, exponent etc. */ tmp_length = xsum (tmp_length, precision); break; case 'a': case 'A': if (type == TYPE_LONGDOUBLE) tmp_length = (unsigned int) (LDBL_DIG * 0.831 /* decimal -> hexadecimal */ ) + 1; /* turn floor into ceil */ else tmp_length = (unsigned int) (DBL_DIG * 0.831 /* decimal -> hexadecimal */ ) + 1; /* turn floor into ceil */ if (tmp_length < precision) tmp_length = precision; /* Account for sign, decimal point etc. */ tmp_length = xsum (tmp_length, 12); break; case 'c': # if HAVE_WINT_T && !WIDE_CHAR_VERSION if (type == TYPE_WIDE_CHAR) tmp_length = MB_CUR_MAX; else # endif tmp_length = 1; break; case 's': # if HAVE_WCHAR_T if (type == TYPE_WIDE_STRING) { # if WIDE_CHAR_VERSION /* ISO C says about %ls in fwprintf: "If the precision is not specified or is greater than the size of the array, the array shall contain a null wide character." So if there is a precision, we must not use wcslen. */ const wchar_t *arg = ap->arg[arg_index].a.a_wide_string; if (has_precision) tmp_length = local_wcsnlen (arg, precision); else tmp_length = local_wcslen (arg); # else /* ISO C says about %ls in fprintf: "If a precision is specified, no more than that many bytes are written (including shift sequences, if any), and the array shall contain a null wide character if, to equal the multibyte character sequence length given by the precision, the function would need to access a wide character one past the end of the array." So if there is a precision, we must not use wcslen. */ /* This case has already been handled separately in VASNPRINTF. */ abort (); # endif } else # endif { # if WIDE_CHAR_VERSION /* ISO C says about %s in fwprintf: "If the precision is not specified or is greater than the size of the converted array, the converted array shall contain a null wide character." So if there is a precision, we must not use strlen. */ /* This case has already been handled separately in VASNPRINTF. */ abort (); # else /* ISO C says about %s in fprintf: "If the precision is not specified or greater than the size of the array, the array shall contain a null character." So if there is a precision, we must not use strlen. */ const char *arg = ap->arg[arg_index].a.a_string; if (has_precision) tmp_length = local_strnlen (arg, precision); else tmp_length = strlen (arg); # endif } break; case 'p': tmp_length = (unsigned int) (sizeof (void *) * CHAR_BIT * 0.25 /* binary -> hexadecimal */ ) + 1 /* turn floor into ceil */ + 2; /* account for leading 0x */ break; default: abort (); } if (!pad_ourselves) { # if ENABLE_UNISTDIO /* Padding considers the number of characters, therefore the number of elements after padding may be > max (tmp_length, width) but is certainly <= tmp_length + width. */ tmp_length = xsum (tmp_length, width); # else /* Padding considers the number of elements, says POSIX. */ if (tmp_length < width) tmp_length = width; # endif } tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */ return tmp_length; } #endif DCHAR_T * VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp, const FCHAR_T *format, va_list args) { DIRECTIVES d; arguments a; if (PRINTF_PARSE (format, &d, &a) < 0) /* errno is already set. */ return NULL; #define CLEANUP() \ if (d.dir != d.direct_alloc_dir) \ free (d.dir); \ if (a.arg != a.direct_alloc_arg) \ free (a.arg); if (PRINTF_FETCHARGS (args, &a) < 0) { CLEANUP (); errno = EINVAL; return NULL; } { size_t buf_neededlength; TCHAR_T *buf; TCHAR_T *buf_malloced; const FCHAR_T *cp; size_t i; DIRECTIVE *dp; /* Output string accumulator. */ DCHAR_T *result; size_t allocated; size_t length; /* Allocate a small buffer that will hold a directive passed to sprintf or snprintf. */ buf_neededlength = xsum4 (7, d.max_width_length, d.max_precision_length, 6); #if HAVE_ALLOCA if (buf_neededlength < 4000 / sizeof (TCHAR_T)) { buf = (TCHAR_T *) alloca (buf_neededlength * sizeof (TCHAR_T)); buf_malloced = NULL; } else #endif { size_t buf_memsize = xtimes (buf_neededlength, sizeof (TCHAR_T)); if (size_overflow_p (buf_memsize)) goto out_of_memory_1; buf = (TCHAR_T *) malloc (buf_memsize); if (buf == NULL) goto out_of_memory_1; buf_malloced = buf; } if (resultbuf != NULL) { result = resultbuf; allocated = *lengthp; } else { result = NULL; allocated = 0; } length = 0; /* Invariants: result is either == resultbuf or == NULL or malloc-allocated. If length > 0, then result != NULL. */ /* Ensures that allocated >= needed. Aborts through a jump to out_of_memory if needed is SIZE_MAX or otherwise too big. */ #define ENSURE_ALLOCATION(needed) \ if ((needed) > allocated) \ { \ size_t memory_size; \ DCHAR_T *memory; \ \ allocated = (allocated > 0 ? xtimes (allocated, 2) : 12); \ if ((needed) > allocated) \ allocated = (needed); \ memory_size = xtimes (allocated, sizeof (DCHAR_T)); \ if (size_overflow_p (memory_size)) \ goto out_of_memory; \ if (result == resultbuf || result == NULL) \ memory = (DCHAR_T *) malloc (memory_size); \ else \ memory = (DCHAR_T *) realloc (result, memory_size); \ if (memory == NULL) \ goto out_of_memory; \ if (result == resultbuf && length > 0) \ DCHAR_CPY (memory, result, length); \ result = memory; \ } for (cp = format, i = 0, dp = &d.dir[0]; ; cp = dp->dir_end, i++, dp++) { if (cp != dp->dir_start) { size_t n = dp->dir_start - cp; size_t augmented_length = xsum (length, n); ENSURE_ALLOCATION (augmented_length); /* This copies a piece of FCHAR_T[] into a DCHAR_T[]. Here we need that the format string contains only ASCII characters if FCHAR_T and DCHAR_T are not the same type. */ if (sizeof (FCHAR_T) == sizeof (DCHAR_T)) { DCHAR_CPY (result + length, (const DCHAR_T *) cp, n); length = augmented_length; } else { do result[length++] = *cp++; while (--n > 0); } } if (i == d.count) break; /* Execute a single directive. */ if (dp->conversion == '%') { size_t augmented_length; if (!(dp->arg_index == ARG_NONE)) abort (); augmented_length = xsum (length, 1); ENSURE_ALLOCATION (augmented_length); result[length] = '%'; length = augmented_length; } else { if (!(dp->arg_index != ARG_NONE)) abort (); if (dp->conversion == 'n') { switch (a.arg[dp->arg_index].type) { case TYPE_COUNT_SCHAR_POINTER: *a.arg[dp->arg_index].a.a_count_schar_pointer = length; break; case TYPE_COUNT_SHORT_POINTER: *a.arg[dp->arg_index].a.a_count_short_pointer = length; break; case TYPE_COUNT_INT_POINTER: *a.arg[dp->arg_index].a.a_count_int_pointer = length; break; case TYPE_COUNT_LONGINT_POINTER: *a.arg[dp->arg_index].a.a_count_longint_pointer = length; break; #if HAVE_LONG_LONG_INT case TYPE_COUNT_LONGLONGINT_POINTER: *a.arg[dp->arg_index].a.a_count_longlongint_pointer = length; break; #endif default: abort (); } } #if ENABLE_UNISTDIO /* The unistdio extensions. */ else if (dp->conversion == 'U') { arg_type type = a.arg[dp->arg_index].type; int flags = dp->flags; int has_width; size_t width; int has_precision; size_t precision; has_width = 0; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { /* "A negative field width is taken as a '-' flag followed by a positive field width." */ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } has_width = 1; } has_precision = 0; precision = 0; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; /* "A negative precision is taken as if the precision were omitted." */ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } switch (type) { case TYPE_U8_STRING: { const uint8_t *arg = a.arg[dp->arg_index].a.a_u8_string; const uint8_t *arg_end; size_t characters; if (has_precision) { /* Use only PRECISION characters, from the left. */ arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count = u8_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { /* Use the entire string, and count the number of characters. */ arg_end = arg; characters = 0; for (;;) { int count = u8_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { /* Use the entire string. */ arg_end = arg + u8_strlen (arg); /* The number of characters doesn't matter. */ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_UINT8_T { size_t n = arg_end - arg; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_CPY (result + length, arg, n); length += n; } # else { /* Convert. */ DCHAR_T *converted = result + length; size_t converted_len = allocated - length; # if DCHAR_IS_TCHAR /* Convert from UTF-8 to locale encoding. */ converted = u8_conv_to_encoding (locale_charset (), iconveh_question_mark, arg, arg_end - arg, NULL, converted, &converted_len); # else /* Convert from UTF-8 to UTF-16/UTF-32. */ converted = U8_TO_DCHAR (arg, arg_end - arg, converted, &converted_len); # endif if (converted == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } if (converted != result + length) { ENSURE_ALLOCATION (xsum (length, converted_len)); DCHAR_CPY (result + length, converted, converted_len); free (converted); } length += converted_len; } # endif if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } break; case TYPE_U16_STRING: { const uint16_t *arg = a.arg[dp->arg_index].a.a_u16_string; const uint16_t *arg_end; size_t characters; if (has_precision) { /* Use only PRECISION characters, from the left. */ arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count = u16_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { /* Use the entire string, and count the number of characters. */ arg_end = arg; characters = 0; for (;;) { int count = u16_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { /* Use the entire string. */ arg_end = arg + u16_strlen (arg); /* The number of characters doesn't matter. */ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_UINT16_T { size_t n = arg_end - arg; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_CPY (result + length, arg, n); length += n; } # else { /* Convert. */ DCHAR_T *converted = result + length; size_t converted_len = allocated - length; # if DCHAR_IS_TCHAR /* Convert from UTF-16 to locale encoding. */ converted = u16_conv_to_encoding (locale_charset (), iconveh_question_mark, arg, arg_end - arg, NULL, converted, &converted_len); # else /* Convert from UTF-16 to UTF-8/UTF-32. */ converted = U16_TO_DCHAR (arg, arg_end - arg, converted, &converted_len); # endif if (converted == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } if (converted != result + length) { ENSURE_ALLOCATION (xsum (length, converted_len)); DCHAR_CPY (result + length, converted, converted_len); free (converted); } length += converted_len; } # endif if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } break; case TYPE_U32_STRING: { const uint32_t *arg = a.arg[dp->arg_index].a.a_u32_string; const uint32_t *arg_end; size_t characters; if (has_precision) { /* Use only PRECISION characters, from the left. */ arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count = u32_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { /* Use the entire string, and count the number of characters. */ arg_end = arg; characters = 0; for (;;) { int count = u32_strmblen (arg_end); if (count == 0) break; if (count < 0) { if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { /* Use the entire string. */ arg_end = arg + u32_strlen (arg); /* The number of characters doesn't matter. */ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_UINT32_T { size_t n = arg_end - arg; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_CPY (result + length, arg, n); length += n; } # else { /* Convert. */ DCHAR_T *converted = result + length; size_t converted_len = allocated - length; # if DCHAR_IS_TCHAR /* Convert from UTF-32 to locale encoding. */ converted = u32_conv_to_encoding (locale_charset (), iconveh_question_mark, arg, arg_end - arg, NULL, converted, &converted_len); # else /* Convert from UTF-32 to UTF-8/UTF-16. */ converted = U32_TO_DCHAR (arg, arg_end - arg, converted, &converted_len); # endif if (converted == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } if (converted != result + length) { ENSURE_ALLOCATION (xsum (length, converted_len)); DCHAR_CPY (result + length, converted, converted_len); free (converted); } length += converted_len; } # endif if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } break; default: abort (); } } #endif #if (!USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || (NEED_PRINTF_DIRECTIVE_LS && !defined IN_LIBINTL)) && HAVE_WCHAR_T else if (dp->conversion == 's' # if WIDE_CHAR_VERSION && a.arg[dp->arg_index].type != TYPE_WIDE_STRING # else && a.arg[dp->arg_index].type == TYPE_WIDE_STRING # endif ) { /* The normal handling of the 's' directive below requires allocating a temporary buffer. The determination of its length (tmp_length), in the case when a precision is specified, below requires a conversion between a char[] string and a wchar_t[] wide string. It could be done, but we have no guarantee that the implementation of sprintf will use the exactly same algorithm. Without this guarantee, it is possible to have buffer overrun bugs. In order to avoid such bugs, we implement the entire processing of the 's' directive ourselves. */ int flags = dp->flags; int has_width; size_t width; int has_precision; size_t precision; has_width = 0; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { /* "A negative field width is taken as a '-' flag followed by a positive field width." */ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } has_width = 1; } has_precision = 0; precision = 6; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; /* "A negative precision is taken as if the precision were omitted." */ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } # if WIDE_CHAR_VERSION /* %s in vasnwprintf. See the specification of fwprintf. */ { const char *arg = a.arg[dp->arg_index].a.a_string; const char *arg_end; size_t characters; if (has_precision) { /* Use only as many bytes as needed to produce PRECISION wide characters, from the left. */ # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; for (; precision > 0; precision--) { int count; # if HAVE_MBRTOWC count = mbrlen (arg_end, MB_CUR_MAX, &state); # else count = mblen (arg_end, MB_CUR_MAX); # endif if (count == 0) /* Found the terminating NUL. */ break; if (count < 0) { /* Invalid or incomplete multibyte character. */ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else if (has_width) { /* Use the entire string, and count the number of wide characters. */ # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; for (;;) { int count; # if HAVE_MBRTOWC count = mbrlen (arg_end, MB_CUR_MAX, &state); # else count = mblen (arg_end, MB_CUR_MAX); # endif if (count == 0) /* Found the terminating NUL. */ break; if (count < 0) { /* Invalid or incomplete multibyte character. */ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end += count; characters++; } } else { /* Use the entire string. */ arg_end = arg + strlen (arg); /* The number of characters doesn't matter. */ characters = 0; } if (characters < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } if (has_precision || has_width) { /* We know the number of wide characters in advance. */ size_t remaining; # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif ENSURE_ALLOCATION (xsum (length, characters)); for (remaining = characters; remaining > 0; remaining--) { wchar_t wc; int count; # if HAVE_MBRTOWC count = mbrtowc (&wc, arg, arg_end - arg, &state); # else count = mbtowc (&wc, arg, arg_end - arg); # endif if (count <= 0) /* mbrtowc not consistent with mbrlen, or mbtowc not consistent with mblen. */ abort (); result[length++] = wc; arg += count; } if (!(arg == arg_end)) abort (); } else { # if HAVE_MBRTOWC mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif while (arg < arg_end) { wchar_t wc; int count; # if HAVE_MBRTOWC count = mbrtowc (&wc, arg, arg_end - arg, &state); # else count = mbtowc (&wc, arg, arg_end - arg); # endif if (count <= 0) /* mbrtowc not consistent with mbrlen, or mbtowc not consistent with mblen. */ abort (); ENSURE_ALLOCATION (xsum (length, 1)); result[length++] = wc; arg += count; } } if (characters < width && (dp->flags & FLAG_LEFT)) { size_t n = width - characters; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } # else /* %ls in vasnprintf. See the specification of fprintf. */ { const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string; const wchar_t *arg_end; size_t characters; # if !DCHAR_IS_TCHAR /* This code assumes that TCHAR_T is 'char'. */ verify (sizeof (TCHAR_T) == 1); TCHAR_T *tmpsrc; DCHAR_T *tmpdst; size_t tmpdst_len; # endif size_t w; if (has_precision) { /* Use only as many wide characters as needed to produce at most PRECISION bytes, from the left. */ # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; while (precision > 0) { char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */ int count; if (*arg_end == 0) /* Found the terminating null wide character. */ break; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg_end, &state); # else count = wctomb (cbuf, *arg_end); # endif if (count < 0) { /* Cannot convert. */ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } if (precision < count) break; arg_end++; characters += count; precision -= count; } } # if DCHAR_IS_TCHAR else if (has_width) # else else # endif { /* Use the entire string, and count the number of bytes. */ # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif arg_end = arg; characters = 0; for (;;) { char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */ int count; if (*arg_end == 0) /* Found the terminating null wide character. */ break; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg_end, &state); # else count = wctomb (cbuf, *arg_end); # endif if (count < 0) { /* Cannot convert. */ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } arg_end++; characters += count; } } # if DCHAR_IS_TCHAR else { /* Use the entire string. */ arg_end = arg + local_wcslen (arg); /* The number of bytes doesn't matter. */ characters = 0; } # endif # if !DCHAR_IS_TCHAR /* Convert the string into a piece of temporary memory. */ tmpsrc = (TCHAR_T *) malloc (characters * sizeof (TCHAR_T)); if (tmpsrc == NULL) goto out_of_memory; { TCHAR_T *tmpptr = tmpsrc; size_t remaining; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif for (remaining = characters; remaining > 0; ) { char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */ int count; if (*arg == 0) abort (); # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg, &state); # else count = wctomb (cbuf, *arg); # endif if (count <= 0) /* Inconsistency. */ abort (); memcpy (tmpptr, cbuf, count); tmpptr += count; arg++; remaining -= count; } if (!(arg == arg_end)) abort (); } /* Convert from TCHAR_T[] to DCHAR_T[]. */ tmpdst = DCHAR_CONV_FROM_ENCODING (locale_charset (), iconveh_question_mark, tmpsrc, characters, NULL, NULL, &tmpdst_len); if (tmpdst == NULL) { int saved_errno = errno; free (tmpsrc); if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } free (tmpsrc); # endif if (has_width) { # if ENABLE_UNISTDIO /* Outside POSIX, it's preferable to compare the width against the number of _characters_ of the converted value. */ w = DCHAR_MBSNLEN (result + length, characters); # else /* The width is compared against the number of _bytes_ of the converted value, says POSIX. */ w = characters; # endif } else /* w doesn't matter. */ w = 0; if (w < width && !(dp->flags & FLAG_LEFT)) { size_t n = width - w; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } # if DCHAR_IS_TCHAR if (has_precision || has_width) { /* We know the number of bytes in advance. */ size_t remaining; # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif ENSURE_ALLOCATION (xsum (length, characters)); for (remaining = characters; remaining > 0; ) { char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */ int count; if (*arg == 0) abort (); # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg, &state); # else count = wctomb (cbuf, *arg); # endif if (count <= 0) /* Inconsistency. */ abort (); memcpy (result + length, cbuf, count); length += count; arg++; remaining -= count; } if (!(arg == arg_end)) abort (); } else { # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t mbstate_t state; memset (&state, '\0', sizeof (mbstate_t)); # endif while (arg < arg_end) { char cbuf[64]; /* Assume MB_CUR_MAX <= 64. */ int count; if (*arg == 0) abort (); # if HAVE_WCRTOMB && !defined GNULIB_defined_mbstate_t count = wcrtomb (cbuf, *arg, &state); # else count = wctomb (cbuf, *arg); # endif if (count <= 0) { /* Cannot convert. */ if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EILSEQ; return NULL; } ENSURE_ALLOCATION (xsum (length, count)); memcpy (result + length, cbuf, count); length += count; arg++; } } # else ENSURE_ALLOCATION (xsum (length, tmpdst_len)); DCHAR_CPY (result + length, tmpdst, tmpdst_len); free (tmpdst); length += tmpdst_len; # endif if (w < width && (dp->flags & FLAG_LEFT)) { size_t n = width - w; ENSURE_ALLOCATION (xsum (length, n)); DCHAR_SET (result + length, ' ', n); length += n; } } # endif } #endif #if (NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_DOUBLE) && !defined IN_LIBINTL else if ((dp->conversion == 'a' || dp->conversion == 'A') # if !(NEED_PRINTF_DIRECTIVE_A || (NEED_PRINTF_LONG_DOUBLE && NEED_PRINTF_DOUBLE)) && (0 # if NEED_PRINTF_DOUBLE || a.arg[dp->arg_index].type == TYPE_DOUBLE # endif # if NEED_PRINTF_LONG_DOUBLE || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE # endif ) # endif ) { arg_type type = a.arg[dp->arg_index].type; int flags = dp->flags; size_t width; int has_precision; size_t precision; size_t tmp_length; size_t count; DCHAR_T tmpbuf[700]; DCHAR_T *tmp; DCHAR_T *pad_ptr; DCHAR_T *p; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { /* "A negative field width is taken as a '-' flag followed by a positive field width." */ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } } has_precision = 0; precision = 0; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; /* "A negative precision is taken as if the precision were omitted." */ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } /* Allocate a temporary buffer of sufficient size. */ if (type == TYPE_LONGDOUBLE) tmp_length = (unsigned int) ((LDBL_DIG + 1) * 0.831 /* decimal -> hexadecimal */ ) + 1; /* turn floor into ceil */ else tmp_length = (unsigned int) ((DBL_DIG + 1) * 0.831 /* decimal -> hexadecimal */ ) + 1; /* turn floor into ceil */ if (tmp_length < precision) tmp_length = precision; /* Account for sign, decimal point etc. */ tmp_length = xsum (tmp_length, 12); if (tmp_length < width) tmp_length = width; tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */ if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T)) tmp = tmpbuf; else { size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T)); if (size_overflow_p (tmp_memsize)) /* Overflow, would lead to out of memory. */ goto out_of_memory; tmp = (DCHAR_T *) malloc (tmp_memsize); if (tmp == NULL) /* Out of memory. */ goto out_of_memory; } pad_ptr = NULL; p = tmp; if (type == TYPE_LONGDOUBLE) { # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_LONG_DOUBLE long double arg = a.arg[dp->arg_index].a.a_longdouble; if (isnanl (arg)) { if (dp->conversion == 'A') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; DECL_LONG_DOUBLE_ROUNDING BEGIN_LONG_DOUBLE_ROUNDING (); if (signbit (arg)) /* arg < 0.0L or negative zero */ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0L && arg + arg == arg) { if (dp->conversion == 'A') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { int exponent; long double mantissa; if (arg > 0.0L) mantissa = printf_frexpl (arg, &exponent); else { exponent = 0; mantissa = 0.0L; } if (has_precision && precision < (unsigned int) ((LDBL_DIG + 1) * 0.831) + 1) { /* Round the mantissa. */ long double tail = mantissa; size_t q; for (q = precision; ; q--) { int digit = (int) tail; tail -= digit; if (q == 0) { if (digit & 1 ? tail >= 0.5L : tail > 0.5L) tail = 1 - tail; else tail = - tail; break; } tail *= 16.0L; } if (tail != 0.0L) for (q = precision; q > 0; q--) tail *= 0.0625L; mantissa += tail; } *p++ = '0'; *p++ = dp->conversion - 'A' + 'X'; pad_ptr = p; { int digit; digit = (int) mantissa; mantissa -= digit; *p++ = '0' + digit; if ((flags & FLAG_ALT) || mantissa > 0.0L || precision > 0) { *p++ = decimal_point_char (); /* This loop terminates because we assume that FLT_RADIX is a power of 2. */ while (mantissa > 0.0L) { mantissa *= 16.0L; digit = (int) mantissa; mantissa -= digit; *p++ = digit + (digit < 10 ? '0' : dp->conversion - 10); if (precision > 0) precision--; } while (precision > 0) { *p++ = '0'; precision--; } } } *p++ = dp->conversion - 'A' + 'P'; # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', 'd', '\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, "%+d", exponent); while (*p != '\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, "%+d", exponent); for (ep = expbuf; (*p = *ep) != '\0'; ep++) p++; } # endif } END_LONG_DOUBLE_ROUNDING (); } # else abort (); # endif } else { # if NEED_PRINTF_DIRECTIVE_A || NEED_PRINTF_DOUBLE double arg = a.arg[dp->arg_index].a.a_double; if (isnand (arg)) { if (dp->conversion == 'A') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; if (signbit (arg)) /* arg < 0.0 or negative zero */ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0 && arg + arg == arg) { if (dp->conversion == 'A') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { int exponent; double mantissa; if (arg > 0.0) mantissa = printf_frexp (arg, &exponent); else { exponent = 0; mantissa = 0.0; } if (has_precision && precision < (unsigned int) ((DBL_DIG + 1) * 0.831) + 1) { /* Round the mantissa. */ double tail = mantissa; size_t q; for (q = precision; ; q--) { int digit = (int) tail; tail -= digit; if (q == 0) { if (digit & 1 ? tail >= 0.5 : tail > 0.5) tail = 1 - tail; else tail = - tail; break; } tail *= 16.0; } if (tail != 0.0) for (q = precision; q > 0; q--) tail *= 0.0625; mantissa += tail; } *p++ = '0'; *p++ = dp->conversion - 'A' + 'X'; pad_ptr = p; { int digit; digit = (int) mantissa; mantissa -= digit; *p++ = '0' + digit; if ((flags & FLAG_ALT) || mantissa > 0.0 || precision > 0) { *p++ = decimal_point_char (); /* This loop terminates because we assume that FLT_RADIX is a power of 2. */ while (mantissa > 0.0) { mantissa *= 16.0; digit = (int) mantissa; mantissa -= digit; *p++ = digit + (digit < 10 ? '0' : dp->conversion - 10); if (precision > 0) precision--; } while (precision > 0) { *p++ = '0'; precision--; } } } *p++ = dp->conversion - 'A' + 'P'; # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', 'd', '\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, "%+d", exponent); while (*p != '\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, "%+d", exponent); for (ep = expbuf; (*p = *ep) != '\0'; ep++) p++; } # endif } } # else abort (); # endif } /* The generated string now extends from tmp to p, with the zero padding insertion point being at pad_ptr. */ count = p - tmp; if (count < width) { size_t pad = width - count; DCHAR_T *end = p + pad; if (flags & FLAG_LEFT) { /* Pad with spaces on the right. */ for (; pad > 0; pad--) *p++ = ' '; } else if ((flags & FLAG_ZERO) && pad_ptr != NULL) { /* Pad with zeroes. */ DCHAR_T *q = end; while (p > pad_ptr) *--q = *--p; for (; pad > 0; pad--) *p++ = '0'; } else { /* Pad with spaces on the left. */ DCHAR_T *q = end; while (p > tmp) *--q = *--p; for (; pad > 0; pad--) *p++ = ' '; } p = end; } count = p - tmp; if (count >= tmp_length) /* tmp_length was incorrectly calculated - fix the code above! */ abort (); /* Make room for the result. */ if (count >= allocated - length) { size_t n = xsum (length, count); ENSURE_ALLOCATION (n); } /* Append the result. */ memcpy (result + length, tmp, count * sizeof (DCHAR_T)); if (tmp != tmpbuf) free (tmp); length += count; } #endif #if (NEED_PRINTF_INFINITE_DOUBLE || NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE || NEED_PRINTF_LONG_DOUBLE) && !defined IN_LIBINTL else if ((dp->conversion == 'f' || dp->conversion == 'F' || dp->conversion == 'e' || dp->conversion == 'E' || dp->conversion == 'g' || dp->conversion == 'G' || dp->conversion == 'a' || dp->conversion == 'A') && (0 # if NEED_PRINTF_DOUBLE || a.arg[dp->arg_index].type == TYPE_DOUBLE # elif NEED_PRINTF_INFINITE_DOUBLE || (a.arg[dp->arg_index].type == TYPE_DOUBLE /* The systems (mingw) which produce wrong output for Inf, -Inf, and NaN also do so for -0.0. Therefore we treat this case here as well. */ && is_infinite_or_zero (a.arg[dp->arg_index].a.a_double)) # endif # if NEED_PRINTF_LONG_DOUBLE || a.arg[dp->arg_index].type == TYPE_LONGDOUBLE # elif NEED_PRINTF_INFINITE_LONG_DOUBLE || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE /* Some systems produce wrong output for Inf, -Inf, and NaN. Some systems in this category (IRIX 5.3) also do so for -0.0. Therefore we treat this case here as well. */ && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble)) # endif )) { # if (NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE) && (NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE) arg_type type = a.arg[dp->arg_index].type; # endif int flags = dp->flags; size_t width; size_t count; int has_precision; size_t precision; size_t tmp_length; DCHAR_T tmpbuf[700]; DCHAR_T *tmp; DCHAR_T *pad_ptr; DCHAR_T *p; width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { /* "A negative field width is taken as a '-' flag followed by a positive field width." */ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } } has_precision = 0; precision = 0; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; /* "A negative precision is taken as if the precision were omitted." */ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } /* POSIX specifies the default precision to be 6 for %f, %F, %e, %E, but not for %g, %G. Implementations appear to use the same default precision also for %g, %G. But for %a, %A, the default precision is 0. */ if (!has_precision) if (!(dp->conversion == 'a' || dp->conversion == 'A')) precision = 6; /* Allocate a temporary buffer of sufficient size. */ # if NEED_PRINTF_DOUBLE && NEED_PRINTF_LONG_DOUBLE tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : DBL_DIG + 1); # elif NEED_PRINTF_INFINITE_DOUBLE && NEED_PRINTF_LONG_DOUBLE tmp_length = (type == TYPE_LONGDOUBLE ? LDBL_DIG + 1 : 0); # elif NEED_PRINTF_LONG_DOUBLE tmp_length = LDBL_DIG + 1; # elif NEED_PRINTF_DOUBLE tmp_length = DBL_DIG + 1; # else tmp_length = 0; # endif if (tmp_length < precision) tmp_length = precision; # if NEED_PRINTF_LONG_DOUBLE # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE if (type == TYPE_LONGDOUBLE) # endif if (dp->conversion == 'f' || dp->conversion == 'F') { long double arg = a.arg[dp->arg_index].a.a_longdouble; if (!(isnanl (arg) || arg + arg == arg)) { /* arg is finite and nonzero. */ int exponent = floorlog10l (arg < 0 ? -arg : arg); if (exponent >= 0 && tmp_length < exponent + precision) tmp_length = exponent + precision; } } # endif # if NEED_PRINTF_DOUBLE # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE if (type == TYPE_DOUBLE) # endif if (dp->conversion == 'f' || dp->conversion == 'F') { double arg = a.arg[dp->arg_index].a.a_double; if (!(isnand (arg) || arg + arg == arg)) { /* arg is finite and nonzero. */ int exponent = floorlog10 (arg < 0 ? -arg : arg); if (exponent >= 0 && tmp_length < exponent + precision) tmp_length = exponent + precision; } } # endif /* Account for sign, decimal point etc. */ tmp_length = xsum (tmp_length, 12); if (tmp_length < width) tmp_length = width; tmp_length = xsum (tmp_length, 1); /* account for trailing NUL */ if (tmp_length <= sizeof (tmpbuf) / sizeof (DCHAR_T)) tmp = tmpbuf; else { size_t tmp_memsize = xtimes (tmp_length, sizeof (DCHAR_T)); if (size_overflow_p (tmp_memsize)) /* Overflow, would lead to out of memory. */ goto out_of_memory; tmp = (DCHAR_T *) malloc (tmp_memsize); if (tmp == NULL) /* Out of memory. */ goto out_of_memory; } pad_ptr = NULL; p = tmp; # if NEED_PRINTF_LONG_DOUBLE || NEED_PRINTF_INFINITE_LONG_DOUBLE # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE if (type == TYPE_LONGDOUBLE) # endif { long double arg = a.arg[dp->arg_index].a.a_longdouble; if (isnanl (arg)) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; DECL_LONG_DOUBLE_ROUNDING BEGIN_LONG_DOUBLE_ROUNDING (); if (signbit (arg)) /* arg < 0.0L or negative zero */ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0L && arg + arg == arg) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { # if NEED_PRINTF_LONG_DOUBLE pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { char *digits; size_t ndigits; digits = scale10_round_decimal_long_double (arg, precision); if (digits == NULL) { END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } ndigits = strlen (digits); if (ndigits > precision) do { --ndigits; *p++ = digits[ndigits]; } while (ndigits > precision); else *p++ = '0'; /* Here ndigits <= precision. */ if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > ndigits; precision--) *p++ = '0'; while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } else if (dp->conversion == 'e' || dp->conversion == 'E') { int exponent; if (arg == 0.0L) { exponent = 0; *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else { /* arg > 0.0L. */ int adjusted; char *digits; size_t ndigits; exponent = floorlog10l (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_long_double (arg, (int)precision - exponent); if (digits == NULL) { END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } ndigits = strlen (digits); if (ndigits == precision + 1) break; if (ndigits < precision || ndigits > precision + 2) /* The exponent was not guessed precisely enough. */ abort (); if (adjusted) /* None of two values of exponent is the right one. Prevent an endless loop. */ abort (); free (digits); if (ndigits == precision) exponent -= 1; else exponent += 1; adjusted = 1; } /* Here ndigits = precision+1. */ if (is_borderline (digits, precision)) { /* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. */ char *digits2 = scale10_round_decimal_long_double (arg, (int)precision - exponent + 1); if (digits2 == NULL) { free (digits); END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } if (strlen (digits2) == precision + 1) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } /* Here ndigits = precision+1. */ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } *p++ = dp->conversion; /* 'e' or 'E' */ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', '.', '2', 'd', '\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, "%+.2d", exponent); while (*p != '\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, "%+.2d", exponent); for (ep = expbuf; (*p = *ep) != '\0'; ep++) p++; } # endif } else if (dp->conversion == 'g' || dp->conversion == 'G') { if (precision == 0) precision = 1; /* precision >= 1. */ if (arg == 0.0L) /* The exponent is 0, >= -4, < precision. Use fixed-point notation. */ { size_t ndigits = precision; /* Number of trailing zeroes that have to be dropped. */ size_t nzeroes = (flags & FLAG_ALT ? 0 : precision - 1); --ndigits; *p++ = '0'; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = '0'; } } } else { /* arg > 0.0L. */ int exponent; int adjusted; char *digits; size_t ndigits; size_t nzeroes; exponent = floorlog10l (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_long_double (arg, (int)(precision - 1) - exponent); if (digits == NULL) { END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } ndigits = strlen (digits); if (ndigits == precision) break; if (ndigits < precision - 1 || ndigits > precision + 1) /* The exponent was not guessed precisely enough. */ abort (); if (adjusted) /* None of two values of exponent is the right one. Prevent an endless loop. */ abort (); free (digits); if (ndigits < precision) exponent -= 1; else exponent += 1; adjusted = 1; } /* Here ndigits = precision. */ if (is_borderline (digits, precision - 1)) { /* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. */ char *digits2 = scale10_round_decimal_long_double (arg, (int)(precision - 1) - exponent + 1); if (digits2 == NULL) { free (digits); END_LONG_DOUBLE_ROUNDING (); goto out_of_memory; } if (strlen (digits2) == precision) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } /* Here ndigits = precision. */ /* Determine the number of trailing zeroes that have to be dropped. */ nzeroes = 0; if ((flags & FLAG_ALT) == 0) while (nzeroes < ndigits && digits[nzeroes] == '0') nzeroes++; /* The exponent is now determined. */ if (exponent >= -4 && exponent < (long)precision) { /* Fixed-point notation: max(exponent,0)+1 digits, then the decimal point, then the remaining digits without trailing zeroes. */ if (exponent >= 0) { size_t ecount = exponent + 1; /* Note: count <= precision = ndigits. */ for (; ecount > 0; ecount--) *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { size_t ecount = -exponent - 1; *p++ = '0'; *p++ = decimal_point_char (); for (; ecount > 0; ecount--) *p++ = '0'; while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { /* Exponential notation. */ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = { '%', '+', '.', '2', 'd', '\0' }; SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\0') p++; # else if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, "%+.2d", exponent); while (*p != '\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, "%+.2d", exponent); for (ep = expbuf; (*p = *ep) != '\0'; ep++) p++; } # endif } free (digits); } } else abort (); # else /* arg is finite. */ if (!(arg == 0.0L)) abort (); pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else if (dp->conversion == 'e' || dp->conversion == 'E') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } *p++ = dp->conversion; /* 'e' or 'E' */ *p++ = '+'; *p++ = '0'; *p++ = '0'; } else if (dp->conversion == 'g' || dp->conversion == 'G') { *p++ = '0'; if (flags & FLAG_ALT) { size_t ndigits = (precision > 0 ? precision - 1 : 0); *p++ = decimal_point_char (); for (; ndigits > 0; --ndigits) *p++ = '0'; } } else if (dp->conversion == 'a' || dp->conversion == 'A') { *p++ = '0'; *p++ = dp->conversion - 'A' + 'X'; pad_ptr = p; *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } *p++ = dp->conversion - 'A' + 'P'; *p++ = '+'; *p++ = '0'; } else abort (); # endif } END_LONG_DOUBLE_ROUNDING (); } } # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE else # endif # endif # if NEED_PRINTF_DOUBLE || NEED_PRINTF_INFINITE_DOUBLE { double arg = a.arg[dp->arg_index].a.a_double; if (isnand (arg)) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'N'; *p++ = 'A'; *p++ = 'N'; } else { *p++ = 'n'; *p++ = 'a'; *p++ = 'n'; } } else { int sign = 0; if (signbit (arg)) /* arg < 0.0 or negative zero */ { sign = -1; arg = -arg; } if (sign < 0) *p++ = '-'; else if (flags & FLAG_SHOWSIGN) *p++ = '+'; else if (flags & FLAG_SPACE) *p++ = ' '; if (arg > 0.0 && arg + arg == arg) { if (dp->conversion >= 'A' && dp->conversion <= 'Z') { *p++ = 'I'; *p++ = 'N'; *p++ = 'F'; } else { *p++ = 'i'; *p++ = 'n'; *p++ = 'f'; } } else { # if NEED_PRINTF_DOUBLE pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { char *digits; size_t ndigits; digits = scale10_round_decimal_double (arg, precision); if (digits == NULL) goto out_of_memory; ndigits = strlen (digits); if (ndigits > precision) do { --ndigits; *p++ = digits[ndigits]; } while (ndigits > precision); else *p++ = '0'; /* Here ndigits <= precision. */ if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > ndigits; precision--) *p++ = '0'; while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } else if (dp->conversion == 'e' || dp->conversion == 'E') { int exponent; if (arg == 0.0) { exponent = 0; *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else { /* arg > 0.0. */ int adjusted; char *digits; size_t ndigits; exponent = floorlog10 (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_double (arg, (int)precision - exponent); if (digits == NULL) goto out_of_memory; ndigits = strlen (digits); if (ndigits == precision + 1) break; if (ndigits < precision || ndigits > precision + 2) /* The exponent was not guessed precisely enough. */ abort (); if (adjusted) /* None of two values of exponent is the right one. Prevent an endless loop. */ abort (); free (digits); if (ndigits == precision) exponent -= 1; else exponent += 1; adjusted = 1; } /* Here ndigits = precision+1. */ if (is_borderline (digits, precision)) { /* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. */ char *digits2 = scale10_round_decimal_double (arg, (int)precision - exponent + 1); if (digits2 == NULL) { free (digits); goto out_of_memory; } if (strlen (digits2) == precision + 1) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } /* Here ndigits = precision+1. */ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); while (ndigits > 0) { --ndigits; *p++ = digits[ndigits]; } } free (digits); } *p++ = dp->conversion; /* 'e' or 'E' */ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = /* Produce the same number of exponent digits as the native printf implementation. */ # if defined _WIN32 && ! defined __CYGWIN__ { '%', '+', '.', '3', 'd', '\0' }; # else { '%', '+', '.', '2', 'd', '\0' }; # endif SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\0') p++; # else { static const char decimal_format[] = /* Produce the same number of exponent digits as the native printf implementation. */ # if defined _WIN32 && ! defined __CYGWIN__ "%+.3d"; # else "%+.2d"; # endif if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, decimal_format, exponent); while (*p != '\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, decimal_format, exponent); for (ep = expbuf; (*p = *ep) != '\0'; ep++) p++; } } # endif } else if (dp->conversion == 'g' || dp->conversion == 'G') { if (precision == 0) precision = 1; /* precision >= 1. */ if (arg == 0.0) /* The exponent is 0, >= -4, < precision. Use fixed-point notation. */ { size_t ndigits = precision; /* Number of trailing zeroes that have to be dropped. */ size_t nzeroes = (flags & FLAG_ALT ? 0 : precision - 1); --ndigits; *p++ = '0'; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = '0'; } } } else { /* arg > 0.0. */ int exponent; int adjusted; char *digits; size_t ndigits; size_t nzeroes; exponent = floorlog10 (arg); adjusted = 0; for (;;) { digits = scale10_round_decimal_double (arg, (int)(precision - 1) - exponent); if (digits == NULL) goto out_of_memory; ndigits = strlen (digits); if (ndigits == precision) break; if (ndigits < precision - 1 || ndigits > precision + 1) /* The exponent was not guessed precisely enough. */ abort (); if (adjusted) /* None of two values of exponent is the right one. Prevent an endless loop. */ abort (); free (digits); if (ndigits < precision) exponent -= 1; else exponent += 1; adjusted = 1; } /* Here ndigits = precision. */ if (is_borderline (digits, precision - 1)) { /* Maybe the exponent guess was too high and a smaller exponent can be reached by turning a 10...0 into 9...9x. */ char *digits2 = scale10_round_decimal_double (arg, (int)(precision - 1) - exponent + 1); if (digits2 == NULL) { free (digits); goto out_of_memory; } if (strlen (digits2) == precision) { free (digits); digits = digits2; exponent -= 1; } else free (digits2); } /* Here ndigits = precision. */ /* Determine the number of trailing zeroes that have to be dropped. */ nzeroes = 0; if ((flags & FLAG_ALT) == 0) while (nzeroes < ndigits && digits[nzeroes] == '0') nzeroes++; /* The exponent is now determined. */ if (exponent >= -4 && exponent < (long)precision) { /* Fixed-point notation: max(exponent,0)+1 digits, then the decimal point, then the remaining digits without trailing zeroes. */ if (exponent >= 0) { size_t ecount = exponent + 1; /* Note: ecount <= precision = ndigits. */ for (; ecount > 0; ecount--) *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { size_t ecount = -exponent - 1; *p++ = '0'; *p++ = decimal_point_char (); for (; ecount > 0; ecount--) *p++ = '0'; while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } } else { /* Exponential notation. */ *p++ = digits[--ndigits]; if ((flags & FLAG_ALT) || ndigits > nzeroes) { *p++ = decimal_point_char (); while (ndigits > nzeroes) { --ndigits; *p++ = digits[ndigits]; } } *p++ = dp->conversion - 'G' + 'E'; /* 'e' or 'E' */ # if WIDE_CHAR_VERSION { static const wchar_t decimal_format[] = /* Produce the same number of exponent digits as the native printf implementation. */ # if defined _WIN32 && ! defined __CYGWIN__ { '%', '+', '.', '3', 'd', '\0' }; # else { '%', '+', '.', '2', 'd', '\0' }; # endif SNPRINTF (p, 6 + 1, decimal_format, exponent); } while (*p != '\0') p++; # else { static const char decimal_format[] = /* Produce the same number of exponent digits as the native printf implementation. */ # if defined _WIN32 && ! defined __CYGWIN__ "%+.3d"; # else "%+.2d"; # endif if (sizeof (DCHAR_T) == 1) { sprintf ((char *) p, decimal_format, exponent); while (*p != '\0') p++; } else { char expbuf[6 + 1]; const char *ep; sprintf (expbuf, decimal_format, exponent); for (ep = expbuf; (*p = *ep) != '\0'; ep++) p++; } } # endif } free (digits); } } else abort (); # else /* arg is finite. */ if (!(arg == 0.0)) abort (); pad_ptr = p; if (dp->conversion == 'f' || dp->conversion == 'F') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } } else if (dp->conversion == 'e' || dp->conversion == 'E') { *p++ = '0'; if ((flags & FLAG_ALT) || precision > 0) { *p++ = decimal_point_char (); for (; precision > 0; precision--) *p++ = '0'; } *p++ = dp->conversion; /* 'e' or 'E' */ *p++ = '+'; /* Produce the same number of exponent digits as the native printf implementation. */ # if defined _WIN32 && ! defined __CYGWIN__ *p++ = '0'; # endif *p++ = '0'; *p++ = '0'; } else if (dp->conversion == 'g' || dp->conversion == 'G') { *p++ = '0'; if (flags & FLAG_ALT) { size_t ndigits = (precision > 0 ? precision - 1 : 0); *p++ = decimal_point_char (); for (; ndigits > 0; --ndigits) *p++ = '0'; } } else abort (); # endif } } } # endif /* The generated string now extends from tmp to p, with the zero padding insertion point being at pad_ptr. */ count = p - tmp; if (count < width) { size_t pad = width - count; DCHAR_T *end = p + pad; if (flags & FLAG_LEFT) { /* Pad with spaces on the right. */ for (; pad > 0; pad--) *p++ = ' '; } else if ((flags & FLAG_ZERO) && pad_ptr != NULL) { /* Pad with zeroes. */ DCHAR_T *q = end; while (p > pad_ptr) *--q = *--p; for (; pad > 0; pad--) *p++ = '0'; } else { /* Pad with spaces on the left. */ DCHAR_T *q = end; while (p > tmp) *--q = *--p; for (; pad > 0; pad--) *p++ = ' '; } p = end; } count = p - tmp; if (count >= tmp_length) /* tmp_length was incorrectly calculated - fix the code above! */ abort (); /* Make room for the result. */ if (count >= allocated - length) { size_t n = xsum (length, count); ENSURE_ALLOCATION (n); } /* Append the result. */ memcpy (result + length, tmp, count * sizeof (DCHAR_T)); if (tmp != tmpbuf) free (tmp); length += count; } #endif else { arg_type type = a.arg[dp->arg_index].type; int flags = dp->flags; #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION int has_width; #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION size_t width; #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION int has_precision; size_t precision; #endif #if NEED_PRINTF_UNBOUNDED_PRECISION int prec_ourselves; #else # define prec_ourselves 0 #endif #if NEED_PRINTF_FLAG_LEFTADJUST # define pad_ourselves 1 #elif !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION int pad_ourselves; #else # define pad_ourselves 0 #endif TCHAR_T *fbp; unsigned int prefix_count; int prefixes[2] IF_LINT (= { 0 }); int orig_errno; #if !USE_SNPRINTF size_t tmp_length; TCHAR_T tmpbuf[700]; TCHAR_T *tmp; #endif #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION has_width = 0; #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION width = 0; if (dp->width_start != dp->width_end) { if (dp->width_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->width_arg_index].a.a_int; width = arg; if (arg < 0) { /* "A negative field width is taken as a '-' flag followed by a positive field width." */ flags |= FLAG_LEFT; width = -width; } } else { const FCHAR_T *digitp = dp->width_start; do width = xsum (xtimes (width, 10), *digitp++ - '0'); while (digitp != dp->width_end); } #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION has_width = 1; #endif } #endif #if !USE_SNPRINTF || !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF || NEED_PRINTF_UNBOUNDED_PRECISION has_precision = 0; precision = 6; if (dp->precision_start != dp->precision_end) { if (dp->precision_arg_index != ARG_NONE) { int arg; if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); arg = a.arg[dp->precision_arg_index].a.a_int; /* "A negative precision is taken as if the precision were omitted." */ if (arg >= 0) { precision = arg; has_precision = 1; } } else { const FCHAR_T *digitp = dp->precision_start + 1; precision = 0; while (digitp != dp->precision_end) precision = xsum (xtimes (precision, 10), *digitp++ - '0'); has_precision = 1; } } #endif /* Decide whether to handle the precision ourselves. */ #if NEED_PRINTF_UNBOUNDED_PRECISION switch (dp->conversion) { case 'd': case 'i': case 'u': case 'o': case 'x': case 'X': case 'p': prec_ourselves = has_precision && (precision > 0); break; default: prec_ourselves = 0; break; } #endif /* Decide whether to perform the padding ourselves. */ #if !NEED_PRINTF_FLAG_LEFTADJUST && (!DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION) switch (dp->conversion) { # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO /* If we need conversion from TCHAR_T[] to DCHAR_T[], we need to perform the padding after this conversion. Functions with unistdio extensions perform the padding based on character count rather than element count. */ case 'c': case 's': # endif # if NEED_PRINTF_FLAG_ZERO case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': # endif pad_ourselves = 1; break; default: pad_ourselves = prec_ourselves; break; } #endif #if !USE_SNPRINTF /* Allocate a temporary buffer of sufficient size for calling sprintf. */ tmp_length = MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type, flags, width, has_precision, precision, pad_ourselves); if (tmp_length <= sizeof (tmpbuf) / sizeof (TCHAR_T)) tmp = tmpbuf; else { size_t tmp_memsize = xtimes (tmp_length, sizeof (TCHAR_T)); if (size_overflow_p (tmp_memsize)) /* Overflow, would lead to out of memory. */ goto out_of_memory; tmp = (TCHAR_T *) malloc (tmp_memsize); if (tmp == NULL) /* Out of memory. */ goto out_of_memory; } #endif /* Construct the format string for calling snprintf or sprintf. */ fbp = buf; *fbp++ = '%'; #if NEED_PRINTF_FLAG_GROUPING /* The underlying implementation doesn't support the ' flag. Produce no grouping characters in this case; this is acceptable because the grouping is locale dependent. */ #else if (flags & FLAG_GROUP) *fbp++ = '\''; #endif if (flags & FLAG_LEFT) *fbp++ = '-'; if (flags & FLAG_SHOWSIGN) *fbp++ = '+'; if (flags & FLAG_SPACE) *fbp++ = ' '; if (flags & FLAG_ALT) *fbp++ = '#'; #if __GLIBC__ >= 2 && !defined __UCLIBC__ if (flags & FLAG_LOCALIZED) *fbp++ = 'I'; #endif if (!pad_ourselves) { if (flags & FLAG_ZERO) *fbp++ = '0'; if (dp->width_start != dp->width_end) { size_t n = dp->width_end - dp->width_start; /* The width specification is known to consist only of standard ASCII characters. */ if (sizeof (FCHAR_T) == sizeof (TCHAR_T)) { memcpy (fbp, dp->width_start, n * sizeof (TCHAR_T)); fbp += n; } else { const FCHAR_T *mp = dp->width_start; do *fbp++ = *mp++; while (--n > 0); } } } if (!prec_ourselves) { if (dp->precision_start != dp->precision_end) { size_t n = dp->precision_end - dp->precision_start; /* The precision specification is known to consist only of standard ASCII characters. */ if (sizeof (FCHAR_T) == sizeof (TCHAR_T)) { memcpy (fbp, dp->precision_start, n * sizeof (TCHAR_T)); fbp += n; } else { const FCHAR_T *mp = dp->precision_start; do *fbp++ = *mp++; while (--n > 0); } } } switch (type) { #if HAVE_LONG_LONG_INT case TYPE_LONGLONGINT: case TYPE_ULONGLONGINT: # if defined _WIN32 && ! defined __CYGWIN__ *fbp++ = 'I'; *fbp++ = '6'; *fbp++ = '4'; break; # else *fbp++ = 'l'; # endif #endif FALLTHROUGH; case TYPE_LONGINT: case TYPE_ULONGINT: #if HAVE_WINT_T case TYPE_WIDE_CHAR: #endif #if HAVE_WCHAR_T case TYPE_WIDE_STRING: #endif *fbp++ = 'l'; break; case TYPE_LONGDOUBLE: *fbp++ = 'L'; break; default: break; } #if NEED_PRINTF_DIRECTIVE_F if (dp->conversion == 'F') *fbp = 'f'; else #endif *fbp = dp->conversion; #if USE_SNPRINTF # if ! (((__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) \ && !defined __UCLIBC__) \ || (defined __APPLE__ && defined __MACH__) \ || (defined _WIN32 && ! defined __CYGWIN__)) fbp[1] = '%'; fbp[2] = 'n'; fbp[3] = '\0'; # else /* On glibc2 systems from glibc >= 2.3 - probably also older ones - we know that snprintf's return value conforms to ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and gl_SNPRINTF_TRUNCATION_C99 pass. Therefore we can avoid using %n in this situation. On glibc2 systems from 2004-10-18 or newer, the use of %n in format strings in writable memory may crash the program (if compiled with _FORTIFY_SOURCE=2), so we should avoid it in this situation. */ /* On Mac OS X 10.3 or newer, we know that snprintf's return value conforms to ISO C 99: the tests gl_SNPRINTF_RETVAL_C99 and gl_SNPRINTF_TRUNCATION_C99 pass. Therefore we can avoid using %n in this situation. On Mac OS X 10.13 or newer, the use of %n in format strings in writable memory by default crashes the program, so we should avoid it in this situation. */ /* On native Windows systems (such as mingw), we can avoid using %n because: - Although the gl_SNPRINTF_TRUNCATION_C99 test fails, snprintf does not write more than the specified number of bytes. (snprintf (buf, 3, "%d %d", 4567, 89) writes '4', '5', '6' into buf, not '4', '5', '\0'.) - Although the gl_SNPRINTF_RETVAL_C99 test fails, snprintf allows us to recognize the case of an insufficient buffer size: it returns -1 in this case. On native Windows systems (such as mingw) where the OS is Windows Vista, the use of %n in format strings by default crashes the program. See <https://gcc.gnu.org/ml/gcc/2007-06/msg00122.html> and <https://msdn.microsoft.com/en-us/library/ms175782.aspx> So we should avoid %n in this situation. */ fbp[1] = '\0'; # endif #else fbp[1] = '\0'; #endif /* Construct the arguments for calling snprintf or sprintf. */ prefix_count = 0; if (!pad_ourselves && dp->width_arg_index != ARG_NONE) { if (!(a.arg[dp->width_arg_index].type == TYPE_INT)) abort (); prefixes[prefix_count++] = a.arg[dp->width_arg_index].a.a_int; } if (!prec_ourselves && dp->precision_arg_index != ARG_NONE) { if (!(a.arg[dp->precision_arg_index].type == TYPE_INT)) abort (); prefixes[prefix_count++] = a.arg[dp->precision_arg_index].a.a_int; } #if USE_SNPRINTF /* The SNPRINTF result is appended after result[0..length]. The latter is an array of DCHAR_T; SNPRINTF appends an array of TCHAR_T to it. This is possible because sizeof (TCHAR_T) divides sizeof (DCHAR_T) and alignof (TCHAR_T) <= alignof (DCHAR_T). */ # define TCHARS_PER_DCHAR (sizeof (DCHAR_T) / sizeof (TCHAR_T)) /* Ensure that maxlen below will be >= 2. Needed on BeOS, where an snprintf() with maxlen==1 acts like sprintf(). */ ENSURE_ALLOCATION (xsum (length, (2 + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR)); /* Prepare checking whether snprintf returns the count via %n. */ *(TCHAR_T *) (result + length) = '\0'; #endif orig_errno = errno; for (;;) { int count = -1; #if USE_SNPRINTF int retcount = 0; size_t maxlen = allocated - length; /* SNPRINTF can fail if its second argument is > INT_MAX. */ if (maxlen > INT_MAX / TCHARS_PER_DCHAR) maxlen = INT_MAX / TCHARS_PER_DCHAR; maxlen = maxlen * TCHARS_PER_DCHAR; # define SNPRINTF_BUF(arg) \ switch (prefix_count) \ { \ case 0: \ retcount = SNPRINTF ((TCHAR_T *) (result + length), \ maxlen, buf, \ arg, &count); \ break; \ case 1: \ retcount = SNPRINTF ((TCHAR_T *) (result + length), \ maxlen, buf, \ prefixes[0], arg, &count); \ break; \ case 2: \ retcount = SNPRINTF ((TCHAR_T *) (result + length), \ maxlen, buf, \ prefixes[0], prefixes[1], arg, \ &count); \ break; \ default: \ abort (); \ } #else # define SNPRINTF_BUF(arg) \ switch (prefix_count) \ { \ case 0: \ count = sprintf (tmp, buf, arg); \ break; \ case 1: \ count = sprintf (tmp, buf, prefixes[0], arg); \ break; \ case 2: \ count = sprintf (tmp, buf, prefixes[0], prefixes[1],\ arg); \ break; \ default: \ abort (); \ } #endif errno = 0; switch (type) { case TYPE_SCHAR: { int arg = a.arg[dp->arg_index].a.a_schar; SNPRINTF_BUF (arg); } break; case TYPE_UCHAR: { unsigned int arg = a.arg[dp->arg_index].a.a_uchar; SNPRINTF_BUF (arg); } break; case TYPE_SHORT: { int arg = a.arg[dp->arg_index].a.a_short; SNPRINTF_BUF (arg); } break; case TYPE_USHORT: { unsigned int arg = a.arg[dp->arg_index].a.a_ushort; SNPRINTF_BUF (arg); } break; case TYPE_INT: { int arg = a.arg[dp->arg_index].a.a_int; SNPRINTF_BUF (arg); } break; case TYPE_UINT: { unsigned int arg = a.arg[dp->arg_index].a.a_uint; SNPRINTF_BUF (arg); } break; case TYPE_LONGINT: { long int arg = a.arg[dp->arg_index].a.a_longint; SNPRINTF_BUF (arg); } break; case TYPE_ULONGINT: { unsigned long int arg = a.arg[dp->arg_index].a.a_ulongint; SNPRINTF_BUF (arg); } break; #if HAVE_LONG_LONG_INT case TYPE_LONGLONGINT: { long long int arg = a.arg[dp->arg_index].a.a_longlongint; SNPRINTF_BUF (arg); } break; case TYPE_ULONGLONGINT: { unsigned long long int arg = a.arg[dp->arg_index].a.a_ulonglongint; SNPRINTF_BUF (arg); } break; #endif case TYPE_DOUBLE: { double arg = a.arg[dp->arg_index].a.a_double; SNPRINTF_BUF (arg); } break; case TYPE_LONGDOUBLE: { long double arg = a.arg[dp->arg_index].a.a_longdouble; SNPRINTF_BUF (arg); } break; case TYPE_CHAR: { int arg = a.arg[dp->arg_index].a.a_char; SNPRINTF_BUF (arg); } break; #if HAVE_WINT_T case TYPE_WIDE_CHAR: { wint_t arg = a.arg[dp->arg_index].a.a_wide_char; SNPRINTF_BUF (arg); } break; #endif case TYPE_STRING: { const char *arg = a.arg[dp->arg_index].a.a_string; SNPRINTF_BUF (arg); } break; #if HAVE_WCHAR_T case TYPE_WIDE_STRING: { const wchar_t *arg = a.arg[dp->arg_index].a.a_wide_string; SNPRINTF_BUF (arg); } break; #endif case TYPE_POINTER: { void *arg = a.arg[dp->arg_index].a.a_pointer; SNPRINTF_BUF (arg); } break; default: abort (); } #if USE_SNPRINTF /* Portability: Not all implementations of snprintf() are ISO C 99 compliant. Determine the number of bytes that snprintf() has produced or would have produced. */ if (count >= 0) { /* Verify that snprintf() has NUL-terminated its result. */ if (count < maxlen && ((TCHAR_T *) (result + length)) [count] != '\0') abort (); /* Portability hack. */ if (retcount > count) count = retcount; } else { /* snprintf() doesn't understand the '%n' directive. */ if (fbp[1] != '\0') { /* Don't use the '%n' directive; instead, look at the snprintf() return value. */ fbp[1] = '\0'; continue; } else { /* Look at the snprintf() return value. */ if (retcount < 0) { # if !HAVE_SNPRINTF_RETVAL_C99 || USE_MSVC__SNPRINTF /* HP-UX 10.20 snprintf() is doubly deficient: It doesn't understand the '%n' directive, *and* it returns -1 (rather than the length that would have been required) when the buffer is too small. But a failure at this point can also come from other reasons than a too small buffer, such as an invalid wide string argument to the %ls directive, or possibly an invalid floating-point argument. */ size_t tmp_length = MAX_ROOM_NEEDED (&a, dp->arg_index, dp->conversion, type, flags, width, has_precision, precision, pad_ourselves); if (maxlen < tmp_length) { /* Make more room. But try to do through this reallocation only once. */ size_t bigger_need = xsum (length, xsum (tmp_length, TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR); /* And always grow proportionally. (There may be several arguments, each needing a little more room than the previous one.) */ size_t bigger_need2 = xsum (xtimes (allocated, 2), 12); if (bigger_need < bigger_need2) bigger_need = bigger_need2; ENSURE_ALLOCATION (bigger_need); continue; } # endif } else count = retcount; } } #endif /* Attempt to handle failure. */ if (count < 0) { /* SNPRINTF or sprintf failed. Save and use the errno that it has set, if any. */ int saved_errno = errno; if (saved_errno == 0) { if (dp->conversion == 'c' || dp->conversion == 's') saved_errno = EILSEQ; else saved_errno = EINVAL; } if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } #if USE_SNPRINTF /* Handle overflow of the allocated buffer. If such an overflow occurs, a C99 compliant snprintf() returns a count >= maxlen. However, a non-compliant snprintf() function returns only count = maxlen - 1. To cover both cases, test whether count >= maxlen - 1. */ if ((unsigned int) count + 1 >= maxlen) { /* If maxlen already has attained its allowed maximum, allocating more memory will not increase maxlen. Instead of looping, bail out. */ if (maxlen == INT_MAX / TCHARS_PER_DCHAR) goto overflow; else { /* Need at least (count + 1) * sizeof (TCHAR_T) bytes. (The +1 is for the trailing NUL.) But ask for (count + 2) * sizeof (TCHAR_T) bytes, so that in the next round, we likely get maxlen > (unsigned int) count + 1 and so we don't get here again. And allocate proportionally, to avoid looping eternally if snprintf() reports a too small count. */ size_t n = xmax (xsum (length, ((unsigned int) count + 2 + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR), xtimes (allocated, 2)); ENSURE_ALLOCATION (n); continue; } } #endif #if NEED_PRINTF_UNBOUNDED_PRECISION if (prec_ourselves) { /* Handle the precision. */ TCHAR_T *prec_ptr = # if USE_SNPRINTF (TCHAR_T *) (result + length); # else tmp; # endif size_t prefix_count; size_t move; prefix_count = 0; /* Put the additional zeroes after the sign. */ if (count >= 1 && (*prec_ptr == '-' || *prec_ptr == '+' || *prec_ptr == ' ')) prefix_count = 1; /* Put the additional zeroes after the 0x prefix if (flags & FLAG_ALT) || (dp->conversion == 'p'). */ else if (count >= 2 && prec_ptr[0] == '0' && (prec_ptr[1] == 'x' || prec_ptr[1] == 'X')) prefix_count = 2; move = count - prefix_count; if (precision > move) { /* Insert zeroes. */ size_t insert = precision - move; TCHAR_T *prec_end; # if USE_SNPRINTF size_t n = xsum (length, (count + insert + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR); length += (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR; ENSURE_ALLOCATION (n); length -= (count + TCHARS_PER_DCHAR - 1) / TCHARS_PER_DCHAR; prec_ptr = (TCHAR_T *) (result + length); # endif prec_end = prec_ptr + count; prec_ptr += prefix_count; while (prec_end > prec_ptr) { prec_end--; prec_end[insert] = prec_end[0]; } prec_end += insert; do *--prec_end = '0'; while (prec_end > prec_ptr); count += insert; } } #endif #if !USE_SNPRINTF if (count >= tmp_length) /* tmp_length was incorrectly calculated - fix the code above! */ abort (); #endif #if !DCHAR_IS_TCHAR /* Convert from TCHAR_T[] to DCHAR_T[]. */ if (dp->conversion == 'c' || dp->conversion == 's') { /* type = TYPE_CHAR or TYPE_WIDE_CHAR or TYPE_STRING TYPE_WIDE_STRING. The result string is not certainly ASCII. */ const TCHAR_T *tmpsrc; DCHAR_T *tmpdst; size_t tmpdst_len; /* This code assumes that TCHAR_T is 'char'. */ verify (sizeof (TCHAR_T) == 1); # if USE_SNPRINTF tmpsrc = (TCHAR_T *) (result + length); # else tmpsrc = tmp; # endif tmpdst = DCHAR_CONV_FROM_ENCODING (locale_charset (), iconveh_question_mark, tmpsrc, count, NULL, NULL, &tmpdst_len); if (tmpdst == NULL) { int saved_errno = errno; if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = saved_errno; return NULL; } ENSURE_ALLOCATION (xsum (length, tmpdst_len)); DCHAR_CPY (result + length, tmpdst, tmpdst_len); free (tmpdst); count = tmpdst_len; } else { /* The result string is ASCII. Simple 1:1 conversion. */ # if USE_SNPRINTF /* If sizeof (DCHAR_T) == sizeof (TCHAR_T), it's a no-op conversion, in-place on the array starting at (result + length). */ if (sizeof (DCHAR_T) != sizeof (TCHAR_T)) # endif { const TCHAR_T *tmpsrc; DCHAR_T *tmpdst; size_t n; # if USE_SNPRINTF if (result == resultbuf) { tmpsrc = (TCHAR_T *) (result + length); /* ENSURE_ALLOCATION will not move tmpsrc (because it's part of resultbuf). */ ENSURE_ALLOCATION (xsum (length, count)); } else { /* ENSURE_ALLOCATION will move the array (because it uses realloc(). */ ENSURE_ALLOCATION (xsum (length, count)); tmpsrc = (TCHAR_T *) (result + length); } # else tmpsrc = tmp; ENSURE_ALLOCATION (xsum (length, count)); # endif tmpdst = result + length; /* Copy backwards, because of overlapping. */ tmpsrc += count; tmpdst += count; for (n = count; n > 0; n--) *--tmpdst = *--tmpsrc; } } #endif #if DCHAR_IS_TCHAR && !USE_SNPRINTF /* Make room for the result. */ if (count > allocated - length) { /* Need at least count elements. But allocate proportionally. */ size_t n = xmax (xsum (length, count), xtimes (allocated, 2)); ENSURE_ALLOCATION (n); } #endif /* Here count <= allocated - length. */ /* Perform padding. */ #if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO || NEED_PRINTF_FLAG_LEFTADJUST || NEED_PRINTF_FLAG_ZERO || NEED_PRINTF_UNBOUNDED_PRECISION if (pad_ourselves && has_width) { size_t w; # if ENABLE_UNISTDIO /* Outside POSIX, it's preferable to compare the width against the number of _characters_ of the converted value. */ w = DCHAR_MBSNLEN (result + length, count); # else /* The width is compared against the number of _bytes_ of the converted value, says POSIX. */ w = count; # endif if (w < width) { size_t pad = width - w; /* Make room for the result. */ if (xsum (count, pad) > allocated - length) { /* Need at least count + pad elements. But allocate proportionally. */ size_t n = xmax (xsum3 (length, count, pad), xtimes (allocated, 2)); # if USE_SNPRINTF length += count; ENSURE_ALLOCATION (n); length -= count; # else ENSURE_ALLOCATION (n); # endif } /* Here count + pad <= allocated - length. */ { # if !DCHAR_IS_TCHAR || USE_SNPRINTF DCHAR_T * const rp = result + length; # else DCHAR_T * const rp = tmp; # endif DCHAR_T *p = rp + count; DCHAR_T *end = p + pad; DCHAR_T *pad_ptr; # if !DCHAR_IS_TCHAR || ENABLE_UNISTDIO if (dp->conversion == 'c' || dp->conversion == 's') /* No zero-padding for string directives. */ pad_ptr = NULL; else # endif { pad_ptr = (*rp == '-' ? rp + 1 : rp); /* No zero-padding of "inf" and "nan". */ if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z') || (*pad_ptr >= 'a' && *pad_ptr <= 'z')) pad_ptr = NULL; } /* The generated string now extends from rp to p, with the zero padding insertion point being at pad_ptr. */ count = count + pad; /* = end - rp */ if (flags & FLAG_LEFT) { /* Pad with spaces on the right. */ for (; pad > 0; pad--) *p++ = ' '; } else if ((flags & FLAG_ZERO) && pad_ptr != NULL) { /* Pad with zeroes. */ DCHAR_T *q = end; while (p > pad_ptr) *--q = *--p; for (; pad > 0; pad--) *p++ = '0'; } else { /* Pad with spaces on the left. */ DCHAR_T *q = end; while (p > rp) *--q = *--p; for (; pad > 0; pad--) *p++ = ' '; } } } } #endif /* Here still count <= allocated - length. */ #if !DCHAR_IS_TCHAR || USE_SNPRINTF /* The snprintf() result did fit. */ #else /* Append the sprintf() result. */ memcpy (result + length, tmp, count * sizeof (DCHAR_T)); #endif #if !USE_SNPRINTF if (tmp != tmpbuf) free (tmp); #endif #if NEED_PRINTF_DIRECTIVE_F if (dp->conversion == 'F') { /* Convert the %f result to upper case for %F. */ DCHAR_T *rp = result + length; size_t rc; for (rc = count; rc > 0; rc--, rp++) if (*rp >= 'a' && *rp <= 'z') *rp = *rp - 'a' + 'A'; } #endif length += count; break; } errno = orig_errno; #undef pad_ourselves #undef prec_ourselves } } } /* Add the final NUL. */ ENSURE_ALLOCATION (xsum (length, 1)); result[length] = '\0'; if (result != resultbuf && length + 1 < allocated) { /* Shrink the allocated memory if possible. */ DCHAR_T *memory; memory = (DCHAR_T *) realloc (result, (length + 1) * sizeof (DCHAR_T)); if (memory != NULL) result = memory; } if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); *lengthp = length; /* Note that we can produce a big string of a length > INT_MAX. POSIX says that snprintf() fails with errno = EOVERFLOW in this case, but that's only because snprintf() returns an 'int'. This function does not have this limitation. */ return result; #if USE_SNPRINTF overflow: if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); CLEANUP (); errno = EOVERFLOW; return NULL; #endif out_of_memory: if (!(result == resultbuf || result == NULL)) free (result); if (buf_malloced != NULL) free (buf_malloced); out_of_memory_1: CLEANUP (); errno = ENOMEM; return NULL; } } #undef MAX_ROOM_NEEDED #undef TCHARS_PER_DCHAR #undef SNPRINTF #undef USE_SNPRINTF #undef DCHAR_SET #undef DCHAR_CPY #undef PRINTF_PARSE #undef DIRECTIVES #undef DIRECTIVE #undef DCHAR_IS_TCHAR #undef TCHAR_T #undef DCHAR_T #undef FCHAR_T #undef VASNPRINTF
./CrossVul/dataset_final_sorted/CWE-119/c/good_404_1
crossvul-cpp_data_bad_5493_2
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * The purpose of this test is to minimally exercise libcurl's internal * curl_m*printf formatting capabilities and handling of some data types. */ #include "test.h" #include "memdebug.h" #if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG) # define MPRNT_SUFFIX_CURL_OFF_T LL #else # define MPRNT_SUFFIX_CURL_OFF_T L #endif #ifdef CURL_ISOCPP # define MPRNT_OFF_T_C_HELPER2(Val,Suffix) Val ## Suffix #else # define MPRNT_OFF_T_C_HELPER2(Val,Suffix) Val/**/Suffix #endif #define MPRNT_OFF_T_C_HELPER1(Val,Suffix) MPRNT_OFF_T_C_HELPER2(Val,Suffix) #define MPRNT_OFF_T_C(Val) MPRNT_OFF_T_C_HELPER1(Val,MPRNT_SUFFIX_CURL_OFF_T) #define BUFSZ 256 #define USHORT_TESTS_ARRSZ 1 + 100 #define SSHORT_TESTS_ARRSZ 1 + 100 #define UINT_TESTS_ARRSZ 1 + 100 #define SINT_TESTS_ARRSZ 1 + 100 #define ULONG_TESTS_ARRSZ 1 + 100 #define SLONG_TESTS_ARRSZ 1 + 100 #define COFFT_TESTS_ARRSZ 1 + 100 struct unsshort_st { unsigned short num; /* unsigned short */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; struct sigshort_st { short num; /* signed short */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; struct unsint_st { unsigned int num; /* unsigned int */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; struct sigint_st { int num; /* signed int */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; struct unslong_st { unsigned long num; /* unsigned long */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; struct siglong_st { long num; /* signed long */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; struct curloff_st { curl_off_t num; /* curl_off_t */ const char *expected; /* expected string */ char result[BUFSZ]; /* result string */ }; static struct unsshort_st us_test[USHORT_TESTS_ARRSZ]; static struct sigshort_st ss_test[SSHORT_TESTS_ARRSZ]; static struct unsint_st ui_test[UINT_TESTS_ARRSZ]; static struct sigint_st si_test[SINT_TESTS_ARRSZ]; static struct unslong_st ul_test[ULONG_TESTS_ARRSZ]; static struct siglong_st sl_test[SLONG_TESTS_ARRSZ]; static struct curloff_st co_test[COFFT_TESTS_ARRSZ]; static int test_unsigned_short_formatting(void) { int i, j; int num_ushort_tests; int failed = 0; #if (SIZEOF_SHORT == 1) i=1; us_test[i].num = 0xFFU; us_test[i].expected = "256"; i++; us_test[i].num = 0xF0U; us_test[i].expected = "240"; i++; us_test[i].num = 0x0FU; us_test[i].expected = "15"; i++; us_test[i].num = 0xE0U; us_test[i].expected = "224"; i++; us_test[i].num = 0x0EU; us_test[i].expected = "14"; i++; us_test[i].num = 0xC0U; us_test[i].expected = "192"; i++; us_test[i].num = 0x0CU; us_test[i].expected = "12"; i++; us_test[i].num = 0x01U; us_test[i].expected = "1"; i++; us_test[i].num = 0x00U; us_test[i].expected = "0"; num_ushort_tests = i; #elif (SIZEOF_SHORT == 2) i=1; us_test[i].num = 0xFFFFU; us_test[i].expected = "65535"; i++; us_test[i].num = 0xFF00U; us_test[i].expected = "65280"; i++; us_test[i].num = 0x00FFU; us_test[i].expected = "255"; i++; us_test[i].num = 0xF000U; us_test[i].expected = "61440"; i++; us_test[i].num = 0x0F00U; us_test[i].expected = "3840"; i++; us_test[i].num = 0x00F0U; us_test[i].expected = "240"; i++; us_test[i].num = 0x000FU; us_test[i].expected = "15"; i++; us_test[i].num = 0xC000U; us_test[i].expected = "49152"; i++; us_test[i].num = 0x0C00U; us_test[i].expected = "3072"; i++; us_test[i].num = 0x00C0U; us_test[i].expected = "192"; i++; us_test[i].num = 0x000CU; us_test[i].expected = "12"; i++; us_test[i].num = 0x0001U; us_test[i].expected = "1"; i++; us_test[i].num = 0x0000U; us_test[i].expected = "0"; num_ushort_tests = i; #elif (SIZEOF_SHORT == 4) i=1; us_test[i].num = 0xFFFFFFFFU; us_test[i].expected = "4294967295"; i++; us_test[i].num = 0xFFFF0000U; us_test[i].expected = "4294901760"; i++; us_test[i].num = 0x0000FFFFU; us_test[i].expected = "65535"; i++; us_test[i].num = 0xFF000000U; us_test[i].expected = "4278190080"; i++; us_test[i].num = 0x00FF0000U; us_test[i].expected = "16711680"; i++; us_test[i].num = 0x0000FF00U; us_test[i].expected = "65280"; i++; us_test[i].num = 0x000000FFU; us_test[i].expected = "255"; i++; us_test[i].num = 0xF0000000U; us_test[i].expected = "4026531840"; i++; us_test[i].num = 0x0F000000U; us_test[i].expected = "251658240"; i++; us_test[i].num = 0x00F00000U; us_test[i].expected = "15728640"; i++; us_test[i].num = 0x000F0000U; us_test[i].expected = "983040"; i++; us_test[i].num = 0x0000F000U; us_test[i].expected = "61440"; i++; us_test[i].num = 0x00000F00U; us_test[i].expected = "3840"; i++; us_test[i].num = 0x000000F0U; us_test[i].expected = "240"; i++; us_test[i].num = 0x0000000FU; us_test[i].expected = "15"; i++; us_test[i].num = 0xC0000000U; us_test[i].expected = "3221225472"; i++; us_test[i].num = 0x0C000000U; us_test[i].expected = "201326592"; i++; us_test[i].num = 0x00C00000U; us_test[i].expected = "12582912"; i++; us_test[i].num = 0x000C0000U; us_test[i].expected = "786432"; i++; us_test[i].num = 0x0000C000U; us_test[i].expected = "49152"; i++; us_test[i].num = 0x00000C00U; us_test[i].expected = "3072"; i++; us_test[i].num = 0x000000C0U; us_test[i].expected = "192"; i++; us_test[i].num = 0x0000000CU; us_test[i].expected = "12"; i++; us_test[i].num = 0x00000001U; us_test[i].expected = "1"; i++; us_test[i].num = 0x00000000U; us_test[i].expected = "0"; num_ushort_tests = i; #endif for(i=1; i<=num_ushort_tests; i++) { for(j=0; j<BUFSZ; j++) us_test[i].result[j] = 'X'; us_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(us_test[i].result, "%hu", us_test[i].num); if(memcmp(us_test[i].result, us_test[i].expected, strlen(us_test[i].expected))) { printf("unsigned short test #%.2d: Failed (Expected: %s Got: %s)\n", i, us_test[i].expected, us_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() unsigned short tests OK!\n"); else printf("Some curl_mprintf() unsigned short tests Failed!\n"); return failed; } static int test_signed_short_formatting(void) { int i, j; int num_sshort_tests; int failed = 0; #if (SIZEOF_SHORT == 1) i=1; ss_test[i].num = 0x7F; ss_test[i].expected = "127"; i++; ss_test[i].num = 0x70; ss_test[i].expected = "112"; i++; ss_test[i].num = 0x07; ss_test[i].expected = "7"; i++; ss_test[i].num = 0x50; ss_test[i].expected = "80"; i++; ss_test[i].num = 0x05; ss_test[i].expected = "5"; i++; ss_test[i].num = 0x01; ss_test[i].expected = "1"; i++; ss_test[i].num = 0x00; ss_test[i].expected = "0"; i++; ss_test[i].num = -0x7F -1; ss_test[i].expected = "-128"; i++; ss_test[i].num = -0x70 -1; ss_test[i].expected = "-113"; i++; ss_test[i].num = -0x07 -1; ss_test[i].expected = "-8"; i++; ss_test[i].num = -0x50 -1; ss_test[i].expected = "-81"; i++; ss_test[i].num = -0x05 -1; ss_test[i].expected = "-6"; i++; ss_test[i].num = 0x00 -1; ss_test[i].expected = "-1"; num_sshort_tests = i; #elif (SIZEOF_SHORT == 2) i=1; ss_test[i].num = 0x7FFF; ss_test[i].expected = "32767"; i++; ss_test[i].num = 0x7FFE; ss_test[i].expected = "32766"; i++; ss_test[i].num = 0x7FFD; ss_test[i].expected = "32765"; i++; ss_test[i].num = 0x7F00; ss_test[i].expected = "32512"; i++; ss_test[i].num = 0x07F0; ss_test[i].expected = "2032"; i++; ss_test[i].num = 0x007F; ss_test[i].expected = "127"; i++; ss_test[i].num = 0x7000; ss_test[i].expected = "28672"; i++; ss_test[i].num = 0x0700; ss_test[i].expected = "1792"; i++; ss_test[i].num = 0x0070; ss_test[i].expected = "112"; i++; ss_test[i].num = 0x0007; ss_test[i].expected = "7"; i++; ss_test[i].num = 0x5000; ss_test[i].expected = "20480"; i++; ss_test[i].num = 0x0500; ss_test[i].expected = "1280"; i++; ss_test[i].num = 0x0050; ss_test[i].expected = "80"; i++; ss_test[i].num = 0x0005; ss_test[i].expected = "5"; i++; ss_test[i].num = 0x0001; ss_test[i].expected = "1"; i++; ss_test[i].num = 0x0000; ss_test[i].expected = "0"; i++; ss_test[i].num = -0x7FFF -1; ss_test[i].expected = "-32768"; i++; ss_test[i].num = -0x7FFE -1; ss_test[i].expected = "-32767"; i++; ss_test[i].num = -0x7FFD -1; ss_test[i].expected = "-32766"; i++; ss_test[i].num = -0x7F00 -1; ss_test[i].expected = "-32513"; i++; ss_test[i].num = -0x07F0 -1; ss_test[i].expected = "-2033"; i++; ss_test[i].num = -0x007F -1; ss_test[i].expected = "-128"; i++; ss_test[i].num = -0x7000 -1; ss_test[i].expected = "-28673"; i++; ss_test[i].num = -0x0700 -1; ss_test[i].expected = "-1793"; i++; ss_test[i].num = -0x0070 -1; ss_test[i].expected = "-113"; i++; ss_test[i].num = -0x0007 -1; ss_test[i].expected = "-8"; i++; ss_test[i].num = -0x5000 -1; ss_test[i].expected = "-20481"; i++; ss_test[i].num = -0x0500 -1; ss_test[i].expected = "-1281"; i++; ss_test[i].num = -0x0050 -1; ss_test[i].expected = "-81"; i++; ss_test[i].num = -0x0005 -1; ss_test[i].expected = "-6"; i++; ss_test[i].num = 0x0000 -1; ss_test[i].expected = "-1"; num_sshort_tests = i; #elif (SIZEOF_SHORT == 4) i=1; ss_test[i].num = 0x7FFFFFFF; ss_test[i].expected = "2147483647"; i++; ss_test[i].num = 0x7FFFFFFE; ss_test[i].expected = "2147483646"; i++; ss_test[i].num = 0x7FFFFFFD; ss_test[i].expected = "2147483645"; i++; ss_test[i].num = 0x7FFF0000; ss_test[i].expected = "2147418112"; i++; ss_test[i].num = 0x00007FFF; ss_test[i].expected = "32767"; i++; ss_test[i].num = 0x7F000000; ss_test[i].expected = "2130706432"; i++; ss_test[i].num = 0x007F0000; ss_test[i].expected = "8323072"; i++; ss_test[i].num = 0x00007F00; ss_test[i].expected = "32512"; i++; ss_test[i].num = 0x0000007F; ss_test[i].expected = "127"; i++; ss_test[i].num = 0x70000000; ss_test[i].expected = "1879048192"; i++; ss_test[i].num = 0x07000000; ss_test[i].expected = "117440512"; i++; ss_test[i].num = 0x00700000; ss_test[i].expected = "7340032"; i++; ss_test[i].num = 0x00070000; ss_test[i].expected = "458752"; i++; ss_test[i].num = 0x00007000; ss_test[i].expected = "28672"; i++; ss_test[i].num = 0x00000700; ss_test[i].expected = "1792"; i++; ss_test[i].num = 0x00000070; ss_test[i].expected = "112"; i++; ss_test[i].num = 0x00000007; ss_test[i].expected = "7"; i++; ss_test[i].num = 0x50000000; ss_test[i].expected = "1342177280"; i++; ss_test[i].num = 0x05000000; ss_test[i].expected = "83886080"; i++; ss_test[i].num = 0x00500000; ss_test[i].expected = "5242880"; i++; ss_test[i].num = 0x00050000; ss_test[i].expected = "327680"; i++; ss_test[i].num = 0x00005000; ss_test[i].expected = "20480"; i++; ss_test[i].num = 0x00000500; ss_test[i].expected = "1280"; i++; ss_test[i].num = 0x00000050; ss_test[i].expected = "80"; i++; ss_test[i].num = 0x00000005; ss_test[i].expected = "5"; i++; ss_test[i].num = 0x00000001; ss_test[i].expected = "1"; i++; ss_test[i].num = 0x00000000; ss_test[i].expected = "0"; i++; ss_test[i].num = -0x7FFFFFFF -1; ss_test[i].expected = "-2147483648"; i++; ss_test[i].num = -0x7FFFFFFE -1; ss_test[i].expected = "-2147483647"; i++; ss_test[i].num = -0x7FFFFFFD -1; ss_test[i].expected = "-2147483646"; i++; ss_test[i].num = -0x7FFF0000 -1; ss_test[i].expected = "-2147418113"; i++; ss_test[i].num = -0x00007FFF -1; ss_test[i].expected = "-32768"; i++; ss_test[i].num = -0x7F000000 -1; ss_test[i].expected = "-2130706433"; i++; ss_test[i].num = -0x007F0000 -1; ss_test[i].expected = "-8323073"; i++; ss_test[i].num = -0x00007F00 -1; ss_test[i].expected = "-32513"; i++; ss_test[i].num = -0x0000007F -1; ss_test[i].expected = "-128"; i++; ss_test[i].num = -0x70000000 -1; ss_test[i].expected = "-1879048193"; i++; ss_test[i].num = -0x07000000 -1; ss_test[i].expected = "-117440513"; i++; ss_test[i].num = -0x00700000 -1; ss_test[i].expected = "-7340033"; i++; ss_test[i].num = -0x00070000 -1; ss_test[i].expected = "-458753"; i++; ss_test[i].num = -0x00007000 -1; ss_test[i].expected = "-28673"; i++; ss_test[i].num = -0x00000700 -1; ss_test[i].expected = "-1793"; i++; ss_test[i].num = -0x00000070 -1; ss_test[i].expected = "-113"; i++; ss_test[i].num = -0x00000007 -1; ss_test[i].expected = "-8"; i++; ss_test[i].num = -0x50000000 -1; ss_test[i].expected = "-1342177281"; i++; ss_test[i].num = -0x05000000 -1; ss_test[i].expected = "-83886081"; i++; ss_test[i].num = -0x00500000 -1; ss_test[i].expected = "-5242881"; i++; ss_test[i].num = -0x00050000 -1; ss_test[i].expected = "-327681"; i++; ss_test[i].num = -0x00005000 -1; ss_test[i].expected = "-20481"; i++; ss_test[i].num = -0x00000500 -1; ss_test[i].expected = "-1281"; i++; ss_test[i].num = -0x00000050 -1; ss_test[i].expected = "-81"; i++; ss_test[i].num = -0x00000005 -1; ss_test[i].expected = "-6"; i++; ss_test[i].num = 0x00000000 -1; ss_test[i].expected = "-1"; num_sshort_tests = i; #endif for(i=1; i<=num_sshort_tests; i++) { for(j=0; j<BUFSZ; j++) ss_test[i].result[j] = 'X'; ss_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(ss_test[i].result, "%hd", ss_test[i].num); if(memcmp(ss_test[i].result, ss_test[i].expected, strlen(ss_test[i].expected))) { printf("signed short test #%.2d: Failed (Expected: %s Got: %s)\n", i, ss_test[i].expected, ss_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() signed short tests OK!\n"); else printf("Some curl_mprintf() signed short tests Failed!\n"); return failed; } static int test_unsigned_int_formatting(void) { int i, j; int num_uint_tests; int failed = 0; #if (SIZEOF_INT == 2) i=1; ui_test[i].num = 0xFFFFU; ui_test[i].expected = "65535"; i++; ui_test[i].num = 0xFF00U; ui_test[i].expected = "65280"; i++; ui_test[i].num = 0x00FFU; ui_test[i].expected = "255"; i++; ui_test[i].num = 0xF000U; ui_test[i].expected = "61440"; i++; ui_test[i].num = 0x0F00U; ui_test[i].expected = "3840"; i++; ui_test[i].num = 0x00F0U; ui_test[i].expected = "240"; i++; ui_test[i].num = 0x000FU; ui_test[i].expected = "15"; i++; ui_test[i].num = 0xC000U; ui_test[i].expected = "49152"; i++; ui_test[i].num = 0x0C00U; ui_test[i].expected = "3072"; i++; ui_test[i].num = 0x00C0U; ui_test[i].expected = "192"; i++; ui_test[i].num = 0x000CU; ui_test[i].expected = "12"; i++; ui_test[i].num = 0x0001U; ui_test[i].expected = "1"; i++; ui_test[i].num = 0x0000U; ui_test[i].expected = "0"; num_uint_tests = i; #elif (SIZEOF_INT == 4) i=1; ui_test[i].num = 0xFFFFFFFFU; ui_test[i].expected = "4294967295"; i++; ui_test[i].num = 0xFFFF0000U; ui_test[i].expected = "4294901760"; i++; ui_test[i].num = 0x0000FFFFU; ui_test[i].expected = "65535"; i++; ui_test[i].num = 0xFF000000U; ui_test[i].expected = "4278190080"; i++; ui_test[i].num = 0x00FF0000U; ui_test[i].expected = "16711680"; i++; ui_test[i].num = 0x0000FF00U; ui_test[i].expected = "65280"; i++; ui_test[i].num = 0x000000FFU; ui_test[i].expected = "255"; i++; ui_test[i].num = 0xF0000000U; ui_test[i].expected = "4026531840"; i++; ui_test[i].num = 0x0F000000U; ui_test[i].expected = "251658240"; i++; ui_test[i].num = 0x00F00000U; ui_test[i].expected = "15728640"; i++; ui_test[i].num = 0x000F0000U; ui_test[i].expected = "983040"; i++; ui_test[i].num = 0x0000F000U; ui_test[i].expected = "61440"; i++; ui_test[i].num = 0x00000F00U; ui_test[i].expected = "3840"; i++; ui_test[i].num = 0x000000F0U; ui_test[i].expected = "240"; i++; ui_test[i].num = 0x0000000FU; ui_test[i].expected = "15"; i++; ui_test[i].num = 0xC0000000U; ui_test[i].expected = "3221225472"; i++; ui_test[i].num = 0x0C000000U; ui_test[i].expected = "201326592"; i++; ui_test[i].num = 0x00C00000U; ui_test[i].expected = "12582912"; i++; ui_test[i].num = 0x000C0000U; ui_test[i].expected = "786432"; i++; ui_test[i].num = 0x0000C000U; ui_test[i].expected = "49152"; i++; ui_test[i].num = 0x00000C00U; ui_test[i].expected = "3072"; i++; ui_test[i].num = 0x000000C0U; ui_test[i].expected = "192"; i++; ui_test[i].num = 0x0000000CU; ui_test[i].expected = "12"; i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1"; i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0"; num_uint_tests = i; #elif (SIZEOF_INT == 8) /* !checksrc! disable LONGLINE all */ i=1; ui_test[i].num = 0xFFFFFFFFFFFFFFFFU; ui_test[i].expected = "18446744073709551615"; i++; ui_test[i].num = 0xFFFFFFFF00000000U; ui_test[i].expected = "18446744069414584320"; i++; ui_test[i].num = 0x00000000FFFFFFFFU; ui_test[i].expected = "4294967295"; i++; ui_test[i].num = 0xFFFF000000000000U; ui_test[i].expected = "18446462598732840960"; i++; ui_test[i].num = 0x0000FFFF00000000U; ui_test[i].expected = "281470681743360"; i++; ui_test[i].num = 0x00000000FFFF0000U; ui_test[i].expected = "4294901760"; i++; ui_test[i].num = 0x000000000000FFFFU; ui_test[i].expected = "65535"; i++; ui_test[i].num = 0xFF00000000000000U; ui_test[i].expected = "18374686479671623680"; i++; ui_test[i].num = 0x00FF000000000000U; ui_test[i].expected = "71776119061217280"; i++; ui_test[i].num = 0x0000FF0000000000U; ui_test[i].expected = "280375465082880"; i++; ui_test[i].num = 0x000000FF00000000U; ui_test[i].expected = "1095216660480"; i++; ui_test[i].num = 0x00000000FF000000U; ui_test[i].expected = "4278190080"; i++; ui_test[i].num = 0x0000000000FF0000U; ui_test[i].expected = "16711680"; i++; ui_test[i].num = 0x000000000000FF00U; ui_test[i].expected = "65280"; i++; ui_test[i].num = 0x00000000000000FFU; ui_test[i].expected = "255"; i++; ui_test[i].num = 0xF000000000000000U; ui_test[i].expected = "17293822569102704640"; i++; ui_test[i].num = 0x0F00000000000000U; ui_test[i].expected = "1080863910568919040"; i++; ui_test[i].num = 0x00F0000000000000U; ui_test[i].expected = "67553994410557440"; i++; ui_test[i].num = 0x000F000000000000U; ui_test[i].expected = "4222124650659840"; i++; ui_test[i].num = 0x0000F00000000000U; ui_test[i].expected = "263882790666240"; i++; ui_test[i].num = 0x00000F0000000000U; ui_test[i].expected = "16492674416640"; i++; ui_test[i].num = 0x000000F000000000U; ui_test[i].expected = "1030792151040"; i++; ui_test[i].num = 0x0000000F00000000U; ui_test[i].expected = "64424509440"; i++; ui_test[i].num = 0x00000000F0000000U; ui_test[i].expected = "4026531840"; i++; ui_test[i].num = 0x000000000F000000U; ui_test[i].expected = "251658240"; i++; ui_test[i].num = 0x0000000000F00000U; ui_test[i].expected = "15728640"; i++; ui_test[i].num = 0x00000000000F0000U; ui_test[i].expected = "983040"; i++; ui_test[i].num = 0x000000000000F000U; ui_test[i].expected = "61440"; i++; ui_test[i].num = 0x0000000000000F00U; ui_test[i].expected = "3840"; i++; ui_test[i].num = 0x00000000000000F0U; ui_test[i].expected = "240"; i++; ui_test[i].num = 0x000000000000000FU; ui_test[i].expected = "15"; i++; ui_test[i].num = 0xC000000000000000U; ui_test[i].expected = "13835058055282163712"; i++; ui_test[i].num = 0x0C00000000000000U; ui_test[i].expected = "864691128455135232"; i++; ui_test[i].num = 0x00C0000000000000U; ui_test[i].expected = "54043195528445952"; i++; ui_test[i].num = 0x000C000000000000U; ui_test[i].expected = "3377699720527872"; i++; ui_test[i].num = 0x0000C00000000000U; ui_test[i].expected = "211106232532992"; i++; ui_test[i].num = 0x00000C0000000000U; ui_test[i].expected = "13194139533312"; i++; ui_test[i].num = 0x000000C000000000U; ui_test[i].expected = "824633720832"; i++; ui_test[i].num = 0x0000000C00000000U; ui_test[i].expected = "51539607552"; i++; ui_test[i].num = 0x00000000C0000000U; ui_test[i].expected = "3221225472"; i++; ui_test[i].num = 0x000000000C000000U; ui_test[i].expected = "201326592"; i++; ui_test[i].num = 0x0000000000C00000U; ui_test[i].expected = "12582912"; i++; ui_test[i].num = 0x00000000000C0000U; ui_test[i].expected = "786432"; i++; ui_test[i].num = 0x000000000000C000U; ui_test[i].expected = "49152"; i++; ui_test[i].num = 0x0000000000000C00U; ui_test[i].expected = "3072"; i++; ui_test[i].num = 0x00000000000000C0U; ui_test[i].expected = "192"; i++; ui_test[i].num = 0x000000000000000CU; ui_test[i].expected = "12"; i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1"; i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0"; num_uint_tests = i; #endif for(i=1; i<=num_uint_tests; i++) { for(j=0; j<BUFSZ; j++) ui_test[i].result[j] = 'X'; ui_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(ui_test[i].result, "%u", ui_test[i].num); if(memcmp(ui_test[i].result, ui_test[i].expected, strlen(ui_test[i].expected))) { printf("unsigned int test #%.2d: Failed (Expected: %s Got: %s)\n", i, ui_test[i].expected, ui_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() unsigned int tests OK!\n"); else printf("Some curl_mprintf() unsigned int tests Failed!\n"); return failed; } static int test_signed_int_formatting(void) { int i, j; int num_sint_tests; int failed = 0; #if (SIZEOF_INT == 2) i=1; si_test[i].num = 0x7FFF; si_test[i].expected = "32767"; i++; si_test[i].num = 0x7FFE; si_test[i].expected = "32766"; i++; si_test[i].num = 0x7FFD; si_test[i].expected = "32765"; i++; si_test[i].num = 0x7F00; si_test[i].expected = "32512"; i++; si_test[i].num = 0x07F0; si_test[i].expected = "2032"; i++; si_test[i].num = 0x007F; si_test[i].expected = "127"; i++; si_test[i].num = 0x7000; si_test[i].expected = "28672"; i++; si_test[i].num = 0x0700; si_test[i].expected = "1792"; i++; si_test[i].num = 0x0070; si_test[i].expected = "112"; i++; si_test[i].num = 0x0007; si_test[i].expected = "7"; i++; si_test[i].num = 0x5000; si_test[i].expected = "20480"; i++; si_test[i].num = 0x0500; si_test[i].expected = "1280"; i++; si_test[i].num = 0x0050; si_test[i].expected = "80"; i++; si_test[i].num = 0x0005; si_test[i].expected = "5"; i++; si_test[i].num = 0x0001; si_test[i].expected = "1"; i++; si_test[i].num = 0x0000; si_test[i].expected = "0"; i++; si_test[i].num = -0x7FFF -1; si_test[i].expected = "-32768"; i++; si_test[i].num = -0x7FFE -1; si_test[i].expected = "-32767"; i++; si_test[i].num = -0x7FFD -1; si_test[i].expected = "-32766"; i++; si_test[i].num = -0x7F00 -1; si_test[i].expected = "-32513"; i++; si_test[i].num = -0x07F0 -1; si_test[i].expected = "-2033"; i++; si_test[i].num = -0x007F -1; si_test[i].expected = "-128"; i++; si_test[i].num = -0x7000 -1; si_test[i].expected = "-28673"; i++; si_test[i].num = -0x0700 -1; si_test[i].expected = "-1793"; i++; si_test[i].num = -0x0070 -1; si_test[i].expected = "-113"; i++; si_test[i].num = -0x0007 -1; si_test[i].expected = "-8"; i++; si_test[i].num = -0x5000 -1; si_test[i].expected = "-20481"; i++; si_test[i].num = -0x0500 -1; si_test[i].expected = "-1281"; i++; si_test[i].num = -0x0050 -1; si_test[i].expected = "-81"; i++; si_test[i].num = -0x0005 -1; si_test[i].expected = "-6"; i++; si_test[i].num = 0x0000 -1; si_test[i].expected = "-1"; num_sint_tests = i; #elif (SIZEOF_INT == 4) i=1; si_test[i].num = 0x7FFFFFFF; si_test[i].expected = "2147483647"; i++; si_test[i].num = 0x7FFFFFFE; si_test[i].expected = "2147483646"; i++; si_test[i].num = 0x7FFFFFFD; si_test[i].expected = "2147483645"; i++; si_test[i].num = 0x7FFF0000; si_test[i].expected = "2147418112"; i++; si_test[i].num = 0x00007FFF; si_test[i].expected = "32767"; i++; si_test[i].num = 0x7F000000; si_test[i].expected = "2130706432"; i++; si_test[i].num = 0x007F0000; si_test[i].expected = "8323072"; i++; si_test[i].num = 0x00007F00; si_test[i].expected = "32512"; i++; si_test[i].num = 0x0000007F; si_test[i].expected = "127"; i++; si_test[i].num = 0x70000000; si_test[i].expected = "1879048192"; i++; si_test[i].num = 0x07000000; si_test[i].expected = "117440512"; i++; si_test[i].num = 0x00700000; si_test[i].expected = "7340032"; i++; si_test[i].num = 0x00070000; si_test[i].expected = "458752"; i++; si_test[i].num = 0x00007000; si_test[i].expected = "28672"; i++; si_test[i].num = 0x00000700; si_test[i].expected = "1792"; i++; si_test[i].num = 0x00000070; si_test[i].expected = "112"; i++; si_test[i].num = 0x00000007; si_test[i].expected = "7"; i++; si_test[i].num = 0x50000000; si_test[i].expected = "1342177280"; i++; si_test[i].num = 0x05000000; si_test[i].expected = "83886080"; i++; si_test[i].num = 0x00500000; si_test[i].expected = "5242880"; i++; si_test[i].num = 0x00050000; si_test[i].expected = "327680"; i++; si_test[i].num = 0x00005000; si_test[i].expected = "20480"; i++; si_test[i].num = 0x00000500; si_test[i].expected = "1280"; i++; si_test[i].num = 0x00000050; si_test[i].expected = "80"; i++; si_test[i].num = 0x00000005; si_test[i].expected = "5"; i++; si_test[i].num = 0x00000001; si_test[i].expected = "1"; i++; si_test[i].num = 0x00000000; si_test[i].expected = "0"; i++; si_test[i].num = -0x7FFFFFFF -1; si_test[i].expected = "-2147483648"; i++; si_test[i].num = -0x7FFFFFFE -1; si_test[i].expected = "-2147483647"; i++; si_test[i].num = -0x7FFFFFFD -1; si_test[i].expected = "-2147483646"; i++; si_test[i].num = -0x7FFF0000 -1; si_test[i].expected = "-2147418113"; i++; si_test[i].num = -0x00007FFF -1; si_test[i].expected = "-32768"; i++; si_test[i].num = -0x7F000000 -1; si_test[i].expected = "-2130706433"; i++; si_test[i].num = -0x007F0000 -1; si_test[i].expected = "-8323073"; i++; si_test[i].num = -0x00007F00 -1; si_test[i].expected = "-32513"; i++; si_test[i].num = -0x0000007F -1; si_test[i].expected = "-128"; i++; si_test[i].num = -0x70000000 -1; si_test[i].expected = "-1879048193"; i++; si_test[i].num = -0x07000000 -1; si_test[i].expected = "-117440513"; i++; si_test[i].num = -0x00700000 -1; si_test[i].expected = "-7340033"; i++; si_test[i].num = -0x00070000 -1; si_test[i].expected = "-458753"; i++; si_test[i].num = -0x00007000 -1; si_test[i].expected = "-28673"; i++; si_test[i].num = -0x00000700 -1; si_test[i].expected = "-1793"; i++; si_test[i].num = -0x00000070 -1; si_test[i].expected = "-113"; i++; si_test[i].num = -0x00000007 -1; si_test[i].expected = "-8"; i++; si_test[i].num = -0x50000000 -1; si_test[i].expected = "-1342177281"; i++; si_test[i].num = -0x05000000 -1; si_test[i].expected = "-83886081"; i++; si_test[i].num = -0x00500000 -1; si_test[i].expected = "-5242881"; i++; si_test[i].num = -0x00050000 -1; si_test[i].expected = "-327681"; i++; si_test[i].num = -0x00005000 -1; si_test[i].expected = "-20481"; i++; si_test[i].num = -0x00000500 -1; si_test[i].expected = "-1281"; i++; si_test[i].num = -0x00000050 -1; si_test[i].expected = "-81"; i++; si_test[i].num = -0x00000005 -1; si_test[i].expected = "-6"; i++; si_test[i].num = 0x00000000 -1; si_test[i].expected = "-1"; num_sint_tests = i; #elif (SIZEOF_INT == 8) i=1; si_test[i].num = 0x7FFFFFFFFFFFFFFF; si_test[i].expected = "9223372036854775807"; i++; si_test[i].num = 0x7FFFFFFFFFFFFFFE; si_test[i].expected = "9223372036854775806"; i++; si_test[i].num = 0x7FFFFFFFFFFFFFFD; si_test[i].expected = "9223372036854775805"; i++; si_test[i].num = 0x7FFFFFFF00000000; si_test[i].expected = "9223372032559808512"; i++; si_test[i].num = 0x000000007FFFFFFF; si_test[i].expected = "2147483647"; i++; si_test[i].num = 0x7FFF000000000000; si_test[i].expected = "9223090561878065152"; i++; si_test[i].num = 0x00007FFF00000000; si_test[i].expected = "140733193388032"; i++; si_test[i].num = 0x000000007FFF0000; si_test[i].expected = "2147418112"; i++; si_test[i].num = 0x0000000000007FFF; si_test[i].expected = "32767"; i++; si_test[i].num = 0x7F00000000000000; si_test[i].expected = "9151314442816847872"; i++; si_test[i].num = 0x007F000000000000; si_test[i].expected = "35747322042253312"; i++; si_test[i].num = 0x00007F0000000000; si_test[i].expected = "139637976727552"; i++; si_test[i].num = 0x0000007F00000000; si_test[i].expected = "545460846592"; i++; si_test[i].num = 0x000000007F000000; si_test[i].expected = "2130706432"; i++; si_test[i].num = 0x00000000007F0000; si_test[i].expected = "8323072"; i++; si_test[i].num = 0x0000000000007F00; si_test[i].expected = "32512"; i++; si_test[i].num = 0x000000000000007F; si_test[i].expected = "127"; i++; si_test[i].num = 0x7000000000000000; si_test[i].expected = "8070450532247928832"; i++; si_test[i].num = 0x0700000000000000; si_test[i].expected = "504403158265495552"; i++; si_test[i].num = 0x0070000000000000; si_test[i].expected = "31525197391593472"; i++; si_test[i].num = 0x0007000000000000; si_test[i].expected = "1970324836974592"; i++; si_test[i].num = 0x0000700000000000; si_test[i].expected = "123145302310912"; i++; si_test[i].num = 0x0000070000000000; si_test[i].expected = "7696581394432"; i++; si_test[i].num = 0x0000007000000000; si_test[i].expected = "481036337152"; i++; si_test[i].num = 0x0000000700000000; si_test[i].expected = "30064771072"; i++; si_test[i].num = 0x0000000070000000; si_test[i].expected = "1879048192"; i++; si_test[i].num = 0x0000000007000000; si_test[i].expected = "117440512"; i++; si_test[i].num = 0x0000000000700000; si_test[i].expected = "7340032"; i++; si_test[i].num = 0x0000000000070000; si_test[i].expected = "458752"; i++; si_test[i].num = 0x0000000000007000; si_test[i].expected = "28672"; i++; si_test[i].num = 0x0000000000000700; si_test[i].expected = "1792"; i++; si_test[i].num = 0x0000000000000070; si_test[i].expected = "112"; i++; si_test[i].num = 0x0000000000000007; si_test[i].expected = "7"; i++; si_test[i].num = 0x0000000000000001; si_test[i].expected = "1"; i++; si_test[i].num = 0x0000000000000000; si_test[i].expected = "0"; i++; si_test[i].num = -0x7FFFFFFFFFFFFFFF -1; si_test[i].expected = "-9223372036854775808"; i++; si_test[i].num = -0x7FFFFFFFFFFFFFFE -1; si_test[i].expected = "-9223372036854775807"; i++; si_test[i].num = -0x7FFFFFFFFFFFFFFD -1; si_test[i].expected = "-9223372036854775806"; i++; si_test[i].num = -0x7FFFFFFF00000000 -1; si_test[i].expected = "-9223372032559808513"; i++; si_test[i].num = -0x000000007FFFFFFF -1; si_test[i].expected = "-2147483648"; i++; si_test[i].num = -0x7FFF000000000000 -1; si_test[i].expected = "-9223090561878065153"; i++; si_test[i].num = -0x00007FFF00000000 -1; si_test[i].expected = "-140733193388033"; i++; si_test[i].num = -0x000000007FFF0000 -1; si_test[i].expected = "-2147418113"; i++; si_test[i].num = -0x0000000000007FFF -1; si_test[i].expected = "-32768"; i++; si_test[i].num = -0x7F00000000000000 -1; si_test[i].expected = "-9151314442816847873"; i++; si_test[i].num = -0x007F000000000000 -1; si_test[i].expected = "-35747322042253313"; i++; si_test[i].num = -0x00007F0000000000 -1; si_test[i].expected = "-139637976727553"; i++; si_test[i].num = -0x0000007F00000000 -1; si_test[i].expected = "-545460846593"; i++; si_test[i].num = -0x000000007F000000 -1; si_test[i].expected = "-2130706433"; i++; si_test[i].num = -0x00000000007F0000 -1; si_test[i].expected = "-8323073"; i++; si_test[i].num = -0x0000000000007F00 -1; si_test[i].expected = "-32513"; i++; si_test[i].num = -0x000000000000007F -1; si_test[i].expected = "-128"; i++; si_test[i].num = -0x7000000000000000 -1; si_test[i].expected = "-8070450532247928833"; i++; si_test[i].num = -0x0700000000000000 -1; si_test[i].expected = "-504403158265495553"; i++; si_test[i].num = -0x0070000000000000 -1; si_test[i].expected = "-31525197391593473"; i++; si_test[i].num = -0x0007000000000000 -1; si_test[i].expected = "-1970324836974593"; i++; si_test[i].num = -0x0000700000000000 -1; si_test[i].expected = "-123145302310913"; i++; si_test[i].num = -0x0000070000000000 -1; si_test[i].expected = "-7696581394433"; i++; si_test[i].num = -0x0000007000000000 -1; si_test[i].expected = "-481036337153"; i++; si_test[i].num = -0x0000000700000000 -1; si_test[i].expected = "-30064771073"; i++; si_test[i].num = -0x0000000070000000 -1; si_test[i].expected = "-1879048193"; i++; si_test[i].num = -0x0000000007000000 -1; si_test[i].expected = "-117440513"; i++; si_test[i].num = -0x0000000000700000 -1; si_test[i].expected = "-7340033"; i++; si_test[i].num = -0x0000000000070000 -1; si_test[i].expected = "-458753"; i++; si_test[i].num = -0x0000000000007000 -1; si_test[i].expected = "-28673"; i++; si_test[i].num = -0x0000000000000700 -1; si_test[i].expected = "-1793"; i++; si_test[i].num = -0x0000000000000070 -1; si_test[i].expected = "-113"; i++; si_test[i].num = -0x0000000000000007 -1; si_test[i].expected = "-8"; i++; si_test[i].num = 0x0000000000000000 -1; si_test[i].expected = "-1"; num_sint_tests = i; #endif for(i=1; i<=num_sint_tests; i++) { for(j=0; j<BUFSZ; j++) si_test[i].result[j] = 'X'; si_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(si_test[i].result, "%d", si_test[i].num); if(memcmp(si_test[i].result, si_test[i].expected, strlen(si_test[i].expected))) { printf("signed int test #%.2d: Failed (Expected: %s Got: %s)\n", i, si_test[i].expected, si_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() signed int tests OK!\n"); else printf("Some curl_mprintf() signed int tests Failed!\n"); return failed; } static int test_unsigned_long_formatting(void) { int i, j; int num_ulong_tests; int failed = 0; #if (CURL_SIZEOF_LONG == 2) i=1; ul_test[i].num = 0xFFFFUL; ul_test[i].expected = "65535"; i++; ul_test[i].num = 0xFF00UL; ul_test[i].expected = "65280"; i++; ul_test[i].num = 0x00FFUL; ul_test[i].expected = "255"; i++; ul_test[i].num = 0xF000UL; ul_test[i].expected = "61440"; i++; ul_test[i].num = 0x0F00UL; ul_test[i].expected = "3840"; i++; ul_test[i].num = 0x00F0UL; ul_test[i].expected = "240"; i++; ul_test[i].num = 0x000FUL; ul_test[i].expected = "15"; i++; ul_test[i].num = 0xC000UL; ul_test[i].expected = "49152"; i++; ul_test[i].num = 0x0C00UL; ul_test[i].expected = "3072"; i++; ul_test[i].num = 0x00C0UL; ul_test[i].expected = "192"; i++; ul_test[i].num = 0x000CUL; ul_test[i].expected = "12"; i++; ul_test[i].num = 0x0001UL; ul_test[i].expected = "1"; i++; ul_test[i].num = 0x0000UL; ul_test[i].expected = "0"; num_ulong_tests = i; #elif (CURL_SIZEOF_LONG == 4) i=1; ul_test[i].num = 0xFFFFFFFFUL; ul_test[i].expected = "4294967295"; i++; ul_test[i].num = 0xFFFF0000UL; ul_test[i].expected = "4294901760"; i++; ul_test[i].num = 0x0000FFFFUL; ul_test[i].expected = "65535"; i++; ul_test[i].num = 0xFF000000UL; ul_test[i].expected = "4278190080"; i++; ul_test[i].num = 0x00FF0000UL; ul_test[i].expected = "16711680"; i++; ul_test[i].num = 0x0000FF00UL; ul_test[i].expected = "65280"; i++; ul_test[i].num = 0x000000FFUL; ul_test[i].expected = "255"; i++; ul_test[i].num = 0xF0000000UL; ul_test[i].expected = "4026531840"; i++; ul_test[i].num = 0x0F000000UL; ul_test[i].expected = "251658240"; i++; ul_test[i].num = 0x00F00000UL; ul_test[i].expected = "15728640"; i++; ul_test[i].num = 0x000F0000UL; ul_test[i].expected = "983040"; i++; ul_test[i].num = 0x0000F000UL; ul_test[i].expected = "61440"; i++; ul_test[i].num = 0x00000F00UL; ul_test[i].expected = "3840"; i++; ul_test[i].num = 0x000000F0UL; ul_test[i].expected = "240"; i++; ul_test[i].num = 0x0000000FUL; ul_test[i].expected = "15"; i++; ul_test[i].num = 0xC0000000UL; ul_test[i].expected = "3221225472"; i++; ul_test[i].num = 0x0C000000UL; ul_test[i].expected = "201326592"; i++; ul_test[i].num = 0x00C00000UL; ul_test[i].expected = "12582912"; i++; ul_test[i].num = 0x000C0000UL; ul_test[i].expected = "786432"; i++; ul_test[i].num = 0x0000C000UL; ul_test[i].expected = "49152"; i++; ul_test[i].num = 0x00000C00UL; ul_test[i].expected = "3072"; i++; ul_test[i].num = 0x000000C0UL; ul_test[i].expected = "192"; i++; ul_test[i].num = 0x0000000CUL; ul_test[i].expected = "12"; i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1"; i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0"; num_ulong_tests = i; #elif (CURL_SIZEOF_LONG == 8) i=1; ul_test[i].num = 0xFFFFFFFFFFFFFFFFUL; ul_test[i].expected = "18446744073709551615"; i++; ul_test[i].num = 0xFFFFFFFF00000000UL; ul_test[i].expected = "18446744069414584320"; i++; ul_test[i].num = 0x00000000FFFFFFFFUL; ul_test[i].expected = "4294967295"; i++; ul_test[i].num = 0xFFFF000000000000UL; ul_test[i].expected = "18446462598732840960"; i++; ul_test[i].num = 0x0000FFFF00000000UL; ul_test[i].expected = "281470681743360"; i++; ul_test[i].num = 0x00000000FFFF0000UL; ul_test[i].expected = "4294901760"; i++; ul_test[i].num = 0x000000000000FFFFUL; ul_test[i].expected = "65535"; i++; ul_test[i].num = 0xFF00000000000000UL; ul_test[i].expected = "18374686479671623680"; i++; ul_test[i].num = 0x00FF000000000000UL; ul_test[i].expected = "71776119061217280"; i++; ul_test[i].num = 0x0000FF0000000000UL; ul_test[i].expected = "280375465082880"; i++; ul_test[i].num = 0x000000FF00000000UL; ul_test[i].expected = "1095216660480"; i++; ul_test[i].num = 0x00000000FF000000UL; ul_test[i].expected = "4278190080"; i++; ul_test[i].num = 0x0000000000FF0000UL; ul_test[i].expected = "16711680"; i++; ul_test[i].num = 0x000000000000FF00UL; ul_test[i].expected = "65280"; i++; ul_test[i].num = 0x00000000000000FFUL; ul_test[i].expected = "255"; i++; ul_test[i].num = 0xF000000000000000UL; ul_test[i].expected = "17293822569102704640"; i++; ul_test[i].num = 0x0F00000000000000UL; ul_test[i].expected = "1080863910568919040"; i++; ul_test[i].num = 0x00F0000000000000UL; ul_test[i].expected = "67553994410557440"; i++; ul_test[i].num = 0x000F000000000000UL; ul_test[i].expected = "4222124650659840"; i++; ul_test[i].num = 0x0000F00000000000UL; ul_test[i].expected = "263882790666240"; i++; ul_test[i].num = 0x00000F0000000000UL; ul_test[i].expected = "16492674416640"; i++; ul_test[i].num = 0x000000F000000000UL; ul_test[i].expected = "1030792151040"; i++; ul_test[i].num = 0x0000000F00000000UL; ul_test[i].expected = "64424509440"; i++; ul_test[i].num = 0x00000000F0000000UL; ul_test[i].expected = "4026531840"; i++; ul_test[i].num = 0x000000000F000000UL; ul_test[i].expected = "251658240"; i++; ul_test[i].num = 0x0000000000F00000UL; ul_test[i].expected = "15728640"; i++; ul_test[i].num = 0x00000000000F0000UL; ul_test[i].expected = "983040"; i++; ul_test[i].num = 0x000000000000F000UL; ul_test[i].expected = "61440"; i++; ul_test[i].num = 0x0000000000000F00UL; ul_test[i].expected = "3840"; i++; ul_test[i].num = 0x00000000000000F0UL; ul_test[i].expected = "240"; i++; ul_test[i].num = 0x000000000000000FUL; ul_test[i].expected = "15"; i++; ul_test[i].num = 0xC000000000000000UL; ul_test[i].expected = "13835058055282163712"; i++; ul_test[i].num = 0x0C00000000000000UL; ul_test[i].expected = "864691128455135232"; i++; ul_test[i].num = 0x00C0000000000000UL; ul_test[i].expected = "54043195528445952"; i++; ul_test[i].num = 0x000C000000000000UL; ul_test[i].expected = "3377699720527872"; i++; ul_test[i].num = 0x0000C00000000000UL; ul_test[i].expected = "211106232532992"; i++; ul_test[i].num = 0x00000C0000000000UL; ul_test[i].expected = "13194139533312"; i++; ul_test[i].num = 0x000000C000000000UL; ul_test[i].expected = "824633720832"; i++; ul_test[i].num = 0x0000000C00000000UL; ul_test[i].expected = "51539607552"; i++; ul_test[i].num = 0x00000000C0000000UL; ul_test[i].expected = "3221225472"; i++; ul_test[i].num = 0x000000000C000000UL; ul_test[i].expected = "201326592"; i++; ul_test[i].num = 0x0000000000C00000UL; ul_test[i].expected = "12582912"; i++; ul_test[i].num = 0x00000000000C0000UL; ul_test[i].expected = "786432"; i++; ul_test[i].num = 0x000000000000C000UL; ul_test[i].expected = "49152"; i++; ul_test[i].num = 0x0000000000000C00UL; ul_test[i].expected = "3072"; i++; ul_test[i].num = 0x00000000000000C0UL; ul_test[i].expected = "192"; i++; ul_test[i].num = 0x000000000000000CUL; ul_test[i].expected = "12"; i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1"; i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0"; num_ulong_tests = i; #endif for(i=1; i<=num_ulong_tests; i++) { for(j=0; j<BUFSZ; j++) ul_test[i].result[j] = 'X'; ul_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(ul_test[i].result, "%lu", ul_test[i].num); if(memcmp(ul_test[i].result, ul_test[i].expected, strlen(ul_test[i].expected))) { printf("unsigned long test #%.2d: Failed (Expected: %s Got: %s)\n", i, ul_test[i].expected, ul_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() unsigned long tests OK!\n"); else printf("Some curl_mprintf() unsigned long tests Failed!\n"); return failed; } static int test_signed_long_formatting(void) { int i, j; int num_slong_tests; int failed = 0; #if (CURL_SIZEOF_LONG == 2) i=1; sl_test[i].num = 0x7FFFL; sl_test[i].expected = "32767"; i++; sl_test[i].num = 0x7FFEL; sl_test[i].expected = "32766"; i++; sl_test[i].num = 0x7FFDL; sl_test[i].expected = "32765"; i++; sl_test[i].num = 0x7F00L; sl_test[i].expected = "32512"; i++; sl_test[i].num = 0x07F0L; sl_test[i].expected = "2032"; i++; sl_test[i].num = 0x007FL; sl_test[i].expected = "127"; i++; sl_test[i].num = 0x7000L; sl_test[i].expected = "28672"; i++; sl_test[i].num = 0x0700L; sl_test[i].expected = "1792"; i++; sl_test[i].num = 0x0070L; sl_test[i].expected = "112"; i++; sl_test[i].num = 0x0007L; sl_test[i].expected = "7"; i++; sl_test[i].num = 0x5000L; sl_test[i].expected = "20480"; i++; sl_test[i].num = 0x0500L; sl_test[i].expected = "1280"; i++; sl_test[i].num = 0x0050L; sl_test[i].expected = "80"; i++; sl_test[i].num = 0x0005L; sl_test[i].expected = "5"; i++; sl_test[i].num = 0x0001L; sl_test[i].expected = "1"; i++; sl_test[i].num = 0x0000L; sl_test[i].expected = "0"; i++; sl_test[i].num = -0x7FFFL -1L; sl_test[i].expected = "-32768"; i++; sl_test[i].num = -0x7FFEL -1L; sl_test[i].expected = "-32767"; i++; sl_test[i].num = -0x7FFDL -1L; sl_test[i].expected = "-32766"; i++; sl_test[i].num = -0x7F00L -1L; sl_test[i].expected = "-32513"; i++; sl_test[i].num = -0x07F0L -1L; sl_test[i].expected = "-2033"; i++; sl_test[i].num = -0x007FL -1L; sl_test[i].expected = "-128"; i++; sl_test[i].num = -0x7000L -1L; sl_test[i].expected = "-28673"; i++; sl_test[i].num = -0x0700L -1L; sl_test[i].expected = "-1793"; i++; sl_test[i].num = -0x0070L -1L; sl_test[i].expected = "-113"; i++; sl_test[i].num = -0x0007L -1L; sl_test[i].expected = "-8"; i++; sl_test[i].num = -0x5000L -1L; sl_test[i].expected = "-20481"; i++; sl_test[i].num = -0x0500L -1L; sl_test[i].expected = "-1281"; i++; sl_test[i].num = -0x0050L -1L; sl_test[i].expected = "-81"; i++; sl_test[i].num = -0x0005L -1L; sl_test[i].expected = "-6"; i++; sl_test[i].num = 0x0000L -1L; sl_test[i].expected = "-1"; num_slong_tests = i; #elif (CURL_SIZEOF_LONG == 4) i=1; sl_test[i].num = 0x7FFFFFFFL; sl_test[i].expected = "2147483647"; i++; sl_test[i].num = 0x7FFFFFFEL; sl_test[i].expected = "2147483646"; i++; sl_test[i].num = 0x7FFFFFFDL; sl_test[i].expected = "2147483645"; i++; sl_test[i].num = 0x7FFF0000L; sl_test[i].expected = "2147418112"; i++; sl_test[i].num = 0x00007FFFL; sl_test[i].expected = "32767"; i++; sl_test[i].num = 0x7F000000L; sl_test[i].expected = "2130706432"; i++; sl_test[i].num = 0x007F0000L; sl_test[i].expected = "8323072"; i++; sl_test[i].num = 0x00007F00L; sl_test[i].expected = "32512"; i++; sl_test[i].num = 0x0000007FL; sl_test[i].expected = "127"; i++; sl_test[i].num = 0x70000000L; sl_test[i].expected = "1879048192"; i++; sl_test[i].num = 0x07000000L; sl_test[i].expected = "117440512"; i++; sl_test[i].num = 0x00700000L; sl_test[i].expected = "7340032"; i++; sl_test[i].num = 0x00070000L; sl_test[i].expected = "458752"; i++; sl_test[i].num = 0x00007000L; sl_test[i].expected = "28672"; i++; sl_test[i].num = 0x00000700L; sl_test[i].expected = "1792"; i++; sl_test[i].num = 0x00000070L; sl_test[i].expected = "112"; i++; sl_test[i].num = 0x00000007L; sl_test[i].expected = "7"; i++; sl_test[i].num = 0x50000000L; sl_test[i].expected = "1342177280"; i++; sl_test[i].num = 0x05000000L; sl_test[i].expected = "83886080"; i++; sl_test[i].num = 0x00500000L; sl_test[i].expected = "5242880"; i++; sl_test[i].num = 0x00050000L; sl_test[i].expected = "327680"; i++; sl_test[i].num = 0x00005000L; sl_test[i].expected = "20480"; i++; sl_test[i].num = 0x00000500L; sl_test[i].expected = "1280"; i++; sl_test[i].num = 0x00000050L; sl_test[i].expected = "80"; i++; sl_test[i].num = 0x00000005L; sl_test[i].expected = "5"; i++; sl_test[i].num = 0x00000001L; sl_test[i].expected = "1"; i++; sl_test[i].num = 0x00000000L; sl_test[i].expected = "0"; i++; sl_test[i].num = -0x7FFFFFFFL -1L; sl_test[i].expected = "-2147483648"; i++; sl_test[i].num = -0x7FFFFFFEL -1L; sl_test[i].expected = "-2147483647"; i++; sl_test[i].num = -0x7FFFFFFDL -1L; sl_test[i].expected = "-2147483646"; i++; sl_test[i].num = -0x7FFF0000L -1L; sl_test[i].expected = "-2147418113"; i++; sl_test[i].num = -0x00007FFFL -1L; sl_test[i].expected = "-32768"; i++; sl_test[i].num = -0x7F000000L -1L; sl_test[i].expected = "-2130706433"; i++; sl_test[i].num = -0x007F0000L -1L; sl_test[i].expected = "-8323073"; i++; sl_test[i].num = -0x00007F00L -1L; sl_test[i].expected = "-32513"; i++; sl_test[i].num = -0x0000007FL -1L; sl_test[i].expected = "-128"; i++; sl_test[i].num = -0x70000000L -1L; sl_test[i].expected = "-1879048193"; i++; sl_test[i].num = -0x07000000L -1L; sl_test[i].expected = "-117440513"; i++; sl_test[i].num = -0x00700000L -1L; sl_test[i].expected = "-7340033"; i++; sl_test[i].num = -0x00070000L -1L; sl_test[i].expected = "-458753"; i++; sl_test[i].num = -0x00007000L -1L; sl_test[i].expected = "-28673"; i++; sl_test[i].num = -0x00000700L -1L; sl_test[i].expected = "-1793"; i++; sl_test[i].num = -0x00000070L -1L; sl_test[i].expected = "-113"; i++; sl_test[i].num = -0x00000007L -1L; sl_test[i].expected = "-8"; i++; sl_test[i].num = -0x50000000L -1L; sl_test[i].expected = "-1342177281"; i++; sl_test[i].num = -0x05000000L -1L; sl_test[i].expected = "-83886081"; i++; sl_test[i].num = -0x00500000L -1L; sl_test[i].expected = "-5242881"; i++; sl_test[i].num = -0x00050000L -1L; sl_test[i].expected = "-327681"; i++; sl_test[i].num = -0x00005000L -1L; sl_test[i].expected = "-20481"; i++; sl_test[i].num = -0x00000500L -1L; sl_test[i].expected = "-1281"; i++; sl_test[i].num = -0x00000050L -1L; sl_test[i].expected = "-81"; i++; sl_test[i].num = -0x00000005L -1L; sl_test[i].expected = "-6"; i++; sl_test[i].num = 0x00000000L -1L; sl_test[i].expected = "-1"; num_slong_tests = i; #elif (CURL_SIZEOF_LONG == 8) i=1; sl_test[i].num = 0x7FFFFFFFFFFFFFFFL; sl_test[i].expected = "9223372036854775807"; i++; sl_test[i].num = 0x7FFFFFFFFFFFFFFEL; sl_test[i].expected = "9223372036854775806"; i++; sl_test[i].num = 0x7FFFFFFFFFFFFFFDL; sl_test[i].expected = "9223372036854775805"; i++; sl_test[i].num = 0x7FFFFFFF00000000L; sl_test[i].expected = "9223372032559808512"; i++; sl_test[i].num = 0x000000007FFFFFFFL; sl_test[i].expected = "2147483647"; i++; sl_test[i].num = 0x7FFF000000000000L; sl_test[i].expected = "9223090561878065152"; i++; sl_test[i].num = 0x00007FFF00000000L; sl_test[i].expected = "140733193388032"; i++; sl_test[i].num = 0x000000007FFF0000L; sl_test[i].expected = "2147418112"; i++; sl_test[i].num = 0x0000000000007FFFL; sl_test[i].expected = "32767"; i++; sl_test[i].num = 0x7F00000000000000L; sl_test[i].expected = "9151314442816847872"; i++; sl_test[i].num = 0x007F000000000000L; sl_test[i].expected = "35747322042253312"; i++; sl_test[i].num = 0x00007F0000000000L; sl_test[i].expected = "139637976727552"; i++; sl_test[i].num = 0x0000007F00000000L; sl_test[i].expected = "545460846592"; i++; sl_test[i].num = 0x000000007F000000L; sl_test[i].expected = "2130706432"; i++; sl_test[i].num = 0x00000000007F0000L; sl_test[i].expected = "8323072"; i++; sl_test[i].num = 0x0000000000007F00L; sl_test[i].expected = "32512"; i++; sl_test[i].num = 0x000000000000007FL; sl_test[i].expected = "127"; i++; sl_test[i].num = 0x7000000000000000L; sl_test[i].expected = "8070450532247928832"; i++; sl_test[i].num = 0x0700000000000000L; sl_test[i].expected = "504403158265495552"; i++; sl_test[i].num = 0x0070000000000000L; sl_test[i].expected = "31525197391593472"; i++; sl_test[i].num = 0x0007000000000000L; sl_test[i].expected = "1970324836974592"; i++; sl_test[i].num = 0x0000700000000000L; sl_test[i].expected = "123145302310912"; i++; sl_test[i].num = 0x0000070000000000L; sl_test[i].expected = "7696581394432"; i++; sl_test[i].num = 0x0000007000000000L; sl_test[i].expected = "481036337152"; i++; sl_test[i].num = 0x0000000700000000L; sl_test[i].expected = "30064771072"; i++; sl_test[i].num = 0x0000000070000000L; sl_test[i].expected = "1879048192"; i++; sl_test[i].num = 0x0000000007000000L; sl_test[i].expected = "117440512"; i++; sl_test[i].num = 0x0000000000700000L; sl_test[i].expected = "7340032"; i++; sl_test[i].num = 0x0000000000070000L; sl_test[i].expected = "458752"; i++; sl_test[i].num = 0x0000000000007000L; sl_test[i].expected = "28672"; i++; sl_test[i].num = 0x0000000000000700L; sl_test[i].expected = "1792"; i++; sl_test[i].num = 0x0000000000000070L; sl_test[i].expected = "112"; i++; sl_test[i].num = 0x0000000000000007L; sl_test[i].expected = "7"; i++; sl_test[i].num = 0x0000000000000001L; sl_test[i].expected = "1"; i++; sl_test[i].num = 0x0000000000000000L; sl_test[i].expected = "0"; i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFFL -1L; sl_test[i].expected = "-9223372036854775808"; i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFEL -1L; sl_test[i].expected = "-9223372036854775807"; i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFDL -1L; sl_test[i].expected = "-9223372036854775806"; i++; sl_test[i].num = -0x7FFFFFFF00000000L -1L; sl_test[i].expected = "-9223372032559808513"; i++; sl_test[i].num = -0x000000007FFFFFFFL -1L; sl_test[i].expected = "-2147483648"; i++; sl_test[i].num = -0x7FFF000000000000L -1L; sl_test[i].expected = "-9223090561878065153"; i++; sl_test[i].num = -0x00007FFF00000000L -1L; sl_test[i].expected = "-140733193388033"; i++; sl_test[i].num = -0x000000007FFF0000L -1L; sl_test[i].expected = "-2147418113"; i++; sl_test[i].num = -0x0000000000007FFFL -1L; sl_test[i].expected = "-32768"; i++; sl_test[i].num = -0x7F00000000000000L -1L; sl_test[i].expected = "-9151314442816847873"; i++; sl_test[i].num = -0x007F000000000000L -1L; sl_test[i].expected = "-35747322042253313"; i++; sl_test[i].num = -0x00007F0000000000L -1L; sl_test[i].expected = "-139637976727553"; i++; sl_test[i].num = -0x0000007F00000000L -1L; sl_test[i].expected = "-545460846593"; i++; sl_test[i].num = -0x000000007F000000L -1L; sl_test[i].expected = "-2130706433"; i++; sl_test[i].num = -0x00000000007F0000L -1L; sl_test[i].expected = "-8323073"; i++; sl_test[i].num = -0x0000000000007F00L -1L; sl_test[i].expected = "-32513"; i++; sl_test[i].num = -0x000000000000007FL -1L; sl_test[i].expected = "-128"; i++; sl_test[i].num = -0x7000000000000000L -1L; sl_test[i].expected = "-8070450532247928833"; i++; sl_test[i].num = -0x0700000000000000L -1L; sl_test[i].expected = "-504403158265495553"; i++; sl_test[i].num = -0x0070000000000000L -1L; sl_test[i].expected = "-31525197391593473"; i++; sl_test[i].num = -0x0007000000000000L -1L; sl_test[i].expected = "-1970324836974593"; i++; sl_test[i].num = -0x0000700000000000L -1L; sl_test[i].expected = "-123145302310913"; i++; sl_test[i].num = -0x0000070000000000L -1L; sl_test[i].expected = "-7696581394433"; i++; sl_test[i].num = -0x0000007000000000L -1L; sl_test[i].expected = "-481036337153"; i++; sl_test[i].num = -0x0000000700000000L -1L; sl_test[i].expected = "-30064771073"; i++; sl_test[i].num = -0x0000000070000000L -1L; sl_test[i].expected = "-1879048193"; i++; sl_test[i].num = -0x0000000007000000L -1L; sl_test[i].expected = "-117440513"; i++; sl_test[i].num = -0x0000000000700000L -1L; sl_test[i].expected = "-7340033"; i++; sl_test[i].num = -0x0000000000070000L -1L; sl_test[i].expected = "-458753"; i++; sl_test[i].num = -0x0000000000007000L -1L; sl_test[i].expected = "-28673"; i++; sl_test[i].num = -0x0000000000000700L -1L; sl_test[i].expected = "-1793"; i++; sl_test[i].num = -0x0000000000000070L -1L; sl_test[i].expected = "-113"; i++; sl_test[i].num = -0x0000000000000007L -1L; sl_test[i].expected = "-8"; i++; sl_test[i].num = 0x0000000000000000L -1L; sl_test[i].expected = "-1"; num_slong_tests = i; #endif for(i=1; i<=num_slong_tests; i++) { for(j=0; j<BUFSZ; j++) sl_test[i].result[j] = 'X'; sl_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(sl_test[i].result, "%ld", sl_test[i].num); if(memcmp(sl_test[i].result, sl_test[i].expected, strlen(sl_test[i].expected))) { printf("signed long test #%.2d: Failed (Expected: %s Got: %s)\n", i, sl_test[i].expected, sl_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() signed long tests OK!\n"); else printf("Some curl_mprintf() signed long tests Failed!\n"); return failed; } static int test_curl_off_t_formatting(void) { int i, j; int num_cofft_tests; int failed = 0; #if (CURL_SIZEOF_CURL_OFF_T == 2) i=1; co_test[i].num = MPRNT_OFF_T_C(0x7FFF); co_test[i].expected = "32767"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFE); co_test[i].expected = "32766"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFD); co_test[i].expected = "32765"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7F00); co_test[i].expected = "32512"; i++; co_test[i].num = MPRNT_OFF_T_C(0x07F0); co_test[i].expected = "2032"; i++; co_test[i].num = MPRNT_OFF_T_C(0x007F); co_test[i].expected = "127"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7000); co_test[i].expected = "28672"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0700); co_test[i].expected = "1792"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0070); co_test[i].expected = "112"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0007); co_test[i].expected = "7"; i++; co_test[i].num = MPRNT_OFF_T_C(0x5000); co_test[i].expected = "20480"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0500); co_test[i].expected = "1280"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0050); co_test[i].expected = "80"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0005); co_test[i].expected = "5"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0001); co_test[i].expected = "1"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000); co_test[i].expected = "0"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32767"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32766"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x07F0) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2033"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x5000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-20481"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0500) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1281"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0050) -MPRNT_OFF_T_C(1); co_test[i].expected = "-81"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0005) -MPRNT_OFF_T_C(1); co_test[i].expected = "-6"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1"; num_cofft_tests = i; #elif (CURL_SIZEOF_CURL_OFF_T == 4) i=1; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFF); co_test[i].expected = "2147483647"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFE); co_test[i].expected = "2147483646"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFD); co_test[i].expected = "2147483645"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFF0000); co_test[i].expected = "2147418112"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00007FFF); co_test[i].expected = "32767"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7F000000); co_test[i].expected = "2130706432"; i++; co_test[i].num = MPRNT_OFF_T_C(0x007F0000); co_test[i].expected = "8323072"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00007F00); co_test[i].expected = "32512"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007F); co_test[i].expected = "127"; i++; co_test[i].num = MPRNT_OFF_T_C(0x70000000); co_test[i].expected = "1879048192"; i++; co_test[i].num = MPRNT_OFF_T_C(0x07000000); co_test[i].expected = "117440512"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00700000); co_test[i].expected = "7340032"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00070000); co_test[i].expected = "458752"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00007000); co_test[i].expected = "28672"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000700); co_test[i].expected = "1792"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000070); co_test[i].expected = "112"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000007); co_test[i].expected = "7"; i++; co_test[i].num = MPRNT_OFF_T_C(0x50000000); co_test[i].expected = "1342177280"; i++; co_test[i].num = MPRNT_OFF_T_C(0x05000000); co_test[i].expected = "83886080"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00500000); co_test[i].expected = "5242880"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00050000); co_test[i].expected = "327680"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00005000); co_test[i].expected = "20480"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000500); co_test[i].expected = "1280"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000050); co_test[i].expected = "80"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000005); co_test[i].expected = "5"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000001); co_test[i].expected = "1"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000); co_test[i].expected = "0"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483648"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483647"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483646"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147418113"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2130706433"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8323073"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x70000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1879048193"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x07000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-117440513"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00700000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7340033"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00070000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-458753"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x50000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1342177281"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x05000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-83886081"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00500000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-5242881"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00050000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-327681"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00005000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-20481"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000500) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1281"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000050) -MPRNT_OFF_T_C(1); co_test[i].expected = "-81"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000005) -MPRNT_OFF_T_C(1); co_test[i].expected = "-6"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1"; num_cofft_tests = i; #elif (CURL_SIZEOF_CURL_OFF_T == 8) i=1; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFF); co_test[i].expected = "9223372036854775807"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFE); co_test[i].expected = "9223372036854775806"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFD); co_test[i].expected = "9223372036854775805"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFF00000000); co_test[i].expected = "9223372032559808512"; i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007FFFFFFF); co_test[i].expected = "2147483647"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFF000000000000); co_test[i].expected = "9223090561878065152"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00007FFF00000000); co_test[i].expected = "140733193388032"; i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007FFF0000); co_test[i].expected = "2147418112"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007FFF); co_test[i].expected = "32767"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7F00000000000000); co_test[i].expected = "9151314442816847872"; i++; co_test[i].num = MPRNT_OFF_T_C(0x007F000000000000); co_test[i].expected = "35747322042253312"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00007F0000000000); co_test[i].expected = "139637976727552"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007F00000000); co_test[i].expected = "545460846592"; i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007F000000); co_test[i].expected = "2130706432"; i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000007F0000); co_test[i].expected = "8323072"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007F00); co_test[i].expected = "32512"; i++; co_test[i].num = MPRNT_OFF_T_C(0x000000000000007F); co_test[i].expected = "127"; i++; co_test[i].num = MPRNT_OFF_T_C(0x7000000000000000); co_test[i].expected = "8070450532247928832"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0700000000000000); co_test[i].expected = "504403158265495552"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0070000000000000); co_test[i].expected = "31525197391593472"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0007000000000000); co_test[i].expected = "1970324836974592"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000700000000000); co_test[i].expected = "123145302310912"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000070000000000); co_test[i].expected = "7696581394432"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007000000000); co_test[i].expected = "481036337152"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000700000000); co_test[i].expected = "30064771072"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000070000000); co_test[i].expected = "1879048192"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000007000000); co_test[i].expected = "117440512"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000700000); co_test[i].expected = "7340032"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000070000); co_test[i].expected = "458752"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007000); co_test[i].expected = "28672"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000700); co_test[i].expected = "1792"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000070); co_test[i].expected = "112"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000007); co_test[i].expected = "7"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000001); co_test[i].expected = "1"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000000); co_test[i].expected = "0"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775808"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775807"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775806"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFF00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372032559808513"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007FFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483648"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223090561878065153"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007FFF00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-140733193388033"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007FFF0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147418113"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F00000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9151314442816847873"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-35747322042253313"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007F0000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-139637976727553"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007F00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-545460846593"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007F000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2130706433"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000000007F0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8323073"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000000000007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x7000000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8070450532247928833"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0700000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-504403158265495553"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0070000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-31525197391593473"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0007000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1970324836974593"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000700000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-123145302310913"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000070000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7696581394433"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-481036337153"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000700000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-30064771073"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000070000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1879048193"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000007000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-117440513"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000700000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7340033"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000070000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-458753"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113"; i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8"; i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1"; num_cofft_tests = i; #endif /* !checksrc! enable LONGLINE */ for(i=1; i<=num_cofft_tests; i++) { for(j=0; j<BUFSZ; j++) co_test[i].result[j] = 'X'; co_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(co_test[i].result, "%" CURL_FORMAT_CURL_OFF_T, co_test[i].num); if(memcmp(co_test[i].result, co_test[i].expected, strlen(co_test[i].expected))) { printf("curl_off_t test #%.2d: Failed (Expected: %s Got: %s)\n", i, co_test[i].expected, co_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() curl_off_t tests OK!\n"); else printf("Some curl_mprintf() curl_off_t tests Failed!\n"); return failed; } static int string_check(char *buf, const char *buf2) { if(strcmp(buf, buf2)) { /* they shouldn't differ */ printf("sprintf failed:\nwe '%s'\nsystem: '%s'\n", buf, buf2); return 1; } return 0; } /* * The output strings in this test need to have been verified with a system * sprintf() before used here. */ static int test_string_formatting(void) { int errors = 0; char buf[256]; curl_msnprintf(buf, sizeof(buf), "%0*d%s", 2, 9, "foo"); errors += string_check(buf, "09foo"); curl_msnprintf(buf, sizeof(buf), "%*.*s", 5, 2, "foo"); errors += string_check(buf, " fo"); curl_msnprintf(buf, sizeof(buf), "%*.*s", 2, 5, "foo"); errors += string_check(buf, "foo"); curl_msnprintf(buf, sizeof(buf), "%*.*s", 0, 10, "foo"); errors += string_check(buf, "foo"); curl_msnprintf(buf, sizeof(buf), "%-10s", "foo"); errors += string_check(buf, "foo "); curl_msnprintf(buf, sizeof(buf), "%10s", "foo"); errors += string_check(buf, " foo"); curl_msnprintf(buf, sizeof(buf), "%*.*s", -10, -10, "foo"); errors += string_check(buf, "foo "); if(!errors) printf("All curl_mprintf() strings tests OK!\n"); else printf("Some curl_mprintf() string tests Failed!\n"); return errors; } static int test_weird_arguments(void) { int errors = 0; char buf[256]; int rc; /* MAX_PARAMETERS is 128, try exact 128! */ rc = curl_msnprintf(buf, sizeof(buf), "%d%d%d%d%d%d%d%d%d%d" /* 10 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 1 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 2 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 3 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 4 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 5 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 6 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 7 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 8 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 9 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 10 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 11 */ "%d%d%d%d%d%d%d%d" /* 8 */ , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 1 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 2 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 4 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 5 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 6 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 7 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 8 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 9 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 10 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 11 */ 0, 1, 2, 3, 4, 5, 6, 7); /* 8 */ if(rc != 128) { printf("curl_mprintf() returned %d and not 128!\n", rc); errors++; } errors += string_check(buf, "0123456789" /* 10 */ "0123456789" /* 10 1 */ "0123456789" /* 10 2 */ "0123456789" /* 10 3 */ "0123456789" /* 10 4 */ "0123456789" /* 10 5 */ "0123456789" /* 10 6 */ "0123456789" /* 10 7 */ "0123456789" /* 10 8 */ "0123456789" /* 10 9 */ "0123456789" /* 10 10*/ "0123456789" /* 10 11 */ "01234567" /* 8 */ ); /* MAX_PARAMETERS is 128, try more! */ buf[0] = 0; rc = curl_msnprintf(buf, sizeof(buf), "%d%d%d%d%d%d%d%d%d%d" /* 10 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 1 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 2 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 3 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 4 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 5 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 6 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 7 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 8 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 9 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 10 */ "%d%d%d%d%d%d%d%d%d%d" /* 10 11 */ "%d%d%d%d%d%d%d%d%d" /* 9 */ , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 1 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 2 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 4 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 5 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 6 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 7 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 8 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 9 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 10 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 11 */ 0, 1, 2, 3, 4, 5, 6, 7, 8); /* 9 */ if(rc != -1) { printf("curl_mprintf() returned %d and not -1!\n", rc); errors++; } errors += string_check(buf, ""); if(errors) printf("Some curl_mprintf() weird arguments tests failed!\n"); return errors; } int test(char *URL) { int errors = 0; (void)URL; /* not used */ errors += test_weird_arguments(); errors += test_unsigned_short_formatting(); errors += test_signed_short_formatting(); errors += test_unsigned_int_formatting(); errors += test_signed_int_formatting(); errors += test_unsigned_long_formatting(); errors += test_signed_long_formatting(); errors += test_curl_off_t_formatting(); errors += test_string_formatting(); if(errors) return TEST_ERR_MAJOR_BAD; else return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5493_2
crossvul-cpp_data_bad_1614_0
/* ----------------------------------------------------------------------------- * Copyright (c) 2011 Ozmo Inc * Released under the GNU General Public License Version 2 (GPLv2). * * This file implements the protocol specific parts of the USB service for a PD. * ----------------------------------------------------------------------------- */ #include <linux/module.h> #include <linux/timer.h> #include <linux/sched.h> #include <linux/netdevice.h> #include <linux/errno.h> #include <linux/input.h> #include <asm/unaligned.h> #include "ozdbg.h" #include "ozprotocol.h" #include "ozeltbuf.h" #include "ozpd.h" #include "ozproto.h" #include "ozusbif.h" #include "ozhcd.h" #include "ozusbsvc.h" #define MAX_ISOC_FIXED_DATA (253-sizeof(struct oz_isoc_fixed)) /* * Context: softirq */ static int oz_usb_submit_elt(struct oz_elt_buf *eb, struct oz_elt_info *ei, struct oz_usb_ctx *usb_ctx, u8 strid, u8 isoc) { int ret; struct oz_elt *elt = (struct oz_elt *)ei->data; struct oz_app_hdr *app_hdr = (struct oz_app_hdr *)(elt+1); elt->type = OZ_ELT_APP_DATA; ei->app_id = OZ_APPID_USB; ei->length = elt->length + sizeof(struct oz_elt); app_hdr->app_id = OZ_APPID_USB; spin_lock_bh(&eb->lock); if (isoc == 0) { app_hdr->elt_seq_num = usb_ctx->tx_seq_num++; if (usb_ctx->tx_seq_num == 0) usb_ctx->tx_seq_num = 1; } ret = oz_queue_elt_info(eb, isoc, strid, ei); if (ret) oz_elt_info_free(eb, ei); spin_unlock_bh(&eb->lock); return ret; } /* * Context: softirq */ int oz_usb_get_desc_req(void *hpd, u8 req_id, u8 req_type, u8 desc_type, u8 index, __le16 windex, int offset, int len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_get_desc_req *body; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); oz_dbg(ON, " req_type = 0x%x\n", req_type); oz_dbg(ON, " desc_type = 0x%x\n", desc_type); oz_dbg(ON, " index = 0x%x\n", index); oz_dbg(ON, " windex = 0x%x\n", windex); oz_dbg(ON, " offset = 0x%x\n", offset); oz_dbg(ON, " len = 0x%x\n", len); if (len > 200) len = 200; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_get_desc_req); body = (struct oz_get_desc_req *)(elt+1); body->type = OZ_GET_DESC_REQ; body->req_id = req_id; put_unaligned(cpu_to_le16(offset), &body->offset); put_unaligned(cpu_to_le16(len), &body->size); body->req_type = req_type; body->desc_type = desc_type; body->w_index = windex; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_config_req(void *hpd, u8 req_id, u8 index) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_config_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_config_req); body = (struct oz_set_config_req *)(elt+1); body->type = OZ_SET_CONFIG_REQ; body->req_id = req_id; body->index = index; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_interface_req(void *hpd, u8 req_id, u8 index, u8 alt) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_set_interface_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_set_interface_req); body = (struct oz_set_interface_req *)(elt+1); body->type = OZ_SET_INTERFACE_REQ; body->req_id = req_id; body->index = index; body->alternative = alt; return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_set_clear_feature_req(void *hpd, u8 req_id, u8 type, u8 recipient, u8 index, __le16 feature) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_feature_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_feature_req); body = (struct oz_feature_req *)(elt+1); body->type = type; body->req_id = req_id; body->recipient = recipient; body->index = index; put_unaligned(feature, &body->feature); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ static int oz_usb_vendor_class_req(void *hpd, u8 req_id, u8 req_type, u8 request, __le16 value, __le16 index, const u8 *data, int data_len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_vendor_class_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_vendor_class_req) - 1 + data_len; body = (struct oz_vendor_class_req *)(elt+1); body->type = OZ_VENDOR_CLASS_REQ; body->req_id = req_id; body->req_type = req_type; body->request = request; put_unaligned(value, &body->value); put_unaligned(index, &body->index); if (data_len) memcpy(body->data, data, data_len); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } /* * Context: tasklet */ int oz_usb_control_req(void *hpd, u8 req_id, struct usb_ctrlrequest *setup, const u8 *data, int data_len) { unsigned wvalue = le16_to_cpu(setup->wValue); unsigned windex = le16_to_cpu(setup->wIndex); unsigned wlength = le16_to_cpu(setup->wLength); int rc = 0; if ((setup->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) { switch (setup->bRequest) { case USB_REQ_GET_DESCRIPTOR: rc = oz_usb_get_desc_req(hpd, req_id, setup->bRequestType, (u8)(wvalue>>8), (u8)wvalue, setup->wIndex, 0, wlength); break; case USB_REQ_SET_CONFIGURATION: rc = oz_usb_set_config_req(hpd, req_id, (u8)wvalue); break; case USB_REQ_SET_INTERFACE: { u8 if_num = (u8)windex; u8 alt = (u8)wvalue; rc = oz_usb_set_interface_req(hpd, req_id, if_num, alt); } break; case USB_REQ_SET_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_SET_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; case USB_REQ_CLEAR_FEATURE: rc = oz_usb_set_clear_feature_req(hpd, req_id, OZ_CLEAR_FEATURE_REQ, setup->bRequestType & 0xf, (u8)windex, setup->wValue); break; } } else { rc = oz_usb_vendor_class_req(hpd, req_id, setup->bRequestType, setup->bRequest, setup->wValue, setup->wIndex, data, data_len); } return rc; } /* * Context: softirq */ int oz_usb_send_isoc(void *hpd, u8 ep_num, struct urb *urb) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt_buf *eb; int i; int hdr_size; u8 *data; struct usb_iso_packet_descriptor *desc; if (pd->mode & OZ_F_ISOC_NO_ELTS) { for (i = 0; i < urb->number_of_packets; i++) { u8 *data; desc = &urb->iso_frame_desc[i]; data = ((u8 *)urb->transfer_buffer)+desc->offset; oz_send_isoc_unit(pd, ep_num, data, desc->length); } return 0; } hdr_size = sizeof(struct oz_isoc_fixed) - 1; eb = &pd->elt_buff; i = 0; while (i < urb->number_of_packets) { struct oz_elt_info *ei = oz_elt_info_alloc(eb); struct oz_elt *elt; struct oz_isoc_fixed *body; int unit_count; int unit_size; int rem; if (ei == NULL) return -1; rem = MAX_ISOC_FIXED_DATA; elt = (struct oz_elt *)ei->data; body = (struct oz_isoc_fixed *)(elt + 1); body->type = OZ_USB_ENDPOINT_DATA; body->endpoint = ep_num; body->format = OZ_DATA_F_ISOC_FIXED; unit_size = urb->iso_frame_desc[i].length; body->unit_size = (u8)unit_size; data = ((u8 *)(elt+1)) + hdr_size; unit_count = 0; while (i < urb->number_of_packets) { desc = &urb->iso_frame_desc[i]; if ((unit_size == desc->length) && (desc->length <= rem)) { memcpy(data, ((u8 *)urb->transfer_buffer) + desc->offset, unit_size); data += unit_size; rem -= unit_size; unit_count++; desc->status = 0; desc->actual_length = desc->length; i++; } else { break; } } elt->length = hdr_size + MAX_ISOC_FIXED_DATA - rem; /* Store the number of units in body->frame_number for the * moment. This field will be correctly determined before * the element is sent. */ body->frame_number = (u8)unit_count; oz_usb_submit_elt(eb, ei, usb_ctx, ep_num, pd->mode & OZ_F_ISOC_ANYTIME); } return 0; } /* * Context: softirq-serialized */ static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; int n; if (!body->unit_size) break; n = (len - sizeof(struct oz_multiple_fixed)+1) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } } /* * This is called when the PD has received a USB element. The type of element * is determined and is then passed to an appropriate handler function. * Context: softirq-serialized */ void oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; u16 offs, total_size; u8 data_len; if (elt->length < sizeof(struct oz_get_desc_rsp) - 1) break; data_len = elt->length - (sizeof(struct oz_get_desc_rsp) - 1); offs = le16_to_cpu(get_unaligned(&body->offset)); total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } /* * Context: softirq, process */ void oz_usb_farewell(struct oz_pd *pd, u8 ep_num, u8 *data, u8 len) { struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (!usb_ctx->stopped) { oz_dbg(ON, "Farewell indicated ep = 0x%x\n", ep_num); oz_hcd_data_ind(usb_ctx->hport, ep_num, data, len); } oz_usb_put(usb_ctx); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_1614_0
crossvul-cpp_data_good_4985_0
/* * MOV demuxer * Copyright (c) 2001 Fabrice Bellard * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <limits.h> //#define DEBUG //#define MOV_EXPORT_ALL_METADATA #include "libavutil/audioconvert.h" #include "libavutil/intreadwrite.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/avstring.h" #include "libavutil/dict.h" #include "libavutil/opt.h" #include "libavutil/timecode.h" #include "libavcodec/ac3tab.h" #include "avformat.h" #include "internal.h" #include "avio_internal.h" #include "riff.h" #include "isom.h" #include "libavcodec/get_bits.h" #include "id3v1.h" #include "mov_chan.h" #if CONFIG_ZLIB #include <zlib.h> #endif /* * First version by Francois Revol revol@free.fr * Seek function by Gael Chardon gael.dev@4now.net */ #include "qtpalette.h" #undef NDEBUG #include <assert.h> /* those functions parse an atom */ /* links atom IDs to parse functions */ typedef struct MOVParseTableEntry { uint32_t type; int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom); } MOVParseTableEntry; static const MOVParseTableEntry mov_default_parse_table[]; static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { char buf[16]; short current, total = 0; avio_rb16(pb); // unknown current = avio_rb16(pb); if (len >= 6) total = avio_rb16(pb); if (!total) snprintf(buf, sizeof(buf), "%d", current); else snprintf(buf, sizeof(buf), "%d/%d", current, total); av_dict_set(&c->fc->metadata, key, buf, 0); return 0; } static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { char buf[16]; /* bypass padding bytes */ avio_r8(pb); avio_r8(pb); avio_r8(pb); snprintf(buf, sizeof(buf), "%d", avio_r8(pb)); av_dict_set(&c->fc->metadata, key, buf, 0); return 0; } static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { char buf[16]; snprintf(buf, sizeof(buf), "%d", avio_r8(pb)); av_dict_set(&c->fc->metadata, key, buf, 0); return 0; } static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { short genre; char buf[20]; avio_r8(pb); // unknown genre = avio_r8(pb); if (genre < 1 || genre > ID3v1_GENRE_MAX) return 0; snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]); av_dict_set(&c->fc->metadata, key, buf, 0); return 0; } static const uint32_t mac_to_unicode[128] = { 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1, 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8, 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3, 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC, 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF, 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8, 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211, 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8, 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB, 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153, 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA, 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02, 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1, 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4, 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC, 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7, }; static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len, char *dst, int dstlen) { char *p = dst; char *end = dst+dstlen-1; int i; for (i = 0; i < len; i++) { uint8_t t, c = avio_r8(pb); if (c < 0x80 && p < end) *p++ = c; else if (p < end) PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;); } *p = 0; return p - dst; } static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom) { #ifdef MOV_EXPORT_ALL_METADATA char tmp_key[5]; #endif char str[1024], key2[16], language[4] = {0}; const char *key = NULL; uint16_t str_size, langcode = 0; uint32_t data_type = 0; int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL; switch (atom.type) { case MKTAG(0xa9,'n','a','m'): key = "title"; break; case MKTAG(0xa9,'a','u','t'): case MKTAG(0xa9,'A','R','T'): key = "artist"; break; case MKTAG( 'a','A','R','T'): key = "album_artist"; break; case MKTAG(0xa9,'w','r','t'): key = "composer"; break; case MKTAG( 'c','p','r','t'): case MKTAG(0xa9,'c','p','y'): key = "copyright"; break; case MKTAG(0xa9,'g','r','p'): key = "grouping"; break; case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break; case MKTAG(0xa9,'c','m','t'): case MKTAG(0xa9,'i','n','f'): key = "comment"; break; case MKTAG(0xa9,'a','l','b'): key = "album"; break; case MKTAG(0xa9,'d','a','y'): key = "date"; break; case MKTAG(0xa9,'g','e','n'): key = "genre"; break; case MKTAG( 'g','n','r','e'): key = "genre"; parse = mov_metadata_gnre; break; case MKTAG(0xa9,'t','o','o'): case MKTAG(0xa9,'s','w','r'): key = "encoder"; break; case MKTAG(0xa9,'e','n','c'): key = "encoder"; break; case MKTAG( 'd','e','s','c'): key = "description";break; case MKTAG( 'l','d','e','s'): key = "synopsis"; break; case MKTAG( 't','v','s','h'): key = "show"; break; case MKTAG( 't','v','e','n'): key = "episode_id";break; case MKTAG( 't','v','n','n'): key = "network"; break; case MKTAG( 't','r','k','n'): key = "track"; parse = mov_metadata_track_or_disc_number; break; case MKTAG( 'd','i','s','k'): key = "disc"; parse = mov_metadata_track_or_disc_number; break; case MKTAG( 't','v','e','s'): key = "episode_sort"; parse = mov_metadata_int8_bypass_padding; break; case MKTAG( 't','v','s','n'): key = "season_number"; parse = mov_metadata_int8_bypass_padding; break; case MKTAG( 's','t','i','k'): key = "media_type"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'h','d','v','d'): key = "hd_video"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'p','g','a','p'): key = "gapless_playback"; parse = mov_metadata_int8_no_padding; break; } if (c->itunes_metadata && atom.size > 8) { int data_size = avio_rb32(pb); int tag = avio_rl32(pb); if (tag == MKTAG('d','a','t','a')) { data_type = avio_rb32(pb); // type avio_rb32(pb); // unknown str_size = data_size - 16; atom.size -= 16; } else return 0; } else if (atom.size > 4 && key && !c->itunes_metadata) { str_size = avio_rb16(pb); // string length langcode = avio_rb16(pb); ff_mov_lang_to_iso639(langcode, language); atom.size -= 4; } else str_size = atom.size; #ifdef MOV_EXPORT_ALL_METADATA if (!key) { snprintf(tmp_key, 5, "%.4s", (char*)&atom.type); key = tmp_key; } #endif if (!key) return 0; if (atom.size < 0) return AVERROR_INVALIDDATA; str_size = FFMIN3(sizeof(str)-1, str_size, atom.size); if (parse) parse(c, pb, str_size, key); else { if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded mov_read_mac_string(c, pb, str_size, str, sizeof(str)); } else { avio_read(pb, str, str_size); str[str_size] = 0; } av_dict_set(&c->fc->metadata, key, str, 0); if (*language && strcmp(language, "und")) { snprintf(key2, sizeof(key2), "%s-%s", key, language); av_dict_set(&c->fc->metadata, key2, str, 0); } } av_dlog(c->fc, "lang \"%3s\" ", language); av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n", key, str, (char*)&atom.type, str_size, atom.size); return 0; } static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t start; int i, nb_chapters, str_len, version; char str[256+1]; if ((atom.size -= 5) < 0) return 0; version = avio_r8(pb); avio_rb24(pb); if (version) avio_rb32(pb); // ??? nb_chapters = avio_r8(pb); for (i = 0; i < nb_chapters; i++) { if (atom.size < 9) return 0; start = avio_rb64(pb); str_len = avio_r8(pb); if ((atom.size -= 9+str_len) < 0) return 0; avio_read(pb, str, str_len); str[str_len] = 0; avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str); } return 0; } static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t total_size = 0; MOVAtom a; int i; if (atom.size < 0) atom.size = INT64_MAX; while (total_size + 8 <= atom.size && !url_feof(pb)) { int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL; a.size = atom.size; a.type=0; if (atom.size >= 8) { a.size = avio_rb32(pb); a.type = avio_rl32(pb); if (atom.type != MKTAG('r','o','o','t') && atom.type != MKTAG('m','o','o','v')) { if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t')) { av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n"); avio_skip(pb, -8); return 0; } } total_size += 8; if (a.size == 1) { /* 64 bit extended size */ a.size = avio_rb64(pb) - 8; total_size += 8; } } av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n", a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size); if (a.size == 0) { a.size = atom.size - total_size + 8; } a.size -= 8; if (a.size < 0) break; a.size = FFMIN(a.size, atom.size - total_size); for (i = 0; mov_default_parse_table[i].type; i++) if (mov_default_parse_table[i].type == a.type) { parse = mov_default_parse_table[i].parse; break; } // container is user data if (!parse && (atom.type == MKTAG('u','d','t','a') || atom.type == MKTAG('i','l','s','t'))) parse = mov_read_udta_string; if (!parse) { /* skip leaf atoms data */ avio_skip(pb, a.size); } else { int64_t start_pos = avio_tell(pb); int64_t left; int err = parse(c, pb, a); if (err < 0) return err; if (c->found_moov && c->found_mdat && ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) || start_pos + a.size == avio_size(pb))) { if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) c->next_root_atom = start_pos + a.size; return 0; } left = a.size - avio_tell(pb) + start_pos; if (left > 0) /* skip garbage at atom end */ avio_skip(pb, left); } total_size += a.size; } if (total_size < atom.size && atom.size < 0x7ffff) avio_skip(pb, atom.size - total_size); return 0; } static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int entries, i, j; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (entries >= UINT_MAX / sizeof(*sc->drefs)) return AVERROR_INVALIDDATA; av_free(sc->drefs); sc->drefs_count = 0; sc->drefs = av_mallocz(entries * sizeof(*sc->drefs)); if (!sc->drefs) return AVERROR(ENOMEM); sc->drefs_count = entries; for (i = 0; i < sc->drefs_count; i++) { MOVDref *dref = &sc->drefs[i]; uint32_t size = avio_rb32(pb); int64_t next = avio_tell(pb) + size - 4; if (size < 12) return AVERROR_INVALIDDATA; dref->type = avio_rl32(pb); avio_rb32(pb); // version + flags av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size); if (dref->type == MKTAG('a','l','i','s') && size > 150) { /* macintosh alias record */ uint16_t volume_len, len; int16_t type; avio_skip(pb, 10); volume_len = avio_r8(pb); volume_len = FFMIN(volume_len, 27); avio_read(pb, dref->volume, 27); dref->volume[volume_len] = 0; av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len); avio_skip(pb, 12); len = avio_r8(pb); len = FFMIN(len, 63); avio_read(pb, dref->filename, 63); dref->filename[len] = 0; av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len); avio_skip(pb, 16); /* read next level up_from_alias/down_to_target */ dref->nlvl_from = avio_rb16(pb); dref->nlvl_to = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n", dref->nlvl_from, dref->nlvl_to); avio_skip(pb, 16); for (type = 0; type != -1 && avio_tell(pb) < next; ) { if(url_feof(pb)) return AVERROR_EOF; type = avio_rb16(pb); len = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len); if (len&1) len += 1; if (type == 2) { // absolute path av_free(dref->path); dref->path = av_mallocz(len+1); if (!dref->path) return AVERROR(ENOMEM); avio_read(pb, dref->path, len); if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) { len -= volume_len; memmove(dref->path, dref->path+volume_len, len); dref->path[len] = 0; } for (j = 0; j < len; j++) if (dref->path[j] == ':') dref->path[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path); } else if (type == 0) { // directory name av_free(dref->dir); dref->dir = av_malloc(len+1); if (!dref->dir) return AVERROR(ENOMEM); avio_read(pb, dref->dir, len); dref->dir[len] = 0; for (j = 0; j < len; j++) if (dref->dir[j] == ':') dref->dir[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir); } else avio_skip(pb, len); } } avio_seek(pb, next, SEEK_SET); } return 0; } static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint32_t type; uint32_t av_unused ctype; int title_size; char *title_str; if (c->fc->nb_streams < 1) // meta before first trak return 0; st = c->fc->streams[c->fc->nb_streams-1]; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ /* component type */ ctype = avio_rl32(pb); type = avio_rl32(pb); /* component subtype */ av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype); av_dlog(c->fc, "stype= %.4s\n", (char*)&type); if (type == MKTAG('v','i','d','e')) st->codec->codec_type = AVMEDIA_TYPE_VIDEO; else if (type == MKTAG('s','o','u','n')) st->codec->codec_type = AVMEDIA_TYPE_AUDIO; else if (type == MKTAG('m','1','a',' ')) st->codec->codec_id = CODEC_ID_MP2; else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p'))) st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE; avio_rb32(pb); /* component manufacture */ avio_rb32(pb); /* component flags */ avio_rb32(pb); /* component flags mask */ title_size = atom.size - 24; if (title_size > 0) { title_str = av_malloc(title_size + 1); /* Add null terminator */ if (!title_str) return AVERROR(ENOMEM); avio_read(pb, title_str, title_size); title_str[title_size] = 0; if (title_str[0]) av_dict_set(&st->metadata, "handler_name", title_str + (!c->isom && title_str[0] == title_size - 1), 0); av_freep(&title_str); } return 0; } int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom) { AVStream *st; int tag; if (fc->nb_streams < 1) return 0; st = fc->streams[fc->nb_streams-1]; avio_rb32(pb); /* version + flags */ ff_mp4_read_descr(fc, pb, &tag); if (tag == MP4ESDescrTag) { ff_mp4_parse_es_descr(pb, NULL); } else avio_rb16(pb); /* ID */ ff_mp4_read_descr(fc, pb, &tag); if (tag == MP4DecConfigDescrTag) ff_mp4_read_dec_config_descr(fc, st, pb); return 0; } static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return ff_mov_read_esds(c->fc, pb, atom); } static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ac3info, acmod, lfeon, bsmod; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; ac3info = avio_rb24(pb); bsmod = (ac3info >> 14) & 0x7; acmod = (ac3info >> 11) & 0x7; lfeon = (ac3info >> 10) & 0x1; st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon; st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod]; if (lfeon) st->codec->channel_layout |= AV_CH_LOW_FREQUENCY; st->codec->audio_service_type = bsmod; if (st->codec->channels > 1 && bsmod == 0x7) st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE; return 0; } static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint8_t version; uint32_t flags, layout_tag, bitmap, num_descr, label_mask; int i; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 16) return 0; version = avio_r8(pb); flags = avio_rb24(pb); layout_tag = avio_rb32(pb); bitmap = avio_rb32(pb); num_descr = avio_rb32(pb); if (atom.size < 16ULL + num_descr * 20ULL) return 0; av_dlog(c->fc, "chan: size=%" PRId64 " version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n", atom.size, version, flags, layout_tag, bitmap, num_descr); label_mask = 0; for (i = 0; i < num_descr; i++) { uint32_t av_unused label, cflags; label = avio_rb32(pb); // mChannelLabel cflags = avio_rb32(pb); // mChannelFlags avio_rl32(pb); // mCoordinates[0] avio_rl32(pb); // mCoordinates[1] avio_rl32(pb); // mCoordinates[2] if (layout_tag == 0) { uint32_t mask_incr = ff_mov_get_channel_label(label); if (mask_incr == 0) { label_mask = 0; break; } label_mask |= mask_incr; } } if (layout_tag == 0) st->codec->channel_layout = label_mask; else st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap); return 0; } static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; ff_get_wav_header(pb, st->codec, atom.size); return 0; } static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const int num = avio_rb32(pb); const int den = avio_rb32(pb); AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) { av_log(c->fc, AV_LOG_WARNING, "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, num, den); } else if (den != 0) { st->sample_aspect_ratio.num = num; st->sample_aspect_ratio.den = den; } return 0; } /* this atom contains actual media data */ static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (atom.size == 0) /* wrong one (MP4) */ return 0; c->found_mdat=1; return 0; /* now go for moov */ } /* read major brand, minor version and compatible brands and store them as metadata */ static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t minor_ver; int comp_brand_size; char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */ char* comp_brands_str; uint8_t type[5] = {0}; avio_read(pb, type, 4); if (strcmp(type, "qt ")) c->isom = 1; av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type); av_dict_set(&c->fc->metadata, "major_brand", type, 0); minor_ver = avio_rb32(pb); /* minor version */ snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver); av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0); comp_brand_size = atom.size - 8; if (comp_brand_size < 0) return AVERROR_INVALIDDATA; comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */ if (!comp_brands_str) return AVERROR(ENOMEM); avio_read(pb, comp_brands_str, comp_brand_size); comp_brands_str[comp_brand_size] = 0; av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0); av_freep(&comp_brands_str); return 0; } /* this atom should contain all header atoms */ static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */ /* so we don't parse the whole file if over a network */ c->found_moov=1; return 0; /* now go for mdat */ } static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom) { c->fragment.moof_offset = avio_tell(pb) - 8; av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset); return mov_read_default(c, pb, atom); } static void mov_metadata_creation_time(AVDictionary **metadata, time_t time) { char buffer[32]; if (time) { struct tm *ptm; time -= 2082844800; /* seconds between 1904-01-01 and Epoch */ ptm = gmtime(&time); if (!ptm) return; strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm); av_dict_set(metadata, "creation_time", buffer, 0); } } static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int version; char language[4] = {0}; unsigned lang; time_t creation_time; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; version = avio_r8(pb); if (version > 1) { av_log_ask_for_sample(c, "unsupported version %d\n", version); return AVERROR_PATCHWELCOME; } avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&st->metadata, creation_time); sc->time_scale = avio_rb32(pb); st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ lang = avio_rb16(pb); /* language */ if (ff_mov_lang_to_iso639(lang, language)) av_dict_set(&st->metadata, "language", language, 0); avio_rb16(pb); /* quality */ return 0; } static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { time_t creation_time; int version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&c->fc->metadata, creation_time); c->time_scale = avio_rb32(pb); /* time scale */ av_dlog(c->fc, "time scale = %i\n", c->time_scale); c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ // set the AVCodecContext duration because the duration of individual tracks // may be inaccurate if (c->time_scale > 0) c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale); avio_rb32(pb); /* preferred scale */ avio_rb16(pb); /* preferred volume */ avio_skip(pb, 10); /* reserved */ avio_skip(pb, 36); /* display matrix */ avio_rb32(pb); /* preview time */ avio_rb32(pb); /* preview duration */ avio_rb32(pb); /* poster time */ avio_rb32(pb); /* selection time */ avio_rb32(pb); /* selection duration */ avio_rb32(pb); /* current time */ avio_rb32(pb); /* next track ID */ return 0; } static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; // currently SVQ3 decoder expect full STSD header - so let's fake it // this should be fixed and just SMI header should be passed av_free(st->codec->extradata); st->codec->extradata_size = 0; st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = 0x5a + atom.size; memcpy(st->codec->extradata, "SVQ3", 4); // fake avio_read(pb, st->codec->extradata + 0x5a, atom.size); av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a); return 0; } static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int little_endian; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; little_endian = avio_rb16(pb) & 0xFF; av_dlog(c->fc, "enda %d\n", little_endian); if (little_endian == 1) { switch (st->codec->codec_id) { case CODEC_ID_PCM_S24BE: st->codec->codec_id = CODEC_ID_PCM_S24LE; break; case CODEC_ID_PCM_S32BE: st->codec->codec_id = CODEC_ID_PCM_S32LE; break; case CODEC_ID_PCM_F32BE: st->codec->codec_id = CODEC_ID_PCM_F32LE; break; case CODEC_ID_PCM_F64BE: st->codec->codec_id = CODEC_ID_PCM_F64LE; break; default: break; } } return 0; } static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; unsigned mov_field_order; enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 2) return AVERROR_INVALIDDATA; mov_field_order = avio_rb16(pb); if ((mov_field_order & 0xFF00) == 0x0100) decoded_field_order = AV_FIELD_PROGRESSIVE; else if ((mov_field_order & 0xFF00) == 0x0200) { switch (mov_field_order & 0xFF) { case 0x01: decoded_field_order = AV_FIELD_TT; break; case 0x06: decoded_field_order = AV_FIELD_BB; break; case 0x09: decoded_field_order = AV_FIELD_TB; break; case 0x0E: decoded_field_order = AV_FIELD_BT; break; } } if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) { av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order); } st->codec->field_order = decoded_field_order; return 0; } /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */ static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, enum CodecID codec_id) { AVStream *st; uint64_t size; uint8_t *buf; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st= c->fc->streams[c->fc->nb_streams-1]; if (st->codec->codec_id != codec_id) return 0; /* unexpected codec_id - don't mess with extradata */ size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE; if (size > INT_MAX || (uint64_t)atom.size > INT_MAX) return AVERROR_INVALIDDATA; buf= av_realloc(st->codec->extradata, size); if (!buf) return AVERROR(ENOMEM); st->codec->extradata= buf; buf+= st->codec->extradata_size; st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE; AV_WB32( buf , atom.size + 8); AV_WL32( buf + 4, atom.type); avio_read(pb, buf + 8, atom.size); return 0; } /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */ static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC); } static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, CODEC_ID_AVS); } static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000); } static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) { // pass all frma atom to codec, needed at least for QDMC and QDM2 av_free(st->codec->extradata); st->codec->extradata_size = 0; st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = atom.size; avio_read(pb, st->codec->extradata, atom.size); } else if (atom.size > 8) { /* to read frma, esds atoms */ int ret; if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; } else avio_skip(pb, atom.size); return 0; } /** * This function reads atom content and puts data in extradata without tag * nor size unlike mov_read_extradata. */ static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; if (atom.size >= 10) { // Broken files created by legacy versions of Libav and FFmpeg will // wrap a whole fiel atom inside of a glbl atom. unsigned size = avio_rb32(pb); unsigned type = avio_rl32(pb); avio_seek(pb, -8, SEEK_CUR); if (type == MKTAG('f','i','e','l') && size == atom.size) return mov_read_default(c, pb, atom); } av_free(st->codec->extradata); st->codec->extradata_size = 0; st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = atom.size; avio_read(pb, st->codec->extradata, atom.size); return 0; } static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint8_t profile_level; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size >= (1<<28) || atom.size < 7) return AVERROR_INVALIDDATA; profile_level = avio_r8(pb); if (profile_level & 0xf0 != 0xc0) return 0; av_free(st->codec->extradata); st->codec->extradata_size = 0; st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = atom.size - 7; avio_seek(pb, 6, SEEK_CUR); avio_read(pb, st->codec->extradata, st->codec->extradata_size); return 0; } /** * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself, * but can have extradata appended at the end after the 40 bytes belonging * to the struct. */ static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; if (atom.size <= 40) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; av_free(st->codec->extradata); st->codec->extradata_size = 0; st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = atom.size - 40; avio_skip(pb, 40); avio_read(pb, st->codec->extradata, atom.size - 40); return 0; } static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); if (!entries) return 0; if (entries >= UINT_MAX/sizeof(int64_t)) return AVERROR_INVALIDDATA; sc->chunk_offsets = av_malloc(entries * sizeof(int64_t)); if (!sc->chunk_offsets) return AVERROR(ENOMEM); sc->chunk_count = entries; if (atom.type == MKTAG('s','t','c','o')) for (i=0; i<entries; i++) sc->chunk_offsets[i] = avio_rb32(pb); else if (atom.type == MKTAG('c','o','6','4')) for (i=0; i<entries; i++) sc->chunk_offsets[i] = avio_rb64(pb); else return AVERROR_INVALIDDATA; return 0; } /** * Compute codec id for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags) { if (flags & 1) { // floating point if (flags & 2) { // big endian if (bps == 32) return CODEC_ID_PCM_F32BE; else if (bps == 64) return CODEC_ID_PCM_F64BE; } else { if (bps == 32) return CODEC_ID_PCM_F32LE; else if (bps == 64) return CODEC_ID_PCM_F64LE; } } else { if (flags & 2) { if (bps == 8) // signed integer if (flags & 4) return CODEC_ID_PCM_S8; else return CODEC_ID_PCM_U8; else if (bps == 16) return CODEC_ID_PCM_S16BE; else if (bps == 24) return CODEC_ID_PCM_S24BE; else if (bps == 32) return CODEC_ID_PCM_S32BE; } else { if (bps == 8) if (flags & 4) return CODEC_ID_PCM_S8; else return CODEC_ID_PCM_U8; else if (bps == 16) return CODEC_ID_PCM_S16LE; else if (bps == 24) return CODEC_ID_PCM_S24LE; else if (bps == 32) return CODEC_ID_PCM_S32LE; } } return CODEC_ID_NONE; } int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries) { AVStream *st; MOVStreamContext *sc; int j, pseudo_stream_id; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) { //Parsing Sample description table enum CodecID id; int dref_id = 1; MOVAtom a = { AV_RL32("stsd") }; int64_t start_pos = avio_tell(pb); int size = avio_rb32(pb); /* size */ uint32_t format = avio_rl32(pb); /* data format */ if (size >= 16) { avio_rb32(pb); /* reserved */ avio_rb16(pb); /* reserved */ dref_id = avio_rb16(pb); }else if (size <= 0){ av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size); return -1; } if (st->codec->codec_tag && st->codec->codec_tag != format && (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id : st->codec->codec_tag != MKTAG('j','p','e','g')) ){ /* Multiple fourcc, we skip JPEG. This is not correct, we should * export it as a separate AVStream but this needs a few changes * in the MOV demuxer, patch welcome. */ av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n"); avio_skip(pb, size - (avio_tell(pb) - start_pos)); continue; } /* we cannot demux concatenated h264 streams because of different extradata */ if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1")) av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n"); sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id; sc->dref_id= dref_id; st->codec->codec_tag = format; id = ff_codec_get_id(ff_codec_movaudio_tags, format); if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8))) id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF); if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) { st->codec->codec_type = AVMEDIA_TYPE_AUDIO; } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */ format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */ id = ff_codec_get_id(ff_codec_movvideo_tags, format); if (id <= 0) id = ff_codec_get_id(ff_codec_bmp_tags, format); if (id > 0) st->codec->codec_type = AVMEDIA_TYPE_VIDEO; else if (st->codec->codec_type == AVMEDIA_TYPE_DATA || (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE && st->codec->codec_id == CODEC_ID_NONE)){ id = ff_codec_get_id(ff_codec_movsubtitle_tags, format); if (id > 0) st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE; } } av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size, (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff, (format >> 24) & 0xff, st->codec->codec_type); if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) { unsigned int color_depth, len; int color_greyscale; int color_table_id; st->codec->codec_id = id; avio_rb16(pb); /* version */ avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ avio_rb32(pb); /* temporal quality */ avio_rb32(pb); /* spatial quality */ st->codec->width = avio_rb16(pb); /* width */ st->codec->height = avio_rb16(pb); /* height */ avio_rb32(pb); /* horiz resolution */ avio_rb32(pb); /* vert resolution */ avio_rb32(pb); /* data size, always 0 */ avio_rb16(pb); /* frames per samples */ len = avio_r8(pb); /* codec name, pascal string */ if (len > 31) len = 31; mov_read_mac_string(c, pb, len, st->codec->codec_name, 32); if (len < 31) avio_skip(pb, 31 - len); /* codec_tag YV12 triggers an UV swap in rawdec.c */ if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) st->codec->codec_tag=MKTAG('I', '4', '2', '0'); st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */ color_table_id = avio_rb16(pb); /* colortable id */ av_dlog(c->fc, "depth %d, ctab id %d\n", st->codec->bits_per_coded_sample, color_table_id); /* figure out the palette situation */ color_depth = st->codec->bits_per_coded_sample & 0x1F; color_greyscale = st->codec->bits_per_coded_sample & 0x20; /* if the depth is 2, 4, or 8 bpp, file is palettized */ if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) { /* for palette traversal */ unsigned int color_start, color_count, color_end; unsigned char a, r, g, b; if (color_greyscale) { int color_index, color_dec; /* compute the greyscale palette */ st->codec->bits_per_coded_sample = color_depth; color_count = 1 << color_depth; color_index = 255; color_dec = 256 / (color_count - 1); for (j = 0; j < color_count; j++) { if (id == CODEC_ID_CINEPAK){ r = g = b = color_count - 1 - color_index; }else r = g = b = color_index; sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b); color_index -= color_dec; if (color_index < 0) color_index = 0; } } else if (color_table_id) { const uint8_t *color_table; /* if flag bit 3 is set, use the default palette */ color_count = 1 << color_depth; if (color_depth == 2) color_table = ff_qt_default_palette_4; else if (color_depth == 4) color_table = ff_qt_default_palette_16; else color_table = ff_qt_default_palette_256; for (j = 0; j < color_count; j++) { r = color_table[j * 3 + 0]; g = color_table[j * 3 + 1]; b = color_table[j * 3 + 2]; sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b); } } else { /* load the palette from the file */ color_start = avio_rb32(pb); color_count = avio_rb16(pb); color_end = avio_rb16(pb); if ((color_start <= 255) && (color_end <= 255)) { for (j = color_start; j <= color_end; j++) { /* each A, R, G, or B component is 16 bits; * only use the top 8 bits */ a = avio_r8(pb); avio_r8(pb); r = avio_r8(pb); avio_r8(pb); g = avio_r8(pb); avio_r8(pb); b = avio_r8(pb); avio_r8(pb); sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b); } } } sc->has_palette = 1; } } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) { int bits_per_sample, flags; uint16_t version = avio_rb16(pb); st->codec->codec_id = id; avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ st->codec->channels = avio_rb16(pb); /* channel count */ av_dlog(c->fc, "audio channels %d\n", st->codec->channels); st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */ sc->audio_cid = avio_rb16(pb); avio_rb16(pb); /* packet size = 0 */ st->codec->sample_rate = ((avio_rb32(pb) >> 16)); //Read QT version 1 fields. In version 0 these do not exist. av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom); if (!c->isom) { if (version==1) { sc->samples_per_frame = avio_rb32(pb); avio_rb32(pb); /* bytes per packet */ sc->bytes_per_frame = avio_rb32(pb); avio_rb32(pb); /* bytes per sample */ } else if (version==2) { avio_rb32(pb); /* sizeof struct only */ st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */ st->codec->channels = avio_rb32(pb); avio_rb32(pb); /* always 0x7F000000 */ st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */ flags = avio_rb32(pb); /* lpcm format specific flag */ sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */ sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */ if (format == MKTAG('l','p','c','m')) st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags); } } switch (st->codec->codec_id) { case CODEC_ID_PCM_S8: case CODEC_ID_PCM_U8: if (st->codec->bits_per_coded_sample == 16) st->codec->codec_id = CODEC_ID_PCM_S16BE; break; case CODEC_ID_PCM_S16LE: case CODEC_ID_PCM_S16BE: if (st->codec->bits_per_coded_sample == 8) st->codec->codec_id = CODEC_ID_PCM_S8; else if (st->codec->bits_per_coded_sample == 24) st->codec->codec_id = st->codec->codec_id == CODEC_ID_PCM_S16BE ? CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE; break; /* set values for old format before stsd version 1 appeared */ case CODEC_ID_MACE3: sc->samples_per_frame = 6; sc->bytes_per_frame = 2*st->codec->channels; break; case CODEC_ID_MACE6: sc->samples_per_frame = 6; sc->bytes_per_frame = 1*st->codec->channels; break; case CODEC_ID_ADPCM_IMA_QT: sc->samples_per_frame = 64; sc->bytes_per_frame = 34*st->codec->channels; break; case CODEC_ID_GSM: sc->samples_per_frame = 160; sc->bytes_per_frame = 33; break; default: break; } bits_per_sample = av_get_bits_per_sample(st->codec->codec_id); if (bits_per_sample) { st->codec->bits_per_coded_sample = bits_per_sample; sc->sample_size = (bits_per_sample >> 3) * st->codec->channels; } } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){ // ttxt stsd contains display flags, justification, background // color, fonts, and default styles, so fake an atom to read it MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) }; if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom mov_read_glbl(c, pb, fake_atom); st->codec->codec_id= id; st->codec->width = sc->width; st->codec->height = sc->height; } else { if (st->codec->codec_tag == MKTAG('t','m','c','d')) { MOVStreamContext *tmcd_ctx = st->priv_data; int val; avio_rb32(pb); /* reserved */ val = avio_rb32(pb); /* flags */ tmcd_ctx->tmcd_flags = val; if (val & 1) st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE; avio_rb32(pb); /* time scale */ avio_rb32(pb); /* frame duration */ st->codec->time_base.den = avio_r8(pb); /* number of frame */ st->codec->time_base.num = 1; } /* other codec type, just skip (rtp, mp4s, ...) */ avio_skip(pb, size - (avio_tell(pb) - start_pos)); } /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */ a.size = size - (avio_tell(pb) - start_pos); if (a.size > 8) { int ret; if ((ret = mov_read_default(c, pb, a)) < 0) return ret; } else if (a.size > 0) avio_skip(pb, a.size); } if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1) st->codec->sample_rate= sc->time_scale; /* special codec parameters handling */ switch (st->codec->codec_id) { #if CONFIG_DV_DEMUXER case CODEC_ID_DVAUDIO: c->dv_fctx = avformat_alloc_context(); c->dv_demux = avpriv_dv_init_demux(c->dv_fctx); if (!c->dv_demux) { av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n"); return AVERROR(ENOMEM); } sc->dv_audio_container = 1; st->codec->codec_id = CODEC_ID_PCM_S16LE; break; #endif /* no ifdef since parameters are always those */ case CODEC_ID_QCELP: // force sample rate for qcelp when not stored in mov if (st->codec->codec_tag != MKTAG('Q','c','l','p')) st->codec->sample_rate = 8000; st->codec->channels= 1; /* really needed */ break; case CODEC_ID_AMR_NB: st->codec->channels= 1; /* really needed */ /* force sample rate for amr, stsd in 3gp does not store sample rate */ st->codec->sample_rate = 8000; break; case CODEC_ID_AMR_WB: st->codec->channels = 1; st->codec->sample_rate = 16000; break; case CODEC_ID_MP2: case CODEC_ID_MP3: st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */ st->need_parsing = AVSTREAM_PARSE_FULL; break; case CODEC_ID_GSM: case CODEC_ID_ADPCM_MS: case CODEC_ID_ADPCM_IMA_WAV: st->codec->block_align = sc->bytes_per_frame; break; case CODEC_ID_ALAC: if (st->codec->extradata_size == 36) { st->codec->channels = AV_RB8 (st->codec->extradata+21); st->codec->sample_rate = AV_RB32(st->codec->extradata+32); } break; case CODEC_ID_AC3: st->need_parsing = AVSTREAM_PARSE_FULL; break; case CODEC_ID_MPEG1VIDEO: st->need_parsing = AVSTREAM_PARSE_FULL; break; default: break; } return 0; } static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int entries; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); return ff_mov_read_stsd_entries(c, pb, entries); } static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries); if (!entries) return 0; if (entries >= UINT_MAX / sizeof(*sc->stsc_data)) return AVERROR_INVALIDDATA; sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data)); if (!sc->stsc_data) return AVERROR(ENOMEM); sc->stsc_count = entries; for (i=0; i<entries; i++) { sc->stsc_data[i].first = avio_rb32(pb); sc->stsc_data[i].count = avio_rb32(pb); sc->stsc_data[i].id = avio_rb32(pb); } return 0; } static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (entries >= UINT_MAX / sizeof(*sc->stps_data)) return AVERROR_INVALIDDATA; sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data)); if (!sc->stps_data) return AVERROR(ENOMEM); sc->stps_count = entries; for (i = 0; i < entries; i++) { sc->stps_data[i] = avio_rb32(pb); //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]); } return 0; } static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_dlog(c->fc, "keyframe_count = %d\n", entries); if (!entries) { sc->keyframe_absent = 1; return 0; } if (entries >= UINT_MAX / sizeof(int)) return AVERROR_INVALIDDATA; sc->keyframes = av_malloc(entries * sizeof(int)); if (!sc->keyframes) return AVERROR(ENOMEM); sc->keyframe_count = entries; for (i=0; i<entries; i++) { sc->keyframes[i] = avio_rb32(pb); //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]); } return 0; } static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries, sample_size, field_size, num_bytes; GetBitContext gb; unsigned char* buf; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (atom.type == MKTAG('s','t','s','z')) { sample_size = avio_rb32(pb); if (!sc->sample_size) /* do not overwrite value computed in stsd */ sc->sample_size = sample_size; sc->alt_sample_size = sample_size; field_size = 32; } else { sample_size = 0; avio_rb24(pb); /* reserved */ field_size = avio_r8(pb); } entries = avio_rb32(pb); av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries); sc->sample_count = entries; if (sample_size) return 0; if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size); return AVERROR_INVALIDDATA; } if (!entries) return 0; if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size) return AVERROR_INVALIDDATA; sc->sample_sizes = av_malloc(entries * sizeof(int)); if (!sc->sample_sizes) return AVERROR(ENOMEM); num_bytes = (entries*field_size+4)>>3; buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE); if (!buf) { av_freep(&sc->sample_sizes); return AVERROR(ENOMEM); } if (avio_read(pb, buf, num_bytes) < num_bytes) { av_freep(&sc->sample_sizes); av_free(buf); return AVERROR_INVALIDDATA; } init_get_bits(&gb, buf, 8*num_bytes); for (i = 0; i < entries; i++) { sc->sample_sizes[i] = get_bits_long(&gb, field_size); sc->data_size += sc->sample_sizes[i]; } av_free(buf); return 0; } static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; int64_t duration=0; int64_t total_sample_count=0; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries); if (entries >= UINT_MAX / sizeof(*sc->stts_data)) return -1; sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data)); if (!sc->stts_data) return AVERROR(ENOMEM); sc->stts_count = entries; for (i=0; i<entries; i++) { int sample_duration; int sample_count; sample_count=avio_rb32(pb); sample_duration = avio_rb32(pb); /* sample_duration < 0 is invalid based on the spec */ if (sample_duration < 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration); sample_duration = 1; } sc->stts_data[i].count= sample_count; sc->stts_data[i].duration= sample_duration; av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n", sample_count, sample_duration); duration+=(int64_t)sample_duration*sample_count; total_sample_count+=sample_count; } st->nb_frames= total_sample_count; if (duration) st->duration= duration; sc->track_end = duration; return 0; } static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries); if (!entries) return 0; if (entries >= UINT_MAX / sizeof(*sc->ctts_data)) return AVERROR_INVALIDDATA; sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data)); if (!sc->ctts_data) return AVERROR(ENOMEM); sc->ctts_count = entries; for (i=0; i<entries; i++) { int count =avio_rb32(pb); int duration =avio_rb32(pb); sc->ctts_data[i].count = count; sc->ctts_data[i].duration= duration; if (FFABS(duration) > (1<<28) && i+2<entries) { av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n"); av_freep(&sc->ctts_data); sc->ctts_count = 0; return 0; } if (duration < 0 && i+2<entries) sc->dts_shift = FFMAX(sc->dts_shift, -duration); } av_dlog(c->fc, "dts shift %d\n", sc->dts_shift); return 0; } static void mov_build_index(MOVContext *mov, AVStream *st) { MOVStreamContext *sc = st->priv_data; int64_t current_offset; int64_t current_dts = 0; unsigned int stts_index = 0; unsigned int stsc_index = 0; unsigned int stss_index = 0; unsigned int stps_index = 0; unsigned int i, j; uint64_t stream_size = 0; AVIndexEntry *mem; /* adjust first dts according to edit list */ if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) { if (sc->empty_duration) sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale); sc->time_offset = sc->start_time - sc->empty_duration; current_dts = -sc->time_offset; if (sc->ctts_data && sc->stts_data && sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) { /* more than 16 frames delay, dts are likely wrong this happens with files created by iMovie */ sc->wrong_dts = 1; st->codec->has_b_frames = 1; } } /* only use old uncompressed audio chunk demuxing when stts specifies it */ if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && sc->stts_count == 1 && sc->stts_data[0].duration == 1)) { unsigned int current_sample = 0; unsigned int stts_sample = 0; unsigned int sample_size; unsigned int distance = 0; int key_off = sc->keyframe_count && sc->keyframes[0] == 1; current_dts -= sc->dts_shift; if (!sc->sample_count || st->nb_index_entries) return; if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries) return; mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries)); if (!mem) return; st->index_entries = mem; st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries); for (i = 0; i < sc->chunk_count; i++) { current_offset = sc->chunk_offsets[i]; while (stsc_index + 1 < sc->stsc_count && i + 1 == sc->stsc_data[stsc_index + 1].first) stsc_index++; for (j = 0; j < sc->stsc_data[stsc_index].count; j++) { int keyframe = 0; if (current_sample >= sc->sample_count) { av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n"); return; } if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) { keyframe = 1; if (stss_index + 1 < sc->keyframe_count) stss_index++; } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) { keyframe = 1; if (stps_index + 1 < sc->stps_count) stps_index++; } if (keyframe) distance = 0; sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample]; if (sc->pseudo_stream_id == -1 || sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) { AVIndexEntry *e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = sample_size; e->min_distance = distance; e->flags = keyframe ? AVINDEX_KEYFRAME : 0; av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", " "size %d, distance %d, keyframe %d\n", st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe); } current_offset += sample_size; stream_size += sample_size; current_dts += sc->stts_data[stts_index].duration; distance++; stts_sample++; current_sample++; if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) { stts_sample = 0; stts_index++; } } } if (st->duration > 0) st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration; } else { unsigned chunk_samples, total = 0; // compute total chunk count for (i = 0; i < sc->stsc_count; i++) { unsigned count, chunk_count; chunk_samples = sc->stsc_data[i].count; if (i != sc->stsc_count - 1 && sc->samples_per_frame && chunk_samples % sc->samples_per_frame) { av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n"); return; } if (sc->samples_per_frame >= 160) { // gsm count = chunk_samples / sc->samples_per_frame; } else if (sc->samples_per_frame > 1) { unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame; count = (chunk_samples+samples-1) / samples; } else { count = (chunk_samples+1023) / 1024; } if (i < sc->stsc_count - 1) chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first; else chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1); total += chunk_count * count; } av_dlog(mov->fc, "chunk count %d\n", total); if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries) return; mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries)); if (!mem) return; st->index_entries = mem; st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries); // populate index for (i = 0; i < sc->chunk_count; i++) { current_offset = sc->chunk_offsets[i]; if (stsc_index + 1 < sc->stsc_count && i + 1 == sc->stsc_data[stsc_index + 1].first) stsc_index++; chunk_samples = sc->stsc_data[stsc_index].count; while (chunk_samples > 0) { AVIndexEntry *e; unsigned size, samples; if (sc->samples_per_frame >= 160) { // gsm samples = sc->samples_per_frame; size = sc->bytes_per_frame; } else { if (sc->samples_per_frame > 1) { samples = FFMIN((1024 / sc->samples_per_frame)* sc->samples_per_frame, chunk_samples); size = (samples / sc->samples_per_frame) * sc->bytes_per_frame; } else { samples = FFMIN(1024, chunk_samples); size = samples * sc->sample_size; } } if (st->nb_index_entries >= total) { av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total); return; } e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = size; e->min_distance = 0; e->flags = AVINDEX_KEYFRAME; av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", " "size %d, duration %d\n", st->index, i, current_offset, current_dts, size, samples); current_offset += size; current_dts += samples; chunk_samples -= samples; } } } } static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref, AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc) { /* try relative path, we do not try the absolute because it can leak information about our system to an attacker */ if (ref->nlvl_to > 0 && ref->nlvl_from > 0) { char filename[1024]; const char *src_path; int i, l; /* find a source dir */ src_path = strrchr(src, '/'); if (src_path) src_path++; else src_path = src; /* find a next level down to target */ for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--) if (ref->path[l] == '/') { if (i == ref->nlvl_to - 1) break; else i++; } /* compose filename if next level down to target was found */ if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) { memcpy(filename, src, src_path - src); filename[src_path - src] = 0; for (i = 1; i < ref->nlvl_from; i++) av_strlcat(filename, "../", 1024); av_strlcat(filename, ref->path + l + 1, 1024); if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL)) return 0; } } else if (use_absolute_path) { av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, " "this is a possible security issue\n"); if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL)) return 0; } return AVERROR(ENOENT); } static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int ret; st = avformat_new_stream(c->fc, NULL); if (!st) return AVERROR(ENOMEM); st->id = c->fc->nb_streams; sc = av_mallocz(sizeof(MOVStreamContext)); if (!sc) return AVERROR(ENOMEM); st->priv_data = sc; st->codec->codec_type = AVMEDIA_TYPE_DATA; sc->ffindex = st->index; if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; /* sanity checks */ if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count || (!sc->sample_size && !sc->sample_count))) { av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n", st->index); return 0; } if (sc->time_scale <= 0) { av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index); sc->time_scale = c->time_scale; if (sc->time_scale <= 0) sc->time_scale = 1; } avpriv_set_pts_info(st, 64, 1, sc->time_scale); mov_build_index(c, st); if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) { MOVDref *dref = &sc->drefs[sc->dref_id - 1]; if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback, c->use_absolute_path, c->fc) < 0) av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening alias: path='%s', dir='%s', " "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n", st->index, dref->path, dref->dir, dref->filename, dref->volume, dref->nlvl_from, dref->nlvl_to); } else sc->pb = c->fc->pb; if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) { if (!st->sample_aspect_ratio.num && (st->codec->width != sc->width || st->codec->height != sc->height)) { st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) / ((double)st->codec->width * sc->height), INT_MAX); } av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den, sc->time_scale*st->nb_frames, st->duration, INT_MAX); if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1)) av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, sc->time_scale, sc->stts_data[0].duration, INT_MAX); } switch (st->codec->codec_id) { #if CONFIG_H261_DECODER case CODEC_ID_H261: #endif #if CONFIG_H263_DECODER case CODEC_ID_H263: #endif #if CONFIG_H264_DECODER case CODEC_ID_H264: #endif #if CONFIG_MPEG4_DECODER case CODEC_ID_MPEG4: #endif st->codec->width = 0; /* let decoder init width/height */ st->codec->height= 0; break; } /* Do not need those anymore. */ av_freep(&sc->chunk_offsets); av_freep(&sc->stsc_data); av_freep(&sc->sample_sizes); av_freep(&sc->keyframes); av_freep(&sc->stts_data); av_freep(&sc->stps_data); return 0; } static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; c->itunes_metadata = 1; ret = mov_read_default(c, pb, atom); c->itunes_metadata = 0; return ret; } static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom) { while (atom.size > 8) { uint32_t tag = avio_rl32(pb); atom.size -= 4; if (tag == MKTAG('h','d','l','r')) { avio_seek(pb, -8, SEEK_CUR); atom.size += 8; return mov_read_default(c, pb, atom); } } return 0; } static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int i; int width; int height; int64_t disp_transform[2]; int display_matrix[3][2]; AVStream *st; MOVStreamContext *sc; int version; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; version = avio_r8(pb); avio_rb24(pb); /* flags */ /* MOV_TRACK_ENABLED 0x0001 MOV_TRACK_IN_MOVIE 0x0002 MOV_TRACK_IN_PREVIEW 0x0004 MOV_TRACK_IN_POSTER 0x0008 */ if (version == 1) { avio_rb64(pb); avio_rb64(pb); } else { avio_rb32(pb); /* creation time */ avio_rb32(pb); /* modification time */ } st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/ avio_rb32(pb); /* reserved */ /* highlevel (considering edits) duration in movie timebase */ (version == 1) ? avio_rb64(pb) : avio_rb32(pb); avio_rb32(pb); /* reserved */ avio_rb32(pb); /* reserved */ avio_rb16(pb); /* layer */ avio_rb16(pb); /* alternate group */ avio_rb16(pb); /* volume */ avio_rb16(pb); /* reserved */ //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2) // they're kept in fixed point format through all calculations // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio for (i = 0; i < 3; i++) { display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point avio_rb32(pb); // 2.30 fixed point (not used) } width = avio_rb32(pb); // 16.16 fixed point track width height = avio_rb32(pb); // 16.16 fixed point track height sc->width = width >> 16; sc->height = height >> 16; //Assign clockwise rotate values based on transform matrix so that //we can compensate for iPhone orientation during capture. if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) { av_dict_set(&st->metadata, "rotate", "90", 0); } if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) { av_dict_set(&st->metadata, "rotate", "180", 0); } if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) { av_dict_set(&st->metadata, "rotate", "270", 0); } // transform the display width/height according to the matrix // skip this if the display matrix is the default identity matrix // or if it is rotating the picture, ex iPhone 3GS // to keep the same scale, use [width height 1<<16] if (width && height && ((display_matrix[0][0] != 65536 || display_matrix[1][1] != 65536) && !display_matrix[0][1] && !display_matrix[1][0] && !display_matrix[2][0] && !display_matrix[2][1])) { for (i = 0; i < 2; i++) disp_transform[i] = (int64_t) width * display_matrix[0][i] + (int64_t) height * display_matrix[1][i] + ((int64_t) display_matrix[2][i] << 16); //sample aspect ratio is new width/height divided by old width/height st->sample_aspect_ratio = av_d2q( ((double) disp_transform[0] * height) / ((double) disp_transform[1] * width), INT_MAX); } return 0; } static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; MOVTrackExt *trex = NULL; int flags, track_id, i; avio_r8(pb); /* version */ flags = avio_rb24(pb); track_id = avio_rb32(pb); if (!track_id) return AVERROR_INVALIDDATA; frag->track_id = track_id; for (i = 0; i < c->trex_count; i++) if (c->trex_data[i].track_id == frag->track_id) { trex = &c->trex_data[i]; break; } if (!trex) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n"); return AVERROR_INVALIDDATA; } frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ? avio_rb64(pb) : frag->moof_offset; frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id; frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ? avio_rb32(pb) : trex->duration; frag->size = flags & MOV_TFHD_DEFAULT_SIZE ? avio_rb32(pb) : trex->size; frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ? avio_rb32(pb) : trex->flags; av_dlog(c->fc, "frag flags 0x%x\n", frag->flags); return 0; } static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom) { c->chapter_track = avio_rb32(pb); return 0; } static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVTrackExt *trex; if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data)) return AVERROR_INVALIDDATA; trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data)); if (!trex) return AVERROR(ENOMEM); c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used. c->trex_data = trex; trex = &c->trex_data[c->trex_count++]; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ trex->track_id = avio_rb32(pb); trex->stsd_id = avio_rb32(pb); trex->duration = avio_rb32(pb); trex->size = avio_rb32(pb); trex->flags = avio_rb32(pb); return 0; } static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; AVStream *st = NULL; MOVStreamContext *sc; MOVStts *ctts_data; uint64_t offset; int64_t dts; int data_offset = 0; unsigned entries, first_sample_flags = frag->flags; int flags, distance, i, found_keyframe = 0; for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == frag->track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id); return AVERROR_INVALIDDATA; } sc = st->priv_data; if (sc->pseudo_stream_id+1 != frag->stsd_id) return 0; avio_r8(pb); /* version */ flags = avio_rb24(pb); entries = avio_rb32(pb); av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries); /* Always assume the presence of composition time offsets. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following. * 1) in the initial movie, there are no samples. * 2) in the first movie fragment, there is only one sample without composition time offset. * 3) in the subsequent movie fragments, there are samples with composition time offset. */ if (!sc->ctts_count && sc->sample_count) { /* Complement ctts table if moov atom doesn't have ctts atom. */ ctts_data = av_malloc(sizeof(*sc->ctts_data)); if (!ctts_data) return AVERROR(ENOMEM); sc->ctts_data = ctts_data; sc->ctts_data[sc->ctts_count].count = sc->sample_count; sc->ctts_data[sc->ctts_count].duration = 0; sc->ctts_count++; } if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data)) return AVERROR_INVALIDDATA; ctts_data = av_realloc(sc->ctts_data, (entries+sc->ctts_count)*sizeof(*sc->ctts_data)); if (!ctts_data) return AVERROR(ENOMEM); sc->ctts_data = ctts_data; if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb); if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb); dts = sc->track_end - sc->time_offset; offset = frag->base_data_offset + data_offset; distance = 0; av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags); for (i = 0; i < entries; i++) { unsigned sample_size = frag->size; int sample_flags = i ? frag->flags : first_sample_flags; unsigned sample_duration = frag->duration; int keyframe = 0; if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb); sc->ctts_data[sc->ctts_count].count = 1; sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ? avio_rb32(pb) : 0; sc->ctts_count++; if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) keyframe = 1; else if (!found_keyframe) keyframe = found_keyframe = !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC | MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES)); if (keyframe) distance = 0; av_add_index_entry(st, offset, dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0); av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", " "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i, offset, dts, sample_size, distance, keyframe); distance++; dts += sample_duration; offset += sample_size; sc->data_size += sample_size; } frag->moof_offset = offset; st->duration = sc->track_end = dts + sc->time_offset; return 0; } /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */ /* like the files created with Adobe Premiere 5.0, for samples see */ /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */ static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int err; if (atom.size < 8) return 0; /* continue */ if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */ avio_skip(pb, atom.size - 4); return 0; } atom.type = avio_rl32(pb); atom.size -= 8; if (atom.type != MKTAG('m','d','a','t')) { avio_skip(pb, atom.size); return 0; } err = mov_read_mdat(c, pb, atom); return err; } static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom) { #if CONFIG_ZLIB AVIOContext ctx; uint8_t *cmov_data; uint8_t *moov_data; /* uncompressed data */ long cmov_len, moov_len; int ret = -1; avio_rb32(pb); /* dcom atom */ if (avio_rl32(pb) != MKTAG('d','c','o','m')) return AVERROR_INVALIDDATA; if (avio_rl32(pb) != MKTAG('z','l','i','b')) { av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !"); return AVERROR_INVALIDDATA; } avio_rb32(pb); /* cmvd atom */ if (avio_rl32(pb) != MKTAG('c','m','v','d')) return AVERROR_INVALIDDATA; moov_len = avio_rb32(pb); /* uncompressed size */ cmov_len = atom.size - 6 * 4; cmov_data = av_malloc(cmov_len); if (!cmov_data) return AVERROR(ENOMEM); moov_data = av_malloc(moov_len); if (!moov_data) { av_free(cmov_data); return AVERROR(ENOMEM); } avio_read(pb, cmov_data, cmov_len); if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK) goto free_and_return; if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0) goto free_and_return; atom.type = MKTAG('m','o','o','v'); atom.size = moov_len; ret = mov_read_default(c, &ctx, atom); free_and_return: av_free(moov_data); av_free(cmov_data); return ret; #else av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n"); return AVERROR(ENOSYS); #endif } /* edit list atom */ static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; int i, edit_count, version, edit_start_index = 0; if (c->fc->nb_streams < 1) return 0; sc = c->fc->streams[c->fc->nb_streams-1]->priv_data; version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ edit_count = avio_rb32(pb); /* entries */ if ((uint64_t)edit_count*12+8 > atom.size) return AVERROR_INVALIDDATA; for (i=0; i<edit_count; i++){ int64_t time; int64_t duration; if (version == 1) { duration = avio_rb64(pb); time = avio_rb64(pb); } else { duration = avio_rb32(pb); /* segment duration */ time = (int32_t)avio_rb32(pb); /* media time */ } avio_rb32(pb); /* Media rate */ if (i == 0 && time == -1) { sc->empty_duration = duration; edit_start_index = 1; } else if (i == edit_start_index && time >= 0) sc->start_time = time; } if (edit_count > 1) av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, " "a/v desync might occur, patch welcome\n"); av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count); return 0; } static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (atom.size < 16) return 0; avio_skip(pb, 4); ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec); return 0; } static const MOVParseTableEntry mov_default_parse_table[] = { { MKTAG('a','v','s','s'), mov_read_avss }, { MKTAG('c','h','p','l'), mov_read_chpl }, { MKTAG('c','o','6','4'), mov_read_stco }, { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */ { MKTAG('d','i','n','f'), mov_read_default }, { MKTAG('d','r','e','f'), mov_read_dref }, { MKTAG('e','d','t','s'), mov_read_default }, { MKTAG('e','l','s','t'), mov_read_elst }, { MKTAG('e','n','d','a'), mov_read_enda }, { MKTAG('f','i','e','l'), mov_read_fiel }, { MKTAG('f','t','y','p'), mov_read_ftyp }, { MKTAG('g','l','b','l'), mov_read_glbl }, { MKTAG('h','d','l','r'), mov_read_hdlr }, { MKTAG('i','l','s','t'), mov_read_ilst }, { MKTAG('j','p','2','h'), mov_read_jp2h }, { MKTAG('m','d','a','t'), mov_read_mdat }, { MKTAG('m','d','h','d'), mov_read_mdhd }, { MKTAG('m','d','i','a'), mov_read_default }, { MKTAG('m','e','t','a'), mov_read_meta }, { MKTAG('m','i','n','f'), mov_read_default }, { MKTAG('m','o','o','f'), mov_read_moof }, { MKTAG('m','o','o','v'), mov_read_moov }, { MKTAG('m','v','e','x'), mov_read_default }, { MKTAG('m','v','h','d'), mov_read_mvhd }, { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */ { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */ { MKTAG('a','v','c','C'), mov_read_glbl }, { MKTAG('p','a','s','p'), mov_read_pasp }, { MKTAG('s','t','b','l'), mov_read_default }, { MKTAG('s','t','c','o'), mov_read_stco }, { MKTAG('s','t','p','s'), mov_read_stps }, { MKTAG('s','t','r','f'), mov_read_strf }, { MKTAG('s','t','s','c'), mov_read_stsc }, { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */ { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */ { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */ { MKTAG('s','t','t','s'), mov_read_stts }, { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */ { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */ { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */ { MKTAG('t','r','a','k'), mov_read_trak }, { MKTAG('t','r','a','f'), mov_read_default }, { MKTAG('t','r','e','f'), mov_read_default }, { MKTAG('c','h','a','p'), mov_read_chap }, { MKTAG('t','r','e','x'), mov_read_trex }, { MKTAG('t','r','u','n'), mov_read_trun }, { MKTAG('u','d','t','a'), mov_read_default }, { MKTAG('w','a','v','e'), mov_read_wave }, { MKTAG('e','s','d','s'), mov_read_esds }, { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */ { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */ { MKTAG('w','f','e','x'), mov_read_wfex }, { MKTAG('c','m','o','v'), mov_read_cmov }, { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */ { MKTAG('d','v','c','1'), mov_read_dvc1 }, { 0, NULL } }; static int mov_probe(AVProbeData *p) { unsigned int offset; uint32_t tag; int score = 0; /* check file header */ offset = 0; for (;;) { /* ignore invalid offset */ if ((offset + 8) > (unsigned int)p->buf_size) return score; tag = AV_RL32(p->buf + offset + 4); switch(tag) { /* check for obvious tags */ case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */ case MKTAG('m','o','o','v'): case MKTAG('m','d','a','t'): case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */ case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */ case MKTAG('f','t','y','p'): return AVPROBE_SCORE_MAX; /* those are more common words, so rate then a bit less */ case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */ case MKTAG('w','i','d','e'): case MKTAG('f','r','e','e'): case MKTAG('j','u','n','k'): case MKTAG('p','i','c','t'): return AVPROBE_SCORE_MAX - 5; case MKTAG(0x82,0x82,0x7f,0x7d): case MKTAG('s','k','i','p'): case MKTAG('u','u','i','d'): case MKTAG('p','r','f','l'): offset = AV_RB32(p->buf+offset) + offset; /* if we only find those cause probedata is too small at least rate them */ score = AVPROBE_SCORE_MAX - 50; break; default: /* unrecognized tag */ return score; } } } // must be done after parsing all trak because there's no order requirement static void mov_read_chapters(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVStream *st = NULL; MOVStreamContext *sc; int64_t cur_pos; int i; for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->id == mov->chapter_track) { st = s->streams[i]; break; } if (!st) { av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n"); return; } st->discard = AVDISCARD_ALL; sc = st->priv_data; cur_pos = avio_tell(sc->pb); for (i = 0; i < st->nb_index_entries; i++) { AVIndexEntry *sample = &st->index_entries[i]; int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration; uint8_t *title; uint16_t ch; int len, title_len; if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i); goto finish; } // the first two bytes are the length of the title len = avio_rb16(sc->pb); if (len > sample->size-2) continue; title_len = 2*len + 1; if (!(title = av_mallocz(title_len))) goto finish; // The samples could theoretically be in any encoding if there's an encd // atom following, but in practice are only utf-8 or utf-16, distinguished // instead by the presence of a BOM if (!len) { title[0] = 0; } else { ch = avio_rb16(sc->pb); if (ch == 0xfeff) avio_get_str16be(sc->pb, len, title, title_len); else if (ch == 0xfffe) avio_get_str16le(sc->pb, len, title, title_len); else { AV_WB16(title, ch); if (len == 1 || len == 2) title[len] = 0; else avio_get_str(sc->pb, INT_MAX, title + 2, len - 1); } } avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title); av_freep(&title); } finish: avio_seek(sc->pb, cur_pos, SEEK_SET); } static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st, uint32_t value, int flags) { AVTimecode tc; char buf[AV_TIMECODE_STR_SIZE]; AVRational rate = {st->codec->time_base.den, st->codec->time_base.num}; int ret = av_timecode_init(&tc, rate, flags, 0, s); if (ret < 0) return ret; av_dict_set(&st->metadata, "timecode", av_timecode_make_string(&tc, buf, value), 0); return 0; } static int mov_read_timecode_track(AVFormatContext *s, AVStream *st) { MOVStreamContext *sc = st->priv_data; int flags = 0; int64_t cur_pos = avio_tell(sc->pb); uint32_t value; if (!st->nb_index_entries) return -1; avio_seek(sc->pb, st->index_entries->pos, SEEK_SET); value = avio_rb32(s->pb); if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME; if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX; if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE; /* Assume Counter flag is set to 1 in tmcd track (even though it is likely * not the case) and thus assume "frame number format" instead of QT one. * No sample with tmcd track can be found with a QT timecode at the moment, * despite what the tmcd track "suggests" (Counter flag set to 0 means QT * format). */ parse_timecode_in_framenum_format(s, st, value, flags); avio_seek(sc->pb, cur_pos, SEEK_SET); return 0; } static int mov_read_close(AVFormatContext *s) { MOVContext *mov = s->priv_data; int i, j; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; av_freep(&sc->ctts_data); for (j = 0; j < sc->drefs_count; j++) { av_freep(&sc->drefs[j].path); av_freep(&sc->drefs[j].dir); } av_freep(&sc->drefs); if (sc->pb && sc->pb != s->pb) avio_close(sc->pb); sc->pb = NULL; av_freep(&sc->chunk_offsets); av_freep(&sc->keyframes); av_freep(&sc->sample_sizes); av_freep(&sc->stps_data); av_freep(&sc->stsc_data); av_freep(&sc->stts_data); } if (mov->dv_demux) { for (i = 0; i < mov->dv_fctx->nb_streams; i++) { av_freep(&mov->dv_fctx->streams[i]->codec); av_freep(&mov->dv_fctx->streams[i]); } av_freep(&mov->dv_fctx); av_freep(&mov->dv_demux); } av_freep(&mov->trex_data); return 0; } static int mov_read_header(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVIOContext *pb = s->pb; int err; MOVAtom atom = { AV_RL32("root") }; mov->fc = s; /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */ if (pb->seekable) atom.size = avio_size(pb); else atom.size = INT64_MAX; /* check MOV header */ if ((err = mov_read_default(mov, pb, atom)) < 0) { av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err); mov_read_close(s); return err; } if (!mov->found_moov) { av_log(s, AV_LOG_ERROR, "moov atom not found\n"); mov_read_close(s); return AVERROR_INVALIDDATA; } av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb)); if (pb->seekable) { int i; if (mov->chapter_track > 0) mov_read_chapters(s); for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd")) mov_read_timecode_track(s, s->streams[i]); } if (mov->trex_data) { int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (st->duration) st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration; } } return 0; } static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st) { AVIndexEntry *sample = NULL; int64_t best_dts = INT64_MAX; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *avst = s->streams[i]; MOVStreamContext *msc = avst->priv_data; if (msc->pb && msc->current_sample < avst->nb_index_entries) { AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample]; int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale); av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts); if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) || (s->pb->seekable && ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) || (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) { sample = current_sample; best_dts = dts; *st = avst; } } } return sample; } static int mov_read_packet(AVFormatContext *s, AVPacket *pkt) { MOVContext *mov = s->priv_data; MOVStreamContext *sc; AVIndexEntry *sample; AVStream *st = NULL; int ret; mov->fc = s; retry: sample = mov_find_next_sample(s, &st); if (!sample) { mov->found_mdat = 0; if (!mov->next_root_atom) return AVERROR_EOF; avio_seek(s->pb, mov->next_root_atom, SEEK_SET); mov->next_root_atom = 0; if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 || url_feof(s->pb)) return AVERROR_EOF; av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb)); goto retry; } sc = st->priv_data; /* must be done just before reading, to avoid infinite loop on sample */ sc->current_sample++; if (st->discard != AVDISCARD_ALL) { if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n", sc->ffindex, sample->pos); return AVERROR_INVALIDDATA; } ret = av_get_packet(sc->pb, pkt, sample->size); if (ret < 0) return ret; if (sc->has_palette) { uint8_t *pal; pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); if (!pal) { av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n"); } else { memcpy(pal, sc->palette, AVPALETTE_SIZE); sc->has_palette = 0; } } #if CONFIG_DV_DEMUXER if (mov->dv_demux && sc->dv_audio_container) { avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos); av_free(pkt->data); pkt->size = 0; ret = avpriv_dv_get_packet(mov->dv_demux, pkt); if (ret < 0) return ret; } #endif } pkt->stream_index = sc->ffindex; pkt->dts = sample->timestamp; if (sc->ctts_data && sc->ctts_index < sc->ctts_count) { pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration; /* update ctts context */ sc->ctts_sample++; if (sc->ctts_index < sc->ctts_count && sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) { sc->ctts_index++; sc->ctts_sample = 0; } if (sc->wrong_dts) pkt->dts = AV_NOPTS_VALUE; } else { int64_t next_dts = (sc->current_sample < st->nb_index_entries) ? st->index_entries[sc->current_sample].timestamp : st->duration; pkt->duration = next_dts - pkt->dts; pkt->pts = pkt->dts; } if (st->discard == AVDISCARD_ALL) goto retry; pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0; pkt->pos = sample->pos; av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n", pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration); return 0; } static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags) { MOVStreamContext *sc = st->priv_data; int sample, time_sample; int i; sample = av_index_search_timestamp(st, timestamp, flags); av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample); if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp) sample = 0; if (sample < 0) /* not sure what to do */ return AVERROR_INVALIDDATA; sc->current_sample = sample; av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample); /* adjust ctts index */ if (sc->ctts_data) { time_sample = 0; for (i = 0; i < sc->ctts_count; i++) { int next = time_sample + sc->ctts_data[i].count; if (next > sc->current_sample) { sc->ctts_index = i; sc->ctts_sample = sc->current_sample - time_sample; break; } time_sample = next; } } return sample; } static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st; int64_t seek_timestamp, timestamp; int sample; int i; if (stream_index >= s->nb_streams) return AVERROR_INVALIDDATA; if (sample_time < 0) sample_time = 0; st = s->streams[stream_index]; sample = mov_seek_stream(s, st, sample_time, flags); if (sample < 0) return sample; /* adjust seek timestamp to found sample timestamp */ seek_timestamp = st->index_entries[sample].timestamp; for (i = 0; i < s->nb_streams; i++) { st = s->streams[i]; if (stream_index == i) continue; timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base); mov_seek_stream(s, st, timestamp, flags); } return 0; } static const AVOption options[] = { {"use_absolute_path", "allow using absolute path when opening alias, this is a possible security issue", offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM}, {NULL} }; static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT}; AVInputFormat ff_mov_demuxer = { .name = "mov,mp4,m4a,3gp,3g2,mj2", .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"), .priv_data_size = sizeof(MOVContext), .read_probe = mov_probe, .read_header = mov_read_header, .read_packet = mov_read_packet, .read_close = mov_read_close, .read_seek = mov_read_seek, .priv_class = &class, };
./CrossVul/dataset_final_sorted/CWE-119/c/good_4985_0
crossvul-cpp_data_good_3310_0
/* dvb-usb-firmware.c is part of the DVB USB library. * * Copyright (C) 2004-6 Patrick Boettcher (patrick.boettcher@posteo.de) * see dvb-usb-init.c for copyright information. * * This file contains functions for downloading the firmware to Cypress FX 1 and 2 based devices. * * FIXME: This part does actually not belong to dvb-usb, but to the usb-subsystem. */ #include "dvb-usb-common.h" #include <linux/usb.h> struct usb_cypress_controller { int id; const char *name; /* name of the usb controller */ u16 cpu_cs_register; /* needs to be restarted, when the firmware has been downloaded. */ }; static struct usb_cypress_controller cypress[] = { { .id = DEVICE_SPECIFIC, .name = "Device specific", .cpu_cs_register = 0 }, { .id = CYPRESS_AN2135, .name = "Cypress AN2135", .cpu_cs_register = 0x7f92 }, { .id = CYPRESS_AN2235, .name = "Cypress AN2235", .cpu_cs_register = 0x7f92 }, { .id = CYPRESS_FX2, .name = "Cypress FX2", .cpu_cs_register = 0xe600 }, }; /* * load a firmware packet to the device */ static int usb_cypress_writemem(struct usb_device *udev,u16 addr,u8 *data, u8 len) { return usb_control_msg(udev, usb_sndctrlpipe(udev,0), 0xa0, USB_TYPE_VENDOR, addr, 0x00, data, len, 5000); } int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type) { struct hexline *hx; u8 *buf; int ret, pos = 0; u16 cpu_cs_register = cypress[type].cpu_cs_register; buf = kmalloc(sizeof(*hx), GFP_KERNEL); if (!buf) return -ENOMEM; hx = (struct hexline *)buf; /* stop the CPU */ buf[0] = 1; if (usb_cypress_writemem(udev, cpu_cs_register, buf, 1) != 1) err("could not stop the USB controller CPU."); while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) { deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk); ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len); if (ret != hx->len) { err("error while transferring firmware (transferred size: %d, block size: %d)", ret, hx->len); ret = -EINVAL; break; } } if (ret < 0) { err("firmware download failed at %d with %d",pos,ret); kfree(buf); return ret; } if (ret == 0) { /* restart the CPU */ buf[0] = 0; if (usb_cypress_writemem(udev, cpu_cs_register, buf, 1) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } } else ret = -EIO; kfree(buf); return ret; } EXPORT_SYMBOL(usb_cypress_load_firmware); int dvb_usb_download_firmware(struct usb_device *udev, struct dvb_usb_device_properties *props) { int ret; const struct firmware *fw = NULL; if ((ret = request_firmware(&fw, props->firmware, &udev->dev)) != 0) { err("did not find the firmware file. (%s) Please see linux/Documentation/dvb/ for more details on firmware-problems. (%d)", props->firmware,ret); return ret; } info("downloading firmware from file '%s'",props->firmware); switch (props->usb_ctrl) { case CYPRESS_AN2135: case CYPRESS_AN2235: case CYPRESS_FX2: ret = usb_cypress_load_firmware(udev, fw, props->usb_ctrl); break; case DEVICE_SPECIFIC: if (props->download_firmware) ret = props->download_firmware(udev,fw); else { err("BUG: driver didn't specified a download_firmware-callback, although it claims to have a DEVICE_SPECIFIC one."); ret = -EINVAL; } break; default: ret = -EINVAL; break; } release_firmware(fw); return ret; } int dvb_usb_get_hexline(const struct firmware *fw, struct hexline *hx, int *pos) { u8 *b = (u8 *) &fw->data[*pos]; int data_offs = 4; if (*pos >= fw->size) return 0; memset(hx,0,sizeof(struct hexline)); hx->len = b[0]; if ((*pos + hx->len + 4) >= fw->size) return -EINVAL; hx->addr = b[1] | (b[2] << 8); hx->type = b[3]; if (hx->type == 0x04) { /* b[4] and b[5] are the Extended linear address record data field */ hx->addr |= (b[4] << 24) | (b[5] << 16); /* hx->len -= 2; data_offs += 2; */ } memcpy(hx->data,&b[data_offs],hx->len); hx->chk = b[hx->len + data_offs]; *pos += hx->len + 5; return *pos; } EXPORT_SYMBOL(dvb_usb_get_hexline);
./CrossVul/dataset_final_sorted/CWE-119/c/good_3310_0
crossvul-cpp_data_bad_2413_0
/* * inode.c * * PURPOSE * Inode handling routines for the OSTA-UDF(tm) filesystem. * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. * * (C) 1998 Dave Boynton * (C) 1998-2004 Ben Fennema * (C) 1999-2000 Stelias Computing Inc * * HISTORY * * 10/04/98 dgb Added rudimentary directory functions * 10/07/98 Fully working udf_block_map! It works! * 11/25/98 bmap altered to better support extents * 12/06/98 blf partition support in udf_iget, udf_block_map * and udf_read_inode * 12/12/98 rewrote udf_block_map to handle next extents and descs across * block boundaries (which is not actually allowed) * 12/20/98 added support for strategy 4096 * 03/07/99 rewrote udf_block_map (again) * New funcs, inode_bmap, udf_next_aext * 04/19/99 Support for writing device EA's for major/minor # */ #include "udfdecl.h" #include <linux/mm.h> #include <linux/module.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/writeback.h> #include <linux/slab.h> #include <linux/crc-itu-t.h> #include <linux/mpage.h> #include <linux/aio.h> #include "udf_i.h" #include "udf_sb.h" MODULE_AUTHOR("Ben Fennema"); MODULE_DESCRIPTION("Universal Disk Format Filesystem"); MODULE_LICENSE("GPL"); #define EXTENT_MERGE_SIZE 5 static umode_t udf_convert_permissions(struct fileEntry *); static int udf_update_inode(struct inode *, int); static int udf_sync_inode(struct inode *inode); static int udf_alloc_i_data(struct inode *inode, size_t size); static sector_t inode_getblk(struct inode *, sector_t, int *, int *); static int8_t udf_insert_aext(struct inode *, struct extent_position, struct kernel_lb_addr, uint32_t); static void udf_split_extents(struct inode *, int *, int, int, struct kernel_long_ad[EXTENT_MERGE_SIZE], int *); static void udf_prealloc_extents(struct inode *, int, int, struct kernel_long_ad[EXTENT_MERGE_SIZE], int *); static void udf_merge_extents(struct inode *, struct kernel_long_ad[EXTENT_MERGE_SIZE], int *); static void udf_update_extents(struct inode *, struct kernel_long_ad[EXTENT_MERGE_SIZE], int, int, struct extent_position *); static int udf_get_block(struct inode *, sector_t, struct buffer_head *, int); static void __udf_clear_extent_cache(struct inode *inode) { struct udf_inode_info *iinfo = UDF_I(inode); if (iinfo->cached_extent.lstart != -1) { brelse(iinfo->cached_extent.epos.bh); iinfo->cached_extent.lstart = -1; } } /* Invalidate extent cache */ static void udf_clear_extent_cache(struct inode *inode) { struct udf_inode_info *iinfo = UDF_I(inode); spin_lock(&iinfo->i_extent_cache_lock); __udf_clear_extent_cache(inode); spin_unlock(&iinfo->i_extent_cache_lock); } /* Return contents of extent cache */ static int udf_read_extent_cache(struct inode *inode, loff_t bcount, loff_t *lbcount, struct extent_position *pos) { struct udf_inode_info *iinfo = UDF_I(inode); int ret = 0; spin_lock(&iinfo->i_extent_cache_lock); if ((iinfo->cached_extent.lstart <= bcount) && (iinfo->cached_extent.lstart != -1)) { /* Cache hit */ *lbcount = iinfo->cached_extent.lstart; memcpy(pos, &iinfo->cached_extent.epos, sizeof(struct extent_position)); if (pos->bh) get_bh(pos->bh); ret = 1; } spin_unlock(&iinfo->i_extent_cache_lock); return ret; } /* Add extent to extent cache */ static void udf_update_extent_cache(struct inode *inode, loff_t estart, struct extent_position *pos, int next_epos) { struct udf_inode_info *iinfo = UDF_I(inode); spin_lock(&iinfo->i_extent_cache_lock); /* Invalidate previously cached extent */ __udf_clear_extent_cache(inode); if (pos->bh) get_bh(pos->bh); memcpy(&iinfo->cached_extent.epos, pos, sizeof(struct extent_position)); iinfo->cached_extent.lstart = estart; if (next_epos) switch (iinfo->i_alloc_type) { case ICBTAG_FLAG_AD_SHORT: iinfo->cached_extent.epos.offset -= sizeof(struct short_ad); break; case ICBTAG_FLAG_AD_LONG: iinfo->cached_extent.epos.offset -= sizeof(struct long_ad); } spin_unlock(&iinfo->i_extent_cache_lock); } void udf_evict_inode(struct inode *inode) { struct udf_inode_info *iinfo = UDF_I(inode); int want_delete = 0; if (!inode->i_nlink && !is_bad_inode(inode)) { want_delete = 1; udf_setsize(inode, 0); udf_update_inode(inode, IS_SYNC(inode)); } truncate_inode_pages_final(&inode->i_data); invalidate_inode_buffers(inode); clear_inode(inode); if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB && inode->i_size != iinfo->i_lenExtents) { udf_warn(inode->i_sb, "Inode %lu (mode %o) has inode size %llu different from extent length %llu. Filesystem need not be standards compliant.\n", inode->i_ino, inode->i_mode, (unsigned long long)inode->i_size, (unsigned long long)iinfo->i_lenExtents); } kfree(iinfo->i_ext.i_data); iinfo->i_ext.i_data = NULL; udf_clear_extent_cache(inode); if (want_delete) { udf_free_inode(inode); } } static void udf_write_failed(struct address_space *mapping, loff_t to) { struct inode *inode = mapping->host; struct udf_inode_info *iinfo = UDF_I(inode); loff_t isize = inode->i_size; if (to > isize) { truncate_pagecache(inode, isize); if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); udf_truncate_extents(inode); up_write(&iinfo->i_data_sem); } } } static int udf_writepage(struct page *page, struct writeback_control *wbc) { return block_write_full_page(page, udf_get_block, wbc); } static int udf_writepages(struct address_space *mapping, struct writeback_control *wbc) { return mpage_writepages(mapping, wbc, udf_get_block); } static int udf_readpage(struct file *file, struct page *page) { return mpage_readpage(page, udf_get_block); } static int udf_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { return mpage_readpages(mapping, pages, nr_pages, udf_get_block); } static int udf_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { int ret; ret = block_write_begin(mapping, pos, len, flags, pagep, udf_get_block); if (unlikely(ret)) udf_write_failed(mapping, pos + len); return ret; } static ssize_t udf_direct_IO(int rw, struct kiocb *iocb, struct iov_iter *iter, loff_t offset) { struct file *file = iocb->ki_filp; struct address_space *mapping = file->f_mapping; struct inode *inode = mapping->host; size_t count = iov_iter_count(iter); ssize_t ret; ret = blockdev_direct_IO(rw, iocb, inode, iter, offset, udf_get_block); if (unlikely(ret < 0 && (rw & WRITE))) udf_write_failed(mapping, offset + count); return ret; } static sector_t udf_bmap(struct address_space *mapping, sector_t block) { return generic_block_bmap(mapping, block, udf_get_block); } const struct address_space_operations udf_aops = { .readpage = udf_readpage, .readpages = udf_readpages, .writepage = udf_writepage, .writepages = udf_writepages, .write_begin = udf_write_begin, .write_end = generic_write_end, .direct_IO = udf_direct_IO, .bmap = udf_bmap, }; /* * Expand file stored in ICB to a normal one-block-file * * This function requires i_data_sem for writing and releases it. * This function requires i_mutex held */ int udf_expand_file_adinicb(struct inode *inode) { struct page *page; char *kaddr; struct udf_inode_info *iinfo = UDF_I(inode); int err; struct writeback_control udf_wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, }; WARN_ON_ONCE(!mutex_is_locked(&inode->i_mutex)); if (!iinfo->i_lenAlloc) { if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; /* from now on we have normal address_space methods */ inode->i_data.a_ops = &udf_aops; up_write(&iinfo->i_data_sem); mark_inode_dirty(inode); return 0; } /* * Release i_data_sem so that we can lock a page - page lock ranks * above i_data_sem. i_mutex still protects us against file changes. */ up_write(&iinfo->i_data_sem); page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS); if (!page) return -ENOMEM; if (!PageUptodate(page)) { kaddr = kmap(page); memset(kaddr + iinfo->i_lenAlloc, 0x00, PAGE_CACHE_SIZE - iinfo->i_lenAlloc); memcpy(kaddr, iinfo->i_ext.i_data + iinfo->i_lenEAttr, iinfo->i_lenAlloc); flush_dcache_page(page); SetPageUptodate(page); kunmap(page); } down_write(&iinfo->i_data_sem); memset(iinfo->i_ext.i_data + iinfo->i_lenEAttr, 0x00, iinfo->i_lenAlloc); iinfo->i_lenAlloc = 0; if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; /* from now on we have normal address_space methods */ inode->i_data.a_ops = &udf_aops; up_write(&iinfo->i_data_sem); err = inode->i_data.a_ops->writepage(page, &udf_wbc); if (err) { /* Restore everything back so that we don't lose data... */ lock_page(page); kaddr = kmap(page); down_write(&iinfo->i_data_sem); memcpy(iinfo->i_ext.i_data + iinfo->i_lenEAttr, kaddr, inode->i_size); kunmap(page); unlock_page(page); iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB; inode->i_data.a_ops = &udf_adinicb_aops; up_write(&iinfo->i_data_sem); } page_cache_release(page); mark_inode_dirty(inode); return err; } struct buffer_head *udf_expand_dir_adinicb(struct inode *inode, int *block, int *err) { int newblock; struct buffer_head *dbh = NULL; struct kernel_lb_addr eloc; uint8_t alloctype; struct extent_position epos; struct udf_fileident_bh sfibh, dfibh; loff_t f_pos = udf_ext0_offset(inode); int size = udf_ext0_offset(inode) + inode->i_size; struct fileIdentDesc cfi, *sfi, *dfi; struct udf_inode_info *iinfo = UDF_I(inode); if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD)) alloctype = ICBTAG_FLAG_AD_SHORT; else alloctype = ICBTAG_FLAG_AD_LONG; if (!inode->i_size) { iinfo->i_alloc_type = alloctype; mark_inode_dirty(inode); return NULL; } /* alloc block, and copy data to it */ *block = udf_new_block(inode->i_sb, inode, iinfo->i_location.partitionReferenceNum, iinfo->i_location.logicalBlockNum, err); if (!(*block)) return NULL; newblock = udf_get_pblock(inode->i_sb, *block, iinfo->i_location.partitionReferenceNum, 0); if (!newblock) return NULL; dbh = udf_tgetblk(inode->i_sb, newblock); if (!dbh) return NULL; lock_buffer(dbh); memset(dbh->b_data, 0x00, inode->i_sb->s_blocksize); set_buffer_uptodate(dbh); unlock_buffer(dbh); mark_buffer_dirty_inode(dbh, inode); sfibh.soffset = sfibh.eoffset = f_pos & (inode->i_sb->s_blocksize - 1); sfibh.sbh = sfibh.ebh = NULL; dfibh.soffset = dfibh.eoffset = 0; dfibh.sbh = dfibh.ebh = dbh; while (f_pos < size) { iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB; sfi = udf_fileident_read(inode, &f_pos, &sfibh, &cfi, NULL, NULL, NULL, NULL); if (!sfi) { brelse(dbh); return NULL; } iinfo->i_alloc_type = alloctype; sfi->descTag.tagLocation = cpu_to_le32(*block); dfibh.soffset = dfibh.eoffset; dfibh.eoffset += (sfibh.eoffset - sfibh.soffset); dfi = (struct fileIdentDesc *)(dbh->b_data + dfibh.soffset); if (udf_write_fi(inode, sfi, dfi, &dfibh, sfi->impUse, sfi->fileIdent + le16_to_cpu(sfi->lengthOfImpUse))) { iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB; brelse(dbh); return NULL; } } mark_buffer_dirty_inode(dbh, inode); memset(iinfo->i_ext.i_data + iinfo->i_lenEAttr, 0, iinfo->i_lenAlloc); iinfo->i_lenAlloc = 0; eloc.logicalBlockNum = *block; eloc.partitionReferenceNum = iinfo->i_location.partitionReferenceNum; iinfo->i_lenExtents = inode->i_size; epos.bh = NULL; epos.block = iinfo->i_location; epos.offset = udf_file_entry_alloc_offset(inode); udf_add_aext(inode, &epos, &eloc, inode->i_size, 0); /* UniqueID stuff */ brelse(epos.bh); mark_inode_dirty(inode); return dbh; } static int udf_get_block(struct inode *inode, sector_t block, struct buffer_head *bh_result, int create) { int err, new; sector_t phys = 0; struct udf_inode_info *iinfo; if (!create) { phys = udf_block_map(inode, block); if (phys) map_bh(bh_result, inode->i_sb, phys); return 0; } err = -EIO; new = 0; iinfo = UDF_I(inode); down_write(&iinfo->i_data_sem); if (block == iinfo->i_next_alloc_block + 1) { iinfo->i_next_alloc_block++; iinfo->i_next_alloc_goal++; } udf_clear_extent_cache(inode); phys = inode_getblk(inode, block, &err, &new); if (!phys) goto abort; if (new) set_buffer_new(bh_result); map_bh(bh_result, inode->i_sb, phys); abort: up_write(&iinfo->i_data_sem); return err; } static struct buffer_head *udf_getblk(struct inode *inode, long block, int create, int *err) { struct buffer_head *bh; struct buffer_head dummy; dummy.b_state = 0; dummy.b_blocknr = -1000; *err = udf_get_block(inode, block, &dummy, create); if (!*err && buffer_mapped(&dummy)) { bh = sb_getblk(inode->i_sb, dummy.b_blocknr); if (buffer_new(&dummy)) { lock_buffer(bh); memset(bh->b_data, 0x00, inode->i_sb->s_blocksize); set_buffer_uptodate(bh); unlock_buffer(bh); mark_buffer_dirty_inode(bh, inode); } return bh; } return NULL; } /* Extend the file by 'blocks' blocks, return the number of extents added */ static int udf_do_extend_file(struct inode *inode, struct extent_position *last_pos, struct kernel_long_ad *last_ext, sector_t blocks) { sector_t add; int count = 0, fake = !(last_ext->extLength & UDF_EXTENT_LENGTH_MASK); struct super_block *sb = inode->i_sb; struct kernel_lb_addr prealloc_loc = {}; int prealloc_len = 0; struct udf_inode_info *iinfo; int err; /* The previous extent is fake and we should not extend by anything * - there's nothing to do... */ if (!blocks && fake) return 0; iinfo = UDF_I(inode); /* Round the last extent up to a multiple of block size */ if (last_ext->extLength & (sb->s_blocksize - 1)) { last_ext->extLength = (last_ext->extLength & UDF_EXTENT_FLAG_MASK) | (((last_ext->extLength & UDF_EXTENT_LENGTH_MASK) + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1)); iinfo->i_lenExtents = (iinfo->i_lenExtents + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1); } /* Last extent are just preallocated blocks? */ if ((last_ext->extLength & UDF_EXTENT_FLAG_MASK) == EXT_NOT_RECORDED_ALLOCATED) { /* Save the extent so that we can reattach it to the end */ prealloc_loc = last_ext->extLocation; prealloc_len = last_ext->extLength; /* Mark the extent as a hole */ last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (last_ext->extLength & UDF_EXTENT_LENGTH_MASK); last_ext->extLocation.logicalBlockNum = 0; last_ext->extLocation.partitionReferenceNum = 0; } /* Can we merge with the previous extent? */ if ((last_ext->extLength & UDF_EXTENT_FLAG_MASK) == EXT_NOT_RECORDED_NOT_ALLOCATED) { add = ((1 << 30) - sb->s_blocksize - (last_ext->extLength & UDF_EXTENT_LENGTH_MASK)) >> sb->s_blocksize_bits; if (add > blocks) add = blocks; blocks -= add; last_ext->extLength += add << sb->s_blocksize_bits; } if (fake) { udf_add_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); count++; } else udf_write_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); /* Managed to do everything necessary? */ if (!blocks) goto out; /* All further extents will be NOT_RECORDED_NOT_ALLOCATED */ last_ext->extLocation.logicalBlockNum = 0; last_ext->extLocation.partitionReferenceNum = 0; add = (1 << (30-sb->s_blocksize_bits)) - 1; last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (add << sb->s_blocksize_bits); /* Create enough extents to cover the whole hole */ while (blocks > add) { blocks -= add; err = udf_add_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); if (err) return err; count++; } if (blocks) { last_ext->extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (blocks << sb->s_blocksize_bits); err = udf_add_aext(inode, last_pos, &last_ext->extLocation, last_ext->extLength, 1); if (err) return err; count++; } out: /* Do we have some preallocated blocks saved? */ if (prealloc_len) { err = udf_add_aext(inode, last_pos, &prealloc_loc, prealloc_len, 1); if (err) return err; last_ext->extLocation = prealloc_loc; last_ext->extLength = prealloc_len; count++; } /* last_pos should point to the last written extent... */ if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) last_pos->offset -= sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) last_pos->offset -= sizeof(struct long_ad); else return -EIO; return count; } static int udf_extend_file(struct inode *inode, loff_t newsize) { struct extent_position epos; struct kernel_lb_addr eloc; uint32_t elen; int8_t etype; struct super_block *sb = inode->i_sb; sector_t first_block = newsize >> sb->s_blocksize_bits, offset; int adsize; struct udf_inode_info *iinfo = UDF_I(inode); struct kernel_long_ad extent; int err; if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) adsize = sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) adsize = sizeof(struct long_ad); else BUG(); etype = inode_bmap(inode, first_block, &epos, &eloc, &elen, &offset); /* File has extent covering the new size (could happen when extending * inside a block)? */ if (etype != -1) return 0; if (newsize & (sb->s_blocksize - 1)) offset++; /* Extended file just to the boundary of the last file block? */ if (offset == 0) return 0; /* Truncate is extending the file by 'offset' blocks */ if ((!epos.bh && epos.offset == udf_file_entry_alloc_offset(inode)) || (epos.bh && epos.offset == sizeof(struct allocExtDesc))) { /* File has no extents at all or has empty last * indirect extent! Create a fake extent... */ extent.extLocation.logicalBlockNum = 0; extent.extLocation.partitionReferenceNum = 0; extent.extLength = EXT_NOT_RECORDED_NOT_ALLOCATED; } else { epos.offset -= adsize; etype = udf_next_aext(inode, &epos, &extent.extLocation, &extent.extLength, 0); extent.extLength |= etype << 30; } err = udf_do_extend_file(inode, &epos, &extent, offset); if (err < 0) goto out; err = 0; iinfo->i_lenExtents = newsize; out: brelse(epos.bh); return err; } static sector_t inode_getblk(struct inode *inode, sector_t block, int *err, int *new) { struct kernel_long_ad laarr[EXTENT_MERGE_SIZE]; struct extent_position prev_epos, cur_epos, next_epos; int count = 0, startnum = 0, endnum = 0; uint32_t elen = 0, tmpelen; struct kernel_lb_addr eloc, tmpeloc; int c = 1; loff_t lbcount = 0, b_off = 0; uint32_t newblocknum, newblock; sector_t offset = 0; int8_t etype; struct udf_inode_info *iinfo = UDF_I(inode); int goal = 0, pgoal = iinfo->i_location.logicalBlockNum; int lastblock = 0; bool isBeyondEOF; *err = 0; *new = 0; prev_epos.offset = udf_file_entry_alloc_offset(inode); prev_epos.block = iinfo->i_location; prev_epos.bh = NULL; cur_epos = next_epos = prev_epos; b_off = (loff_t)block << inode->i_sb->s_blocksize_bits; /* find the extent which contains the block we are looking for. alternate between laarr[0] and laarr[1] for locations of the current extent, and the previous extent */ do { if (prev_epos.bh != cur_epos.bh) { brelse(prev_epos.bh); get_bh(cur_epos.bh); prev_epos.bh = cur_epos.bh; } if (cur_epos.bh != next_epos.bh) { brelse(cur_epos.bh); get_bh(next_epos.bh); cur_epos.bh = next_epos.bh; } lbcount += elen; prev_epos.block = cur_epos.block; cur_epos.block = next_epos.block; prev_epos.offset = cur_epos.offset; cur_epos.offset = next_epos.offset; etype = udf_next_aext(inode, &next_epos, &eloc, &elen, 1); if (etype == -1) break; c = !c; laarr[c].extLength = (etype << 30) | elen; laarr[c].extLocation = eloc; if (etype != (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) pgoal = eloc.logicalBlockNum + ((elen + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits); count++; } while (lbcount + elen <= b_off); b_off -= lbcount; offset = b_off >> inode->i_sb->s_blocksize_bits; /* * Move prev_epos and cur_epos into indirect extent if we are at * the pointer to it */ udf_next_aext(inode, &prev_epos, &tmpeloc, &tmpelen, 0); udf_next_aext(inode, &cur_epos, &tmpeloc, &tmpelen, 0); /* if the extent is allocated and recorded, return the block if the extent is not a multiple of the blocksize, round up */ if (etype == (EXT_RECORDED_ALLOCATED >> 30)) { if (elen & (inode->i_sb->s_blocksize - 1)) { elen = EXT_RECORDED_ALLOCATED | ((elen + inode->i_sb->s_blocksize - 1) & ~(inode->i_sb->s_blocksize - 1)); udf_write_aext(inode, &cur_epos, &eloc, elen, 1); } brelse(prev_epos.bh); brelse(cur_epos.bh); brelse(next_epos.bh); newblock = udf_get_lb_pblock(inode->i_sb, &eloc, offset); return newblock; } /* Are we beyond EOF? */ if (etype == -1) { int ret; isBeyondEOF = 1; if (count) { if (c) laarr[0] = laarr[1]; startnum = 1; } else { /* Create a fake extent when there's not one */ memset(&laarr[0].extLocation, 0x00, sizeof(struct kernel_lb_addr)); laarr[0].extLength = EXT_NOT_RECORDED_NOT_ALLOCATED; /* Will udf_do_extend_file() create real extent from a fake one? */ startnum = (offset > 0); } /* Create extents for the hole between EOF and offset */ ret = udf_do_extend_file(inode, &prev_epos, laarr, offset); if (ret < 0) { brelse(prev_epos.bh); brelse(cur_epos.bh); brelse(next_epos.bh); *err = ret; return 0; } c = 0; offset = 0; count += ret; /* We are not covered by a preallocated extent? */ if ((laarr[0].extLength & UDF_EXTENT_FLAG_MASK) != EXT_NOT_RECORDED_ALLOCATED) { /* Is there any real extent? - otherwise we overwrite * the fake one... */ if (count) c = !c; laarr[c].extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | inode->i_sb->s_blocksize; memset(&laarr[c].extLocation, 0x00, sizeof(struct kernel_lb_addr)); count++; } endnum = c + 1; lastblock = 1; } else { isBeyondEOF = 0; endnum = startnum = ((count > 2) ? 2 : count); /* if the current extent is in position 0, swap it with the previous */ if (!c && count != 1) { laarr[2] = laarr[0]; laarr[0] = laarr[1]; laarr[1] = laarr[2]; c = 1; } /* if the current block is located in an extent, read the next extent */ etype = udf_next_aext(inode, &next_epos, &eloc, &elen, 0); if (etype != -1) { laarr[c + 1].extLength = (etype << 30) | elen; laarr[c + 1].extLocation = eloc; count++; startnum++; endnum++; } else lastblock = 1; } /* if the current extent is not recorded but allocated, get the * block in the extent corresponding to the requested block */ if ((laarr[c].extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30)) newblocknum = laarr[c].extLocation.logicalBlockNum + offset; else { /* otherwise, allocate a new block */ if (iinfo->i_next_alloc_block == block) goal = iinfo->i_next_alloc_goal; if (!goal) { if (!(goal = pgoal)) /* XXX: what was intended here? */ goal = iinfo->i_location.logicalBlockNum + 1; } newblocknum = udf_new_block(inode->i_sb, inode, iinfo->i_location.partitionReferenceNum, goal, err); if (!newblocknum) { brelse(prev_epos.bh); brelse(cur_epos.bh); brelse(next_epos.bh); *err = -ENOSPC; return 0; } if (isBeyondEOF) iinfo->i_lenExtents += inode->i_sb->s_blocksize; } /* if the extent the requsted block is located in contains multiple * blocks, split the extent into at most three extents. blocks prior * to requested block, requested block, and blocks after requested * block */ udf_split_extents(inode, &c, offset, newblocknum, laarr, &endnum); #ifdef UDF_PREALLOCATE /* We preallocate blocks only for regular files. It also makes sense * for directories but there's a problem when to drop the * preallocation. We might use some delayed work for that but I feel * it's overengineering for a filesystem like UDF. */ if (S_ISREG(inode->i_mode)) udf_prealloc_extents(inode, c, lastblock, laarr, &endnum); #endif /* merge any continuous blocks in laarr */ udf_merge_extents(inode, laarr, &endnum); /* write back the new extents, inserting new extents if the new number * of extents is greater than the old number, and deleting extents if * the new number of extents is less than the old number */ udf_update_extents(inode, laarr, startnum, endnum, &prev_epos); brelse(prev_epos.bh); brelse(cur_epos.bh); brelse(next_epos.bh); newblock = udf_get_pblock(inode->i_sb, newblocknum, iinfo->i_location.partitionReferenceNum, 0); if (!newblock) { *err = -EIO; return 0; } *new = 1; iinfo->i_next_alloc_block = block; iinfo->i_next_alloc_goal = newblocknum; inode->i_ctime = current_fs_time(inode->i_sb); if (IS_SYNC(inode)) udf_sync_inode(inode); else mark_inode_dirty(inode); return newblock; } static void udf_split_extents(struct inode *inode, int *c, int offset, int newblocknum, struct kernel_long_ad laarr[EXTENT_MERGE_SIZE], int *endnum) { unsigned long blocksize = inode->i_sb->s_blocksize; unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits; if ((laarr[*c].extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30) || (laarr[*c].extLength >> 30) == (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) { int curr = *c; int blen = ((laarr[curr].extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) >> blocksize_bits; int8_t etype = (laarr[curr].extLength >> 30); if (blen == 1) ; else if (!offset || blen == offset + 1) { laarr[curr + 2] = laarr[curr + 1]; laarr[curr + 1] = laarr[curr]; } else { laarr[curr + 3] = laarr[curr + 1]; laarr[curr + 2] = laarr[curr + 1] = laarr[curr]; } if (offset) { if (etype == (EXT_NOT_RECORDED_ALLOCATED >> 30)) { udf_free_blocks(inode->i_sb, inode, &laarr[curr].extLocation, 0, offset); laarr[curr].extLength = EXT_NOT_RECORDED_NOT_ALLOCATED | (offset << blocksize_bits); laarr[curr].extLocation.logicalBlockNum = 0; laarr[curr].extLocation. partitionReferenceNum = 0; } else laarr[curr].extLength = (etype << 30) | (offset << blocksize_bits); curr++; (*c)++; (*endnum)++; } laarr[curr].extLocation.logicalBlockNum = newblocknum; if (etype == (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) laarr[curr].extLocation.partitionReferenceNum = UDF_I(inode)->i_location.partitionReferenceNum; laarr[curr].extLength = EXT_RECORDED_ALLOCATED | blocksize; curr++; if (blen != offset + 1) { if (etype == (EXT_NOT_RECORDED_ALLOCATED >> 30)) laarr[curr].extLocation.logicalBlockNum += offset + 1; laarr[curr].extLength = (etype << 30) | ((blen - (offset + 1)) << blocksize_bits); curr++; (*endnum)++; } } } static void udf_prealloc_extents(struct inode *inode, int c, int lastblock, struct kernel_long_ad laarr[EXTENT_MERGE_SIZE], int *endnum) { int start, length = 0, currlength = 0, i; if (*endnum >= (c + 1)) { if (!lastblock) return; else start = c; } else { if ((laarr[c + 1].extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30)) { start = c + 1; length = currlength = (((laarr[c + 1].extLength & UDF_EXTENT_LENGTH_MASK) + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits); } else start = c; } for (i = start + 1; i <= *endnum; i++) { if (i == *endnum) { if (lastblock) length += UDF_DEFAULT_PREALLOC_BLOCKS; } else if ((laarr[i].extLength >> 30) == (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) { length += (((laarr[i].extLength & UDF_EXTENT_LENGTH_MASK) + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits); } else break; } if (length) { int next = laarr[start].extLocation.logicalBlockNum + (((laarr[start].extLength & UDF_EXTENT_LENGTH_MASK) + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits); int numalloc = udf_prealloc_blocks(inode->i_sb, inode, laarr[start].extLocation.partitionReferenceNum, next, (UDF_DEFAULT_PREALLOC_BLOCKS > length ? length : UDF_DEFAULT_PREALLOC_BLOCKS) - currlength); if (numalloc) { if (start == (c + 1)) laarr[start].extLength += (numalloc << inode->i_sb->s_blocksize_bits); else { memmove(&laarr[c + 2], &laarr[c + 1], sizeof(struct long_ad) * (*endnum - (c + 1))); (*endnum)++; laarr[c + 1].extLocation.logicalBlockNum = next; laarr[c + 1].extLocation.partitionReferenceNum = laarr[c].extLocation. partitionReferenceNum; laarr[c + 1].extLength = EXT_NOT_RECORDED_ALLOCATED | (numalloc << inode->i_sb->s_blocksize_bits); start = c + 1; } for (i = start + 1; numalloc && i < *endnum; i++) { int elen = ((laarr[i].extLength & UDF_EXTENT_LENGTH_MASK) + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (elen > numalloc) { laarr[i].extLength -= (numalloc << inode->i_sb->s_blocksize_bits); numalloc = 0; } else { numalloc -= elen; if (*endnum > (i + 1)) memmove(&laarr[i], &laarr[i + 1], sizeof(struct long_ad) * (*endnum - (i + 1))); i--; (*endnum)--; } } UDF_I(inode)->i_lenExtents += numalloc << inode->i_sb->s_blocksize_bits; } } } static void udf_merge_extents(struct inode *inode, struct kernel_long_ad laarr[EXTENT_MERGE_SIZE], int *endnum) { int i; unsigned long blocksize = inode->i_sb->s_blocksize; unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits; for (i = 0; i < (*endnum - 1); i++) { struct kernel_long_ad *li /*l[i]*/ = &laarr[i]; struct kernel_long_ad *lip1 /*l[i plus 1]*/ = &laarr[i + 1]; if (((li->extLength >> 30) == (lip1->extLength >> 30)) && (((li->extLength >> 30) == (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30)) || ((lip1->extLocation.logicalBlockNum - li->extLocation.logicalBlockNum) == (((li->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) >> blocksize_bits)))) { if (((li->extLength & UDF_EXTENT_LENGTH_MASK) + (lip1->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) & ~UDF_EXTENT_LENGTH_MASK) { lip1->extLength = (lip1->extLength - (li->extLength & UDF_EXTENT_LENGTH_MASK) + UDF_EXTENT_LENGTH_MASK) & ~(blocksize - 1); li->extLength = (li->extLength & UDF_EXTENT_FLAG_MASK) + (UDF_EXTENT_LENGTH_MASK + 1) - blocksize; lip1->extLocation.logicalBlockNum = li->extLocation.logicalBlockNum + ((li->extLength & UDF_EXTENT_LENGTH_MASK) >> blocksize_bits); } else { li->extLength = lip1->extLength + (((li->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) & ~(blocksize - 1)); if (*endnum > (i + 2)) memmove(&laarr[i + 1], &laarr[i + 2], sizeof(struct long_ad) * (*endnum - (i + 2))); i--; (*endnum)--; } } else if (((li->extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30)) && ((lip1->extLength >> 30) == (EXT_NOT_RECORDED_NOT_ALLOCATED >> 30))) { udf_free_blocks(inode->i_sb, inode, &li->extLocation, 0, ((li->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) >> blocksize_bits); li->extLocation.logicalBlockNum = 0; li->extLocation.partitionReferenceNum = 0; if (((li->extLength & UDF_EXTENT_LENGTH_MASK) + (lip1->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) & ~UDF_EXTENT_LENGTH_MASK) { lip1->extLength = (lip1->extLength - (li->extLength & UDF_EXTENT_LENGTH_MASK) + UDF_EXTENT_LENGTH_MASK) & ~(blocksize - 1); li->extLength = (li->extLength & UDF_EXTENT_FLAG_MASK) + (UDF_EXTENT_LENGTH_MASK + 1) - blocksize; } else { li->extLength = lip1->extLength + (((li->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) & ~(blocksize - 1)); if (*endnum > (i + 2)) memmove(&laarr[i + 1], &laarr[i + 2], sizeof(struct long_ad) * (*endnum - (i + 2))); i--; (*endnum)--; } } else if ((li->extLength >> 30) == (EXT_NOT_RECORDED_ALLOCATED >> 30)) { udf_free_blocks(inode->i_sb, inode, &li->extLocation, 0, ((li->extLength & UDF_EXTENT_LENGTH_MASK) + blocksize - 1) >> blocksize_bits); li->extLocation.logicalBlockNum = 0; li->extLocation.partitionReferenceNum = 0; li->extLength = (li->extLength & UDF_EXTENT_LENGTH_MASK) | EXT_NOT_RECORDED_NOT_ALLOCATED; } } } static void udf_update_extents(struct inode *inode, struct kernel_long_ad laarr[EXTENT_MERGE_SIZE], int startnum, int endnum, struct extent_position *epos) { int start = 0, i; struct kernel_lb_addr tmploc; uint32_t tmplen; if (startnum > endnum) { for (i = 0; i < (startnum - endnum); i++) udf_delete_aext(inode, *epos, laarr[i].extLocation, laarr[i].extLength); } else if (startnum < endnum) { for (i = 0; i < (endnum - startnum); i++) { udf_insert_aext(inode, *epos, laarr[i].extLocation, laarr[i].extLength); udf_next_aext(inode, epos, &laarr[i].extLocation, &laarr[i].extLength, 1); start++; } } for (i = start; i < endnum; i++) { udf_next_aext(inode, epos, &tmploc, &tmplen, 0); udf_write_aext(inode, epos, &laarr[i].extLocation, laarr[i].extLength, 1); } } struct buffer_head *udf_bread(struct inode *inode, int block, int create, int *err) { struct buffer_head *bh = NULL; bh = udf_getblk(inode, block, create, err); if (!bh) return NULL; if (buffer_uptodate(bh)) return bh; ll_rw_block(READ, 1, &bh); wait_on_buffer(bh); if (buffer_uptodate(bh)) return bh; brelse(bh); *err = -EIO; return NULL; } int udf_setsize(struct inode *inode, loff_t newsize) { int err; struct udf_inode_info *iinfo; int bsize = 1 << inode->i_blkbits; if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))) return -EINVAL; if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; iinfo = UDF_I(inode); if (newsize > inode->i_size) { down_write(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { if (bsize < (udf_file_entry_alloc_offset(inode) + newsize)) { err = udf_expand_file_adinicb(inode); if (err) return err; down_write(&iinfo->i_data_sem); } else { iinfo->i_lenAlloc = newsize; goto set_size; } } err = udf_extend_file(inode, newsize); if (err) { up_write(&iinfo->i_data_sem); return err; } set_size: truncate_setsize(inode, newsize); up_write(&iinfo->i_data_sem); } else { if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); memset(iinfo->i_ext.i_data + iinfo->i_lenEAttr + newsize, 0x00, bsize - newsize - udf_file_entry_alloc_offset(inode)); iinfo->i_lenAlloc = newsize; truncate_setsize(inode, newsize); up_write(&iinfo->i_data_sem); goto update_time; } err = block_truncate_page(inode->i_mapping, newsize, udf_get_block); if (err) return err; down_write(&iinfo->i_data_sem); udf_clear_extent_cache(inode); truncate_setsize(inode, newsize); udf_truncate_extents(inode); up_write(&iinfo->i_data_sem); } update_time: inode->i_mtime = inode->i_ctime = current_fs_time(inode->i_sb); if (IS_SYNC(inode)) udf_sync_inode(inode); else mark_inode_dirty(inode); return 0; } /* * Maximum length of linked list formed by ICB hierarchy. The chosen number is * arbitrary - just that we hopefully don't limit any real use of rewritten * inode on write-once media but avoid looping for too long on corrupted media. */ #define UDF_MAX_ICB_NESTING 1024 static int udf_read_inode(struct inode *inode, bool hidden_inode) { struct buffer_head *bh = NULL; struct fileEntry *fe; struct extendedFileEntry *efe; uint16_t ident; struct udf_inode_info *iinfo = UDF_I(inode); struct udf_sb_info *sbi = UDF_SB(inode->i_sb); struct kernel_lb_addr *iloc = &iinfo->i_location; unsigned int link_count; unsigned int indirections = 0; int ret = -EIO; reread: if (iloc->logicalBlockNum >= sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) { udf_debug("block=%d, partition=%d out of range\n", iloc->logicalBlockNum, iloc->partitionReferenceNum); return -EIO; } /* * Set defaults, but the inode is still incomplete! * Note: get_new_inode() sets the following on a new inode: * i_sb = sb * i_no = ino * i_flags = sb->s_flags * i_state = 0 * clean_inode(): zero fills and sets * i_count = 1 * i_nlink = 1 * i_op = NULL; */ bh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident); if (!bh) { udf_err(inode->i_sb, "(ino %ld) failed !bh\n", inode->i_ino); return -EIO; } if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE && ident != TAG_IDENT_USE) { udf_err(inode->i_sb, "(ino %ld) failed ident=%d\n", inode->i_ino, ident); goto out; } fe = (struct fileEntry *)bh->b_data; efe = (struct extendedFileEntry *)bh->b_data; if (fe->icbTag.strategyType == cpu_to_le16(4096)) { struct buffer_head *ibh; ibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident); if (ident == TAG_IDENT_IE && ibh) { struct kernel_lb_addr loc; struct indirectEntry *ie; ie = (struct indirectEntry *)ibh->b_data; loc = lelb_to_cpu(ie->indirectICB.extLocation); if (ie->indirectICB.extLength) { brelse(ibh); memcpy(&iinfo->i_location, &loc, sizeof(struct kernel_lb_addr)); if (++indirections > UDF_MAX_ICB_NESTING) { udf_err(inode->i_sb, "too many ICBs in ICB hierarchy" " (max %d supported)\n", UDF_MAX_ICB_NESTING); goto out; } brelse(bh); goto reread; } } brelse(ibh); } else if (fe->icbTag.strategyType != cpu_to_le16(4)) { udf_err(inode->i_sb, "unsupported strategy type: %d\n", le16_to_cpu(fe->icbTag.strategyType)); goto out; } if (fe->icbTag.strategyType == cpu_to_le16(4)) iinfo->i_strat4096 = 0; else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */ iinfo->i_strat4096 = 1; iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) & ICBTAG_FLAG_AD_MASK; iinfo->i_unique = 0; iinfo->i_lenEAttr = 0; iinfo->i_lenExtents = 0; iinfo->i_lenAlloc = 0; iinfo->i_next_alloc_block = 0; iinfo->i_next_alloc_goal = 0; if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) { iinfo->i_efe = 1; iinfo->i_use = 0; ret = udf_alloc_i_data(inode, inode->i_sb->s_blocksize - sizeof(struct extendedFileEntry)); if (ret) goto out; memcpy(iinfo->i_ext.i_data, bh->b_data + sizeof(struct extendedFileEntry), inode->i_sb->s_blocksize - sizeof(struct extendedFileEntry)); } else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) { iinfo->i_efe = 0; iinfo->i_use = 0; ret = udf_alloc_i_data(inode, inode->i_sb->s_blocksize - sizeof(struct fileEntry)); if (ret) goto out; memcpy(iinfo->i_ext.i_data, bh->b_data + sizeof(struct fileEntry), inode->i_sb->s_blocksize - sizeof(struct fileEntry)); } else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) { iinfo->i_efe = 0; iinfo->i_use = 1; iinfo->i_lenAlloc = le32_to_cpu( ((struct unallocSpaceEntry *)bh->b_data)-> lengthAllocDescs); ret = udf_alloc_i_data(inode, inode->i_sb->s_blocksize - sizeof(struct unallocSpaceEntry)); if (ret) goto out; memcpy(iinfo->i_ext.i_data, bh->b_data + sizeof(struct unallocSpaceEntry), inode->i_sb->s_blocksize - sizeof(struct unallocSpaceEntry)); return 0; } ret = -EIO; read_lock(&sbi->s_cred_lock); i_uid_write(inode, le32_to_cpu(fe->uid)); if (!uid_valid(inode->i_uid) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET)) inode->i_uid = UDF_SB(inode->i_sb)->s_uid; i_gid_write(inode, le32_to_cpu(fe->gid)); if (!gid_valid(inode->i_gid) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET)) inode->i_gid = UDF_SB(inode->i_sb)->s_gid; if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY && sbi->s_fmode != UDF_INVALID_MODE) inode->i_mode = sbi->s_fmode; else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY && sbi->s_dmode != UDF_INVALID_MODE) inode->i_mode = sbi->s_dmode; else inode->i_mode = udf_convert_permissions(fe); inode->i_mode &= ~sbi->s_umask; read_unlock(&sbi->s_cred_lock); link_count = le16_to_cpu(fe->fileLinkCount); if (!link_count) { if (!hidden_inode) { ret = -ESTALE; goto out; } link_count = 1; } set_nlink(inode, link_count); inode->i_size = le64_to_cpu(fe->informationLength); iinfo->i_lenExtents = inode->i_size; if (iinfo->i_efe == 0) { inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) << (inode->i_sb->s_blocksize_bits - 9); if (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime)) inode->i_atime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_mtime, fe->modificationTime)) inode->i_mtime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime)) inode->i_ctime = sbi->s_record_time; iinfo->i_unique = le64_to_cpu(fe->uniqueID); iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr); iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs); iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint); } else { inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) << (inode->i_sb->s_blocksize_bits - 9); if (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime)) inode->i_atime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_mtime, efe->modificationTime)) inode->i_mtime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime)) iinfo->i_crtime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime)) inode->i_ctime = sbi->s_record_time; iinfo->i_unique = le64_to_cpu(efe->uniqueID); iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr); iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs); iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint); } inode->i_generation = iinfo->i_unique; switch (fe->icbTag.fileType) { case ICBTAG_FILE_TYPE_DIRECTORY: inode->i_op = &udf_dir_inode_operations; inode->i_fop = &udf_dir_operations; inode->i_mode |= S_IFDIR; inc_nlink(inode); break; case ICBTAG_FILE_TYPE_REALTIME: case ICBTAG_FILE_TYPE_REGULAR: case ICBTAG_FILE_TYPE_UNDEF: case ICBTAG_FILE_TYPE_VAT20: if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) inode->i_data.a_ops = &udf_adinicb_aops; else inode->i_data.a_ops = &udf_aops; inode->i_op = &udf_file_inode_operations; inode->i_fop = &udf_file_operations; inode->i_mode |= S_IFREG; break; case ICBTAG_FILE_TYPE_BLOCK: inode->i_mode |= S_IFBLK; break; case ICBTAG_FILE_TYPE_CHAR: inode->i_mode |= S_IFCHR; break; case ICBTAG_FILE_TYPE_FIFO: init_special_inode(inode, inode->i_mode | S_IFIFO, 0); break; case ICBTAG_FILE_TYPE_SOCKET: init_special_inode(inode, inode->i_mode | S_IFSOCK, 0); break; case ICBTAG_FILE_TYPE_SYMLINK: inode->i_data.a_ops = &udf_symlink_aops; inode->i_op = &udf_symlink_inode_operations; inode->i_mode = S_IFLNK | S_IRWXUGO; break; case ICBTAG_FILE_TYPE_MAIN: udf_debug("METADATA FILE-----\n"); break; case ICBTAG_FILE_TYPE_MIRROR: udf_debug("METADATA MIRROR FILE-----\n"); break; case ICBTAG_FILE_TYPE_BITMAP: udf_debug("METADATA BITMAP FILE-----\n"); break; default: udf_err(inode->i_sb, "(ino %ld) failed unknown file type=%d\n", inode->i_ino, fe->icbTag.fileType); goto out; } if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) { struct deviceSpec *dsea = (struct deviceSpec *)udf_get_extendedattr(inode, 12, 1); if (dsea) { init_special_inode(inode, inode->i_mode, MKDEV(le32_to_cpu(dsea->majorDeviceIdent), le32_to_cpu(dsea->minorDeviceIdent))); /* Developer ID ??? */ } else goto out; } ret = 0; out: brelse(bh); return ret; } static int udf_alloc_i_data(struct inode *inode, size_t size) { struct udf_inode_info *iinfo = UDF_I(inode); iinfo->i_ext.i_data = kmalloc(size, GFP_KERNEL); if (!iinfo->i_ext.i_data) { udf_err(inode->i_sb, "(ino %ld) no free memory\n", inode->i_ino); return -ENOMEM; } return 0; } static umode_t udf_convert_permissions(struct fileEntry *fe) { umode_t mode; uint32_t permissions; uint32_t flags; permissions = le32_to_cpu(fe->permissions); flags = le16_to_cpu(fe->icbTag.flags); mode = ((permissions) & S_IRWXO) | ((permissions >> 2) & S_IRWXG) | ((permissions >> 4) & S_IRWXU) | ((flags & ICBTAG_FLAG_SETUID) ? S_ISUID : 0) | ((flags & ICBTAG_FLAG_SETGID) ? S_ISGID : 0) | ((flags & ICBTAG_FLAG_STICKY) ? S_ISVTX : 0); return mode; } int udf_write_inode(struct inode *inode, struct writeback_control *wbc) { return udf_update_inode(inode, wbc->sync_mode == WB_SYNC_ALL); } static int udf_sync_inode(struct inode *inode) { return udf_update_inode(inode, 1); } static int udf_update_inode(struct inode *inode, int do_sync) { struct buffer_head *bh = NULL; struct fileEntry *fe; struct extendedFileEntry *efe; uint64_t lb_recorded; uint32_t udfperms; uint16_t icbflags; uint16_t crclen; int err = 0; struct udf_sb_info *sbi = UDF_SB(inode->i_sb); unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits; struct udf_inode_info *iinfo = UDF_I(inode); bh = udf_tgetblk(inode->i_sb, udf_get_lb_pblock(inode->i_sb, &iinfo->i_location, 0)); if (!bh) { udf_debug("getblk failure\n"); return -ENOMEM; } lock_buffer(bh); memset(bh->b_data, 0, inode->i_sb->s_blocksize); fe = (struct fileEntry *)bh->b_data; efe = (struct extendedFileEntry *)bh->b_data; if (iinfo->i_use) { struct unallocSpaceEntry *use = (struct unallocSpaceEntry *)bh->b_data; use->lengthAllocDescs = cpu_to_le32(iinfo->i_lenAlloc); memcpy(bh->b_data + sizeof(struct unallocSpaceEntry), iinfo->i_ext.i_data, inode->i_sb->s_blocksize - sizeof(struct unallocSpaceEntry)); use->descTag.tagIdent = cpu_to_le16(TAG_IDENT_USE); use->descTag.tagLocation = cpu_to_le32(iinfo->i_location.logicalBlockNum); crclen = sizeof(struct unallocSpaceEntry) + iinfo->i_lenAlloc - sizeof(struct tag); use->descTag.descCRCLength = cpu_to_le16(crclen); use->descTag.descCRC = cpu_to_le16(crc_itu_t(0, (char *)use + sizeof(struct tag), crclen)); use->descTag.tagChecksum = udf_tag_checksum(&use->descTag); goto out; } if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_FORGET)) fe->uid = cpu_to_le32(-1); else fe->uid = cpu_to_le32(i_uid_read(inode)); if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_FORGET)) fe->gid = cpu_to_le32(-1); else fe->gid = cpu_to_le32(i_gid_read(inode)); udfperms = ((inode->i_mode & S_IRWXO)) | ((inode->i_mode & S_IRWXG) << 2) | ((inode->i_mode & S_IRWXU) << 4); udfperms |= (le32_to_cpu(fe->permissions) & (FE_PERM_O_DELETE | FE_PERM_O_CHATTR | FE_PERM_G_DELETE | FE_PERM_G_CHATTR | FE_PERM_U_DELETE | FE_PERM_U_CHATTR)); fe->permissions = cpu_to_le32(udfperms); if (S_ISDIR(inode->i_mode) && inode->i_nlink > 0) fe->fileLinkCount = cpu_to_le16(inode->i_nlink - 1); else fe->fileLinkCount = cpu_to_le16(inode->i_nlink); fe->informationLength = cpu_to_le64(inode->i_size); if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) { struct regid *eid; struct deviceSpec *dsea = (struct deviceSpec *)udf_get_extendedattr(inode, 12, 1); if (!dsea) { dsea = (struct deviceSpec *) udf_add_extendedattr(inode, sizeof(struct deviceSpec) + sizeof(struct regid), 12, 0x3); dsea->attrType = cpu_to_le32(12); dsea->attrSubtype = 1; dsea->attrLength = cpu_to_le32( sizeof(struct deviceSpec) + sizeof(struct regid)); dsea->impUseLength = cpu_to_le32(sizeof(struct regid)); } eid = (struct regid *)dsea->impUse; memset(eid, 0, sizeof(struct regid)); strcpy(eid->ident, UDF_ID_DEVELOPER); eid->identSuffix[0] = UDF_OS_CLASS_UNIX; eid->identSuffix[1] = UDF_OS_ID_LINUX; dsea->majorDeviceIdent = cpu_to_le32(imajor(inode)); dsea->minorDeviceIdent = cpu_to_le32(iminor(inode)); } if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) lb_recorded = 0; /* No extents => no blocks! */ else lb_recorded = (inode->i_blocks + (1 << (blocksize_bits - 9)) - 1) >> (blocksize_bits - 9); if (iinfo->i_efe == 0) { memcpy(bh->b_data + sizeof(struct fileEntry), iinfo->i_ext.i_data, inode->i_sb->s_blocksize - sizeof(struct fileEntry)); fe->logicalBlocksRecorded = cpu_to_le64(lb_recorded); udf_time_to_disk_stamp(&fe->accessTime, inode->i_atime); udf_time_to_disk_stamp(&fe->modificationTime, inode->i_mtime); udf_time_to_disk_stamp(&fe->attrTime, inode->i_ctime); memset(&(fe->impIdent), 0, sizeof(struct regid)); strcpy(fe->impIdent.ident, UDF_ID_DEVELOPER); fe->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX; fe->impIdent.identSuffix[1] = UDF_OS_ID_LINUX; fe->uniqueID = cpu_to_le64(iinfo->i_unique); fe->lengthExtendedAttr = cpu_to_le32(iinfo->i_lenEAttr); fe->lengthAllocDescs = cpu_to_le32(iinfo->i_lenAlloc); fe->checkpoint = cpu_to_le32(iinfo->i_checkpoint); fe->descTag.tagIdent = cpu_to_le16(TAG_IDENT_FE); crclen = sizeof(struct fileEntry); } else { memcpy(bh->b_data + sizeof(struct extendedFileEntry), iinfo->i_ext.i_data, inode->i_sb->s_blocksize - sizeof(struct extendedFileEntry)); efe->objectSize = cpu_to_le64(inode->i_size); efe->logicalBlocksRecorded = cpu_to_le64(lb_recorded); if (iinfo->i_crtime.tv_sec > inode->i_atime.tv_sec || (iinfo->i_crtime.tv_sec == inode->i_atime.tv_sec && iinfo->i_crtime.tv_nsec > inode->i_atime.tv_nsec)) iinfo->i_crtime = inode->i_atime; if (iinfo->i_crtime.tv_sec > inode->i_mtime.tv_sec || (iinfo->i_crtime.tv_sec == inode->i_mtime.tv_sec && iinfo->i_crtime.tv_nsec > inode->i_mtime.tv_nsec)) iinfo->i_crtime = inode->i_mtime; if (iinfo->i_crtime.tv_sec > inode->i_ctime.tv_sec || (iinfo->i_crtime.tv_sec == inode->i_ctime.tv_sec && iinfo->i_crtime.tv_nsec > inode->i_ctime.tv_nsec)) iinfo->i_crtime = inode->i_ctime; udf_time_to_disk_stamp(&efe->accessTime, inode->i_atime); udf_time_to_disk_stamp(&efe->modificationTime, inode->i_mtime); udf_time_to_disk_stamp(&efe->createTime, iinfo->i_crtime); udf_time_to_disk_stamp(&efe->attrTime, inode->i_ctime); memset(&(efe->impIdent), 0, sizeof(struct regid)); strcpy(efe->impIdent.ident, UDF_ID_DEVELOPER); efe->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX; efe->impIdent.identSuffix[1] = UDF_OS_ID_LINUX; efe->uniqueID = cpu_to_le64(iinfo->i_unique); efe->lengthExtendedAttr = cpu_to_le32(iinfo->i_lenEAttr); efe->lengthAllocDescs = cpu_to_le32(iinfo->i_lenAlloc); efe->checkpoint = cpu_to_le32(iinfo->i_checkpoint); efe->descTag.tagIdent = cpu_to_le16(TAG_IDENT_EFE); crclen = sizeof(struct extendedFileEntry); } if (iinfo->i_strat4096) { fe->icbTag.strategyType = cpu_to_le16(4096); fe->icbTag.strategyParameter = cpu_to_le16(1); fe->icbTag.numEntries = cpu_to_le16(2); } else { fe->icbTag.strategyType = cpu_to_le16(4); fe->icbTag.numEntries = cpu_to_le16(1); } if (S_ISDIR(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_DIRECTORY; else if (S_ISREG(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_REGULAR; else if (S_ISLNK(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_SYMLINK; else if (S_ISBLK(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_BLOCK; else if (S_ISCHR(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_CHAR; else if (S_ISFIFO(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_FIFO; else if (S_ISSOCK(inode->i_mode)) fe->icbTag.fileType = ICBTAG_FILE_TYPE_SOCKET; icbflags = iinfo->i_alloc_type | ((inode->i_mode & S_ISUID) ? ICBTAG_FLAG_SETUID : 0) | ((inode->i_mode & S_ISGID) ? ICBTAG_FLAG_SETGID : 0) | ((inode->i_mode & S_ISVTX) ? ICBTAG_FLAG_STICKY : 0) | (le16_to_cpu(fe->icbTag.flags) & ~(ICBTAG_FLAG_AD_MASK | ICBTAG_FLAG_SETUID | ICBTAG_FLAG_SETGID | ICBTAG_FLAG_STICKY)); fe->icbTag.flags = cpu_to_le16(icbflags); if (sbi->s_udfrev >= 0x0200) fe->descTag.descVersion = cpu_to_le16(3); else fe->descTag.descVersion = cpu_to_le16(2); fe->descTag.tagSerialNum = cpu_to_le16(sbi->s_serial_number); fe->descTag.tagLocation = cpu_to_le32( iinfo->i_location.logicalBlockNum); crclen += iinfo->i_lenEAttr + iinfo->i_lenAlloc - sizeof(struct tag); fe->descTag.descCRCLength = cpu_to_le16(crclen); fe->descTag.descCRC = cpu_to_le16(crc_itu_t(0, (char *)fe + sizeof(struct tag), crclen)); fe->descTag.tagChecksum = udf_tag_checksum(&fe->descTag); out: set_buffer_uptodate(bh); unlock_buffer(bh); /* write the data blocks */ mark_buffer_dirty(bh); if (do_sync) { sync_dirty_buffer(bh); if (buffer_write_io_error(bh)) { udf_warn(inode->i_sb, "IO error syncing udf inode [%08lx]\n", inode->i_ino); err = -EIO; } } brelse(bh); return err; } struct inode *__udf_iget(struct super_block *sb, struct kernel_lb_addr *ino, bool hidden_inode) { unsigned long block = udf_get_lb_pblock(sb, ino, 0); struct inode *inode = iget_locked(sb, block); int err; if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; memcpy(&UDF_I(inode)->i_location, ino, sizeof(struct kernel_lb_addr)); err = udf_read_inode(inode, hidden_inode); if (err < 0) { iget_failed(inode); return ERR_PTR(err); } unlock_new_inode(inode); return inode; } int udf_add_aext(struct inode *inode, struct extent_position *epos, struct kernel_lb_addr *eloc, uint32_t elen, int inc) { int adsize; struct short_ad *sad = NULL; struct long_ad *lad = NULL; struct allocExtDesc *aed; uint8_t *ptr; struct udf_inode_info *iinfo = UDF_I(inode); if (!epos->bh) ptr = iinfo->i_ext.i_data + epos->offset - udf_file_entry_alloc_offset(inode) + iinfo->i_lenEAttr; else ptr = epos->bh->b_data + epos->offset; if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) adsize = sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) adsize = sizeof(struct long_ad); else return -EIO; if (epos->offset + (2 * adsize) > inode->i_sb->s_blocksize) { unsigned char *sptr, *dptr; struct buffer_head *nbh; int err, loffset; struct kernel_lb_addr obloc = epos->block; epos->block.logicalBlockNum = udf_new_block(inode->i_sb, NULL, obloc.partitionReferenceNum, obloc.logicalBlockNum, &err); if (!epos->block.logicalBlockNum) return -ENOSPC; nbh = udf_tgetblk(inode->i_sb, udf_get_lb_pblock(inode->i_sb, &epos->block, 0)); if (!nbh) return -EIO; lock_buffer(nbh); memset(nbh->b_data, 0x00, inode->i_sb->s_blocksize); set_buffer_uptodate(nbh); unlock_buffer(nbh); mark_buffer_dirty_inode(nbh, inode); aed = (struct allocExtDesc *)(nbh->b_data); if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT)) aed->previousAllocExtLocation = cpu_to_le32(obloc.logicalBlockNum); if (epos->offset + adsize > inode->i_sb->s_blocksize) { loffset = epos->offset; aed->lengthAllocDescs = cpu_to_le32(adsize); sptr = ptr - adsize; dptr = nbh->b_data + sizeof(struct allocExtDesc); memcpy(dptr, sptr, adsize); epos->offset = sizeof(struct allocExtDesc) + adsize; } else { loffset = epos->offset + adsize; aed->lengthAllocDescs = cpu_to_le32(0); sptr = ptr; epos->offset = sizeof(struct allocExtDesc); if (epos->bh) { aed = (struct allocExtDesc *)epos->bh->b_data; le32_add_cpu(&aed->lengthAllocDescs, adsize); } else { iinfo->i_lenAlloc += adsize; mark_inode_dirty(inode); } } if (UDF_SB(inode->i_sb)->s_udfrev >= 0x0200) udf_new_tag(nbh->b_data, TAG_IDENT_AED, 3, 1, epos->block.logicalBlockNum, sizeof(struct tag)); else udf_new_tag(nbh->b_data, TAG_IDENT_AED, 2, 1, epos->block.logicalBlockNum, sizeof(struct tag)); switch (iinfo->i_alloc_type) { case ICBTAG_FLAG_AD_SHORT: sad = (struct short_ad *)sptr; sad->extLength = cpu_to_le32(EXT_NEXT_EXTENT_ALLOCDECS | inode->i_sb->s_blocksize); sad->extPosition = cpu_to_le32(epos->block.logicalBlockNum); break; case ICBTAG_FLAG_AD_LONG: lad = (struct long_ad *)sptr; lad->extLength = cpu_to_le32(EXT_NEXT_EXTENT_ALLOCDECS | inode->i_sb->s_blocksize); lad->extLocation = cpu_to_lelb(epos->block); memset(lad->impUse, 0x00, sizeof(lad->impUse)); break; } if (epos->bh) { if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) || UDF_SB(inode->i_sb)->s_udfrev >= 0x0201) udf_update_tag(epos->bh->b_data, loffset); else udf_update_tag(epos->bh->b_data, sizeof(struct allocExtDesc)); mark_buffer_dirty_inode(epos->bh, inode); brelse(epos->bh); } else { mark_inode_dirty(inode); } epos->bh = nbh; } udf_write_aext(inode, epos, eloc, elen, inc); if (!epos->bh) { iinfo->i_lenAlloc += adsize; mark_inode_dirty(inode); } else { aed = (struct allocExtDesc *)epos->bh->b_data; le32_add_cpu(&aed->lengthAllocDescs, adsize); if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) || UDF_SB(inode->i_sb)->s_udfrev >= 0x0201) udf_update_tag(epos->bh->b_data, epos->offset + (inc ? 0 : adsize)); else udf_update_tag(epos->bh->b_data, sizeof(struct allocExtDesc)); mark_buffer_dirty_inode(epos->bh, inode); } return 0; } void udf_write_aext(struct inode *inode, struct extent_position *epos, struct kernel_lb_addr *eloc, uint32_t elen, int inc) { int adsize; uint8_t *ptr; struct short_ad *sad; struct long_ad *lad; struct udf_inode_info *iinfo = UDF_I(inode); if (!epos->bh) ptr = iinfo->i_ext.i_data + epos->offset - udf_file_entry_alloc_offset(inode) + iinfo->i_lenEAttr; else ptr = epos->bh->b_data + epos->offset; switch (iinfo->i_alloc_type) { case ICBTAG_FLAG_AD_SHORT: sad = (struct short_ad *)ptr; sad->extLength = cpu_to_le32(elen); sad->extPosition = cpu_to_le32(eloc->logicalBlockNum); adsize = sizeof(struct short_ad); break; case ICBTAG_FLAG_AD_LONG: lad = (struct long_ad *)ptr; lad->extLength = cpu_to_le32(elen); lad->extLocation = cpu_to_lelb(*eloc); memset(lad->impUse, 0x00, sizeof(lad->impUse)); adsize = sizeof(struct long_ad); break; default: return; } if (epos->bh) { if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) || UDF_SB(inode->i_sb)->s_udfrev >= 0x0201) { struct allocExtDesc *aed = (struct allocExtDesc *)epos->bh->b_data; udf_update_tag(epos->bh->b_data, le32_to_cpu(aed->lengthAllocDescs) + sizeof(struct allocExtDesc)); } mark_buffer_dirty_inode(epos->bh, inode); } else { mark_inode_dirty(inode); } if (inc) epos->offset += adsize; } int8_t udf_next_aext(struct inode *inode, struct extent_position *epos, struct kernel_lb_addr *eloc, uint32_t *elen, int inc) { int8_t etype; while ((etype = udf_current_aext(inode, epos, eloc, elen, inc)) == (EXT_NEXT_EXTENT_ALLOCDECS >> 30)) { int block; epos->block = *eloc; epos->offset = sizeof(struct allocExtDesc); brelse(epos->bh); block = udf_get_lb_pblock(inode->i_sb, &epos->block, 0); epos->bh = udf_tread(inode->i_sb, block); if (!epos->bh) { udf_debug("reading block %d failed!\n", block); return -1; } } return etype; } int8_t udf_current_aext(struct inode *inode, struct extent_position *epos, struct kernel_lb_addr *eloc, uint32_t *elen, int inc) { int alen; int8_t etype; uint8_t *ptr; struct short_ad *sad; struct long_ad *lad; struct udf_inode_info *iinfo = UDF_I(inode); if (!epos->bh) { if (!epos->offset) epos->offset = udf_file_entry_alloc_offset(inode); ptr = iinfo->i_ext.i_data + epos->offset - udf_file_entry_alloc_offset(inode) + iinfo->i_lenEAttr; alen = udf_file_entry_alloc_offset(inode) + iinfo->i_lenAlloc; } else { if (!epos->offset) epos->offset = sizeof(struct allocExtDesc); ptr = epos->bh->b_data + epos->offset; alen = sizeof(struct allocExtDesc) + le32_to_cpu(((struct allocExtDesc *)epos->bh->b_data)-> lengthAllocDescs); } switch (iinfo->i_alloc_type) { case ICBTAG_FLAG_AD_SHORT: sad = udf_get_fileshortad(ptr, alen, &epos->offset, inc); if (!sad) return -1; etype = le32_to_cpu(sad->extLength) >> 30; eloc->logicalBlockNum = le32_to_cpu(sad->extPosition); eloc->partitionReferenceNum = iinfo->i_location.partitionReferenceNum; *elen = le32_to_cpu(sad->extLength) & UDF_EXTENT_LENGTH_MASK; break; case ICBTAG_FLAG_AD_LONG: lad = udf_get_filelongad(ptr, alen, &epos->offset, inc); if (!lad) return -1; etype = le32_to_cpu(lad->extLength) >> 30; *eloc = lelb_to_cpu(lad->extLocation); *elen = le32_to_cpu(lad->extLength) & UDF_EXTENT_LENGTH_MASK; break; default: udf_debug("alloc_type = %d unsupported\n", iinfo->i_alloc_type); return -1; } return etype; } static int8_t udf_insert_aext(struct inode *inode, struct extent_position epos, struct kernel_lb_addr neloc, uint32_t nelen) { struct kernel_lb_addr oeloc; uint32_t oelen; int8_t etype; if (epos.bh) get_bh(epos.bh); while ((etype = udf_next_aext(inode, &epos, &oeloc, &oelen, 0)) != -1) { udf_write_aext(inode, &epos, &neloc, nelen, 1); neloc = oeloc; nelen = (etype << 30) | oelen; } udf_add_aext(inode, &epos, &neloc, nelen, 1); brelse(epos.bh); return (nelen >> 30); } int8_t udf_delete_aext(struct inode *inode, struct extent_position epos, struct kernel_lb_addr eloc, uint32_t elen) { struct extent_position oepos; int adsize; int8_t etype; struct allocExtDesc *aed; struct udf_inode_info *iinfo; if (epos.bh) { get_bh(epos.bh); get_bh(epos.bh); } iinfo = UDF_I(inode); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) adsize = sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) adsize = sizeof(struct long_ad); else adsize = 0; oepos = epos; if (udf_next_aext(inode, &epos, &eloc, &elen, 1) == -1) return -1; while ((etype = udf_next_aext(inode, &epos, &eloc, &elen, 1)) != -1) { udf_write_aext(inode, &oepos, &eloc, (etype << 30) | elen, 1); if (oepos.bh != epos.bh) { oepos.block = epos.block; brelse(oepos.bh); get_bh(epos.bh); oepos.bh = epos.bh; oepos.offset = epos.offset - adsize; } } memset(&eloc, 0x00, sizeof(struct kernel_lb_addr)); elen = 0; if (epos.bh != oepos.bh) { udf_free_blocks(inode->i_sb, inode, &epos.block, 0, 1); udf_write_aext(inode, &oepos, &eloc, elen, 1); udf_write_aext(inode, &oepos, &eloc, elen, 1); if (!oepos.bh) { iinfo->i_lenAlloc -= (adsize * 2); mark_inode_dirty(inode); } else { aed = (struct allocExtDesc *)oepos.bh->b_data; le32_add_cpu(&aed->lengthAllocDescs, -(2 * adsize)); if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) || UDF_SB(inode->i_sb)->s_udfrev >= 0x0201) udf_update_tag(oepos.bh->b_data, oepos.offset - (2 * adsize)); else udf_update_tag(oepos.bh->b_data, sizeof(struct allocExtDesc)); mark_buffer_dirty_inode(oepos.bh, inode); } } else { udf_write_aext(inode, &oepos, &eloc, elen, 1); if (!oepos.bh) { iinfo->i_lenAlloc -= adsize; mark_inode_dirty(inode); } else { aed = (struct allocExtDesc *)oepos.bh->b_data; le32_add_cpu(&aed->lengthAllocDescs, -adsize); if (!UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT) || UDF_SB(inode->i_sb)->s_udfrev >= 0x0201) udf_update_tag(oepos.bh->b_data, epos.offset - adsize); else udf_update_tag(oepos.bh->b_data, sizeof(struct allocExtDesc)); mark_buffer_dirty_inode(oepos.bh, inode); } } brelse(epos.bh); brelse(oepos.bh); return (elen >> 30); } int8_t inode_bmap(struct inode *inode, sector_t block, struct extent_position *pos, struct kernel_lb_addr *eloc, uint32_t *elen, sector_t *offset) { unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits; loff_t lbcount = 0, bcount = (loff_t) block << blocksize_bits; int8_t etype; struct udf_inode_info *iinfo; iinfo = UDF_I(inode); if (!udf_read_extent_cache(inode, bcount, &lbcount, pos)) { pos->offset = 0; pos->block = iinfo->i_location; pos->bh = NULL; } *elen = 0; do { etype = udf_next_aext(inode, pos, eloc, elen, 1); if (etype == -1) { *offset = (bcount - lbcount) >> blocksize_bits; iinfo->i_lenExtents = lbcount; return -1; } lbcount += *elen; } while (lbcount <= bcount); /* update extent cache */ udf_update_extent_cache(inode, lbcount - *elen, pos, 1); *offset = (bcount + *elen - lbcount) >> blocksize_bits; return etype; } long udf_block_map(struct inode *inode, sector_t block) { struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; struct extent_position epos = {}; int ret; down_read(&UDF_I(inode)->i_data_sem); if (inode_bmap(inode, block, &epos, &eloc, &elen, &offset) == (EXT_RECORDED_ALLOCATED >> 30)) ret = udf_get_lb_pblock(inode->i_sb, &eloc, offset); else ret = 0; up_read(&UDF_I(inode)->i_data_sem); brelse(epos.bh); if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_VARCONV)) return udf_fixed_to_variable(ret); else return ret; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2413_0
crossvul-cpp_data_bad_341_4
/* * PKCS15 emulation layer for EstEID card. * * Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net> * Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "internal.h" #include "opensc.h" #include "pkcs15.h" #include "esteid.h" int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *); static void set_string (char **strp, const char *value) { if (*strp) free (*strp); *strp = value ? strdup (value) : NULL; } int select_esteid_df (sc_card_t * card) { int r; sc_path_t tmppath; sc_format_path ("3F00EEEE", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed"); return r; } static int sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[r] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } static int esteid_detect_card(sc_pkcs15_card_t *p15card) { if (is_esteid_card(p15card->card)) return SC_SUCCESS; else return SC_ERROR_WRONG_CARD; } int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_esteid_init(p15card); else { int r = esteid_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_esteid_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_4
crossvul-cpp_data_good_2529_1
/* * wildmidi_lib.c -- Midi Wavetable Processing library * * Copyright (C) WildMIDI Developers 2001-2016 * * This file is part of WildMIDI. * * WildMIDI is free software: you can redistribute and/or modify the player * under the terms of the GNU General Public License and you can redistribute * and/or modify the library under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either version 3 of * the licenses, or(at your option) any later version. * * WildMIDI is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License and the * GNU Lesser General Public License along with WildMIDI. If not, see * <http://www.gnu.org/licenses/>. */ #define _WILDMIDI_LIB_C #include "config.h" #include <stdint.h> #include <errno.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wm_error.h" #include "file_io.h" #include "lock.h" #include "reverb.h" #include "gus_pat.h" #include "common.h" #include "wildmidi_lib.h" #include "filenames.h" #include "internal_midi.h" #include "f_hmi.h" #include "f_hmp.h" #include "f_midi.h" #include "f_mus.h" #include "f_xmidi.h" #include "patches.h" #include "sample.h" #include "mus2mid.h" #include "xmi2mid.h" /* * ========================= * Global Data and Data Structs * ========================= */ static int WM_Initialized = 0; uint16_t _WM_MixerOptions = 0; uint16_t _WM_SampleRate; int16_t _WM_MasterVolume; /* when converting files to midi */ typedef struct _cvt_options { int lock; uint16_t xmi_convert_type; uint16_t frequency; } _cvt_options; static _cvt_options WM_ConvertOptions = {0, 0, 0}; float _WM_reverb_room_width = 16.875f; float _WM_reverb_room_length = 22.5f; float _WM_reverb_listen_posx = 8.4375f; float _WM_reverb_listen_posy = 16.875f; int _WM_fix_release = 0; int _WM_auto_amp = 0; int _WM_auto_amp_with_amp = 0; struct _miditrack { uint32_t length; uint32_t ptr; uint32_t delta; uint8_t running_event; uint8_t EOT; }; struct _mdi_patches { struct _patch *patch; struct _mdi_patch *next; }; #define FPBITS 10 #define FPMASK ((1L<<FPBITS)-1L) /* Gauss Interpolation code adapted from code supplied by Eric. A. Welsh */ static double newt_coeffs[58][58]; /* for start/end of samples */ #define MAX_GAUSS_ORDER 34 /* 34 is as high as we can go before errors crop up */ static double *gauss_table = NULL; /* *gauss_table[1<<FPBITS] */ static int gauss_n = MAX_GAUSS_ORDER; static int gauss_lock; static void init_gauss(void) { /* init gauss table */ int n = gauss_n; int m, i, k, n_half = (n >> 1); int j; int sign; double ck; double x, x_inc, xz; double z[35]; double *gptr, *t; _WM_Lock(&gauss_lock); if (gauss_table) { _WM_Unlock(&gauss_lock); return; } newt_coeffs[0][0] = 1; for (i = 0; i <= n; i++) { newt_coeffs[i][0] = 1; newt_coeffs[i][i] = 1; if (i > 1) { newt_coeffs[i][0] = newt_coeffs[i - 1][0] / i; newt_coeffs[i][i] = newt_coeffs[i - 1][0] / i; } for (j = 1; j < i; j++) { newt_coeffs[i][j] = newt_coeffs[i - 1][j - 1] + newt_coeffs[i - 1][j]; if (i > 1) newt_coeffs[i][j] /= i; } z[i] = i / (4 * M_PI); } for (i = 0; i <= n; i++) for (j = 0, sign = (int) pow(-1, i); j <= i; j++, sign *= -1) newt_coeffs[i][j] *= sign; t = malloc((1<<FPBITS) * (n + 1) * sizeof(double)); x_inc = 1.0 / (1<<FPBITS); for (m = 0, x = 0.0; m < (1<<FPBITS); m++, x += x_inc) { xz = (x + n_half) / (4 * M_PI); gptr = &t[m * (n + 1)]; for (k = 0; k <= n; k++) { ck = 1.0; for (i = 0; i <= n; i++) { if (i == k) continue; ck *= (sin(xz - z[i])) / (sin(z[k] - z[i])); } *gptr++ = ck; } } gauss_table = t; _WM_Unlock(&gauss_lock); } static void free_gauss(void) { _WM_Lock(&gauss_lock); free(gauss_table); gauss_table = NULL; _WM_Unlock(&gauss_lock); } struct _hndl { void * handle; struct _hndl *next; struct _hndl *prev; }; static struct _hndl * first_handle = NULL; #define MAX_AUTO_AMP 2.0 /* * ========================= * Internal Functions * ========================= */ void _cvt_reset_options (void) { _WM_Lock(&WM_ConvertOptions.lock); WM_ConvertOptions.xmi_convert_type = 0; WM_ConvertOptions.frequency = 0; _WM_Unlock(&WM_ConvertOptions.lock); } uint16_t _cvt_get_option (uint16_t tag) { uint16_t r = 0; _WM_Lock(&WM_ConvertOptions.lock); switch (tag) { case WM_CO_XMI_TYPE: r = WM_ConvertOptions.xmi_convert_type; break; case WM_CO_FREQUENCY: r = WM_ConvertOptions.frequency; break; } _WM_Unlock(&WM_ConvertOptions.lock); return r; } static void WM_InitPatches(void) { int i; for (i = 0; i < 128; i++) { _WM_patch[i] = NULL; } } static void WM_FreePatches(void) { int i; struct _patch * tmp_patch; struct _sample * tmp_sample; _WM_Lock(&_WM_patch_lock); for (i = 0; i < 128; i++) { while (_WM_patch[i]) { while (_WM_patch[i]->first_sample) { tmp_sample = _WM_patch[i]->first_sample->next; free(_WM_patch[i]->first_sample->data); free(_WM_patch[i]->first_sample); _WM_patch[i]->first_sample = tmp_sample; } free(_WM_patch[i]->filename); tmp_patch = _WM_patch[i]->next; free(_WM_patch[i]); _WM_patch[i] = tmp_patch; } } _WM_Unlock(&_WM_patch_lock); } /* wm_strdup -- adds extra space for appending up to 4 chars */ static char *wm_strdup (const char *str) { size_t l = strlen(str) + 5; char *d = (char *) malloc(l * sizeof(char)); if (d) { strcpy(d, str); return (d); } return (NULL); } static inline int wm_isdigit(int c) { return (c >= '0' && c <= '9'); } static inline int wm_isupper(int c) { return (c >= 'A' && c <= 'Z'); } static inline int wm_tolower(int c) { return ((wm_isupper(c)) ? (c | ('a' - 'A')) : c); } #if 0 /* clang whines that these aren't used. */ static inline int wm_islower(int c) { return (c >= 'a' && c <= 'z'); } static inline int wm_toupper(int c) { return ((wm_islower(c)) ? (c & ~('a' - 'A')) : c); } #endif static int wm_strcasecmp(const char *s1, const char * s2) { const char * p1 = s1; const char * p2 = s2; char c1, c2; if (p1 == p2) return 0; do { c1 = wm_tolower (*p1++); c2 = wm_tolower (*p2++); if (c1 == '\0') break; } while (c1 == c2); return (int)(c1 - c2); } static int wm_strncasecmp(const char *s1, const char *s2, size_t n) { const char * p1 = s1; const char * p2 = s2; char c1, c2; if (p1 == p2 || n == 0) return 0; do { c1 = wm_tolower (*p1++); c2 = wm_tolower (*p2++); if (c1 == '\0' || c1 != c2) break; } while (--n > 0); return (int)(c1 - c2); } #define TOKEN_CNT_INC 8 static char** WM_LC_Tokenize_Line(char *line_data) { int line_length = (int) strlen(line_data); int token_data_length = 0; int line_ofs = 0; int token_start = 0; char **token_data = NULL; int token_count = 0; if (!line_length) return (NULL); do { /* ignore everything after # */ if (line_data[line_ofs] == '#') { break; } if ((line_data[line_ofs] == ' ') || (line_data[line_ofs] == '\t')) { /* whitespace means we aren't in a token */ if (token_start) { token_start = 0; line_data[line_ofs] = '\0'; } } else { if (!token_start) { /* the start of a token in the line */ token_start = 1; if (token_count >= token_data_length) { token_data_length += TOKEN_CNT_INC; token_data = realloc(token_data, token_data_length * sizeof(char *)); if (token_data == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM,"to parse config", errno); return (NULL); } } token_data[token_count] = &line_data[line_ofs]; token_count++; } } line_ofs++; } while (line_ofs != line_length); /* if we have found some tokens then add a null token to the end */ if (token_count) { if (token_count >= token_data_length) { token_data = realloc(token_data, ((token_count + 1) * sizeof(char *))); } token_data[token_count] = NULL; } return (token_data); } static int load_config(const char *config_file, const char *conf_dir) { uint32_t config_size = 0; char *config_buffer = NULL; const char *dir_end = NULL; char *config_dir = NULL; uint32_t config_ptr = 0; uint32_t line_start_ptr = 0; uint16_t patchid = 0; struct _patch * tmp_patch; char **line_tokens = NULL; int token_count = 0; config_buffer = (char *) _WM_BufferFile(config_file, &config_size); if (!config_buffer) { WM_FreePatches(); return (-1); } if (conf_dir) { if (!(config_dir = wm_strdup(conf_dir))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_buffer); return (-1); } } else { dir_end = FIND_LAST_DIRSEP(config_file); if (dir_end) { config_dir = malloc((dir_end - config_file + 2)); if (config_dir == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_buffer); return (-1); } strncpy(config_dir, config_file, (dir_end - config_file + 1)); config_dir[dir_end - config_file + 1] = '\0'; } } config_ptr = 0; line_start_ptr = 0; /* handle files without a newline at the end: this relies on * _WM_BufferFile() allocating the buffer with one extra byte */ config_buffer[config_size] = '\n'; while (config_ptr <= config_size) { if (config_buffer[config_ptr] == '\r' || config_buffer[config_ptr] == '\n') { config_buffer[config_ptr] = '\0'; if (config_ptr != line_start_ptr) { _WM_Global_ErrorI = 0; /* because WM_LC_Tokenize_Line() can legitimately return NULL */ line_tokens = WM_LC_Tokenize_Line(&config_buffer[line_start_ptr]); if (line_tokens) { if (wm_strcasecmp(line_tokens[0], "dir") == 0) { free(config_dir); if (!line_tokens[1]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(missing name in dir line)", 0); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } else if (!(config_dir = wm_strdup(line_tokens[1]))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } if (!IS_DIR_SEPARATOR(config_dir[strlen(config_dir) - 1])) { config_dir[strlen(config_dir) + 1] = '\0'; config_dir[strlen(config_dir)] = DIR_SEPARATOR_CHAR; } } else if (wm_strcasecmp(line_tokens[0], "source") == 0) { char *new_config = NULL; if (!line_tokens[1]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(missing name in source line)", 0); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } else if (!IS_ABSOLUTE_PATH(line_tokens[1]) && config_dir) { new_config = malloc(strlen(config_dir) + strlen(line_tokens[1]) + 1); if (new_config == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } strcpy(new_config, config_dir); strcpy(&new_config[strlen(config_dir)], line_tokens[1]); } else { if (!(new_config = wm_strdup(line_tokens[1]))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } } if (load_config(new_config, config_dir) == -1) { free(new_config); free(line_tokens); free(config_buffer); free(config_dir); return (-1); } free(new_config); } else if (wm_strcasecmp(line_tokens[0], "bank") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in bank line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } patchid = (atoi(line_tokens[1]) & 0xFF) << 8; } else if (wm_strcasecmp(line_tokens[0], "drumset") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in drumset line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } patchid = ((atoi(line_tokens[1]) & 0xFF) << 8) | 0x80; } else if (wm_strcasecmp(line_tokens[0], "reverb_room_width") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_room_width line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_room_width = (float) atof(line_tokens[1]); if (_WM_reverb_room_width < 1.0f) { _WM_DEBUG_MSG("%s: reverb_room_width < 1 meter, setting to minimum of 1 meter", config_file); _WM_reverb_room_width = 1.0f; } else if (_WM_reverb_room_width > 100.0f) { _WM_DEBUG_MSG("%s: reverb_room_width > 100 meters, setting to maximum of 100 meters", config_file); _WM_reverb_room_width = 100.0f; } } else if (wm_strcasecmp(line_tokens[0], "reverb_room_length") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_room_length line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_room_length = (float) atof(line_tokens[1]); if (_WM_reverb_room_length < 1.0f) { _WM_DEBUG_MSG("%s: reverb_room_length < 1 meter, setting to minimum of 1 meter", config_file); _WM_reverb_room_length = 1.0f; } else if (_WM_reverb_room_length > 100.0f) { _WM_DEBUG_MSG("%s: reverb_room_length > 100 meters, setting to maximum of 100 meters", config_file); _WM_reverb_room_length = 100.0f; } } else if (wm_strcasecmp(line_tokens[0], "reverb_listener_posx") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_listen_posx line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_listen_posx = (float) atof(line_tokens[1]); if ((_WM_reverb_listen_posx > _WM_reverb_room_width) || (_WM_reverb_listen_posx < 0.0f)) { _WM_DEBUG_MSG("%s: reverb_listen_posx set outside of room", config_file); _WM_reverb_listen_posx = _WM_reverb_room_width / 2.0f; } } else if (wm_strcasecmp(line_tokens[0], "reverb_listener_posy") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_listen_posy line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_listen_posy = (float) atof(line_tokens[1]); if ((_WM_reverb_listen_posy > _WM_reverb_room_width) || (_WM_reverb_listen_posy < 0.0f)) { _WM_DEBUG_MSG("%s: reverb_listen_posy set outside of room", config_file); _WM_reverb_listen_posy = _WM_reverb_room_length * 0.75f; } } else if (wm_strcasecmp(line_tokens[0], "guspat_editor_author_cant_read_so_fix_release_time_for_me") == 0) { _WM_fix_release = 1; } else if (wm_strcasecmp(line_tokens[0], "auto_amp") == 0) { _WM_auto_amp = 1; } else if (wm_strcasecmp(line_tokens[0], "auto_amp_with_amp") == 0) { _WM_auto_amp = 1; _WM_auto_amp_with_amp = 1; } else if (wm_isdigit(line_tokens[0][0])) { patchid = (patchid & 0xFF80) | (atoi(line_tokens[0]) & 0x7F); if (_WM_patch[(patchid & 0x7F)] == NULL) { _WM_patch[(patchid & 0x7F)] = malloc(sizeof(struct _patch)); if (_WM_patch[(patchid & 0x7F)] == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } tmp_patch = _WM_patch[(patchid & 0x7F)]; tmp_patch->patchid = patchid; tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; tmp_patch->next = NULL; tmp_patch->first_sample = NULL; tmp_patch->loaded = 0; tmp_patch->inuse_count = 0; } else { tmp_patch = _WM_patch[(patchid & 0x7F)]; if (tmp_patch->patchid == patchid) { free(tmp_patch->filename); tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; } else { if (tmp_patch->next) { while (tmp_patch->next) { if (tmp_patch->next->patchid == patchid) break; tmp_patch = tmp_patch->next; } if (tmp_patch->next == NULL) { if ((tmp_patch->next = malloc(sizeof(struct _patch))) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } tmp_patch = tmp_patch->next; tmp_patch->patchid = patchid; tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; tmp_patch->next = NULL; tmp_patch->first_sample = NULL; tmp_patch->loaded = 0; tmp_patch->inuse_count = 0; } else { tmp_patch = tmp_patch->next; free(tmp_patch->filename); tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; } } else { tmp_patch->next = malloc( sizeof(struct _patch)); if (tmp_patch->next == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } tmp_patch = tmp_patch->next; tmp_patch->patchid = patchid; tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; tmp_patch->next = NULL; tmp_patch->first_sample = NULL; tmp_patch->loaded = 0; tmp_patch->inuse_count = 0; } } } if (!line_tokens[1]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(missing name in patch line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } else if (!IS_ABSOLUTE_PATH(line_tokens[1]) && config_dir) { tmp_patch->filename = malloc(strlen(config_dir) + strlen(line_tokens[1]) + 5); if (tmp_patch->filename == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } strcpy(tmp_patch->filename, config_dir); strcat(tmp_patch->filename, line_tokens[1]); } else { if (!(tmp_patch->filename = wm_strdup(line_tokens[1]))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } } if (wm_strncasecmp(&tmp_patch->filename[strlen(tmp_patch->filename) - 4], ".pat", 4) != 0) { strcat(tmp_patch->filename, ".pat"); } tmp_patch->env[0].set = 0x00; tmp_patch->env[1].set = 0x00; tmp_patch->env[2].set = 0x00; tmp_patch->env[3].set = 0x00; tmp_patch->env[4].set = 0x00; tmp_patch->env[5].set = 0x00; tmp_patch->keep = 0; tmp_patch->remove = 0; token_count = 0; while (line_tokens[token_count]) { if (wm_strncasecmp(line_tokens[token_count], "amp=", 4) == 0) { if (!wm_isdigit(line_tokens[token_count][4])) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "amp="); } else { tmp_patch->amp = (atoi(&line_tokens[token_count][4]) << 10) / 100; } } else if (wm_strncasecmp(line_tokens[token_count], "note=", 5) == 0) { if (!wm_isdigit(line_tokens[token_count][5])) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "note="); } else { tmp_patch->note = atoi(&line_tokens[token_count][5]); } } else if (wm_strncasecmp(line_tokens[token_count], "env_time", 8) == 0) { if ((!wm_isdigit(line_tokens[token_count][8])) || (!wm_isdigit(line_tokens[token_count][10])) || (line_tokens[token_count][9] != '=')) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_time"); } else { uint32_t env_no = atoi(&line_tokens[token_count][8]); if (env_no > 5) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_time"); } else { tmp_patch->env[env_no].time = (float) atof(&line_tokens[token_count][10]); if ((tmp_patch->env[env_no].time > 45000.0f) || (tmp_patch->env[env_no].time < 1.47f)) { _WM_DEBUG_MSG("%s: range error in patch line %s", config_file, "env_time"); tmp_patch->env[env_no].set &= 0xFE; } else { tmp_patch->env[env_no].set |= 0x01; } } } } else if (wm_strncasecmp(line_tokens[token_count], "env_level", 9) == 0) { if ((!wm_isdigit(line_tokens[token_count][9])) || (!wm_isdigit(line_tokens[token_count][11])) || (line_tokens[token_count][10] != '=')) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_level"); } else { uint32_t env_no = atoi(&line_tokens[token_count][9]); if (env_no > 5) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_level"); } else { tmp_patch->env[env_no].level = (float) atof(&line_tokens[token_count][11]); if ((tmp_patch->env[env_no].level > 1.0f) || (tmp_patch->env[env_no].level < 0.0f)) { _WM_DEBUG_MSG("%s: range error in patch line for %s", config_file, "env_level"); tmp_patch->env[env_no].set &= 0xFD; } else { tmp_patch->env[env_no].set |= 0x02; } } } } else if (wm_strcasecmp(line_tokens[token_count], "keep=loop") == 0) { tmp_patch->keep |= SAMPLE_LOOP; } else if (wm_strcasecmp(line_tokens[token_count], "keep=env") == 0) { tmp_patch->keep |= SAMPLE_ENVELOPE; } else if (wm_strcasecmp(line_tokens[token_count], "remove=sustain") == 0) { tmp_patch->remove |= SAMPLE_SUSTAIN; } else if (wm_strcasecmp(line_tokens[token_count], "remove=clamped") == 0) { tmp_patch->remove |= SAMPLE_CLAMPED; } token_count++; } } } else if (_WM_Global_ErrorI) { /* malloc() failure in WM_LC_Tokenize_Line() */ WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } /* free up tokens */ free(line_tokens); } line_start_ptr = config_ptr + 1; } config_ptr++; } free(config_buffer); free(config_dir); return (0); } static int WM_LoadConfig(const char *config_file) { return load_config(config_file, NULL); } static int add_handle(void * handle) { struct _hndl *tmp_handle = NULL; if (first_handle == NULL) { first_handle = malloc(sizeof(struct _hndl)); if (first_handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, " to get ram", errno); return (-1); } first_handle->handle = handle; first_handle->prev = NULL; first_handle->next = NULL; } else { tmp_handle = first_handle; if (tmp_handle->next) { while (tmp_handle->next) tmp_handle = tmp_handle->next; } tmp_handle->next = malloc(sizeof(struct _hndl)); if (tmp_handle->next == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, " to get ram", errno); return (-1); } tmp_handle->next->prev = tmp_handle; tmp_handle = tmp_handle->next; tmp_handle->next = NULL; tmp_handle->handle = handle; } return (0); } //#define DEBUG_RESAMPLE #ifdef DEBUG_RESAMPLE #define RESAMPLE_DEBUGI(dx,dy) fprintf(stderr,"\r%s, %i\n",dx,dy) #define RESAMPLE_DEBUGS(dx) fprintf(stderr,"\r%s\n",dx) #else #define RESAMPLE_DEBUGI(dx,dy) #define RESAMPLE_DEBUGS(dx) #endif static int WM_GetOutput_Linear(midi * handle, int8_t *buffer, uint32_t size) { uint32_t buffer_used = 0; uint32_t i; struct _mdi *mdi = (struct _mdi *) handle; uint32_t real_samples_to_mix = 0; uint32_t data_pos; int32_t premix, left_mix, right_mix; // int32_t vol_mul; struct _note *note_data = NULL; uint32_t count; struct _event *event = mdi->current_event; int32_t *tmp_buffer; int32_t *out_buffer; _WM_Lock(&mdi->lock); buffer_used = 0; memset(buffer, 0, size); if ( (size / 2) > mdi->mix_buffer_size) { if ( (size / 2) <= ( mdi->mix_buffer_size * 2 )) { mdi->mix_buffer_size += MEM_CHUNK; } else { mdi->mix_buffer_size = size / 2; } mdi->mix_buffer = realloc(mdi->mix_buffer, mdi->mix_buffer_size * sizeof(int32_t)); } tmp_buffer = mdi->mix_buffer; memset(tmp_buffer, 0, ((size / 2) * sizeof(int32_t))); out_buffer = tmp_buffer; do { if (__builtin_expect((!mdi->samples_to_mix), 0)) { while ((!mdi->samples_to_mix) && (event->do_event)) { event->do_event(mdi, &event->event_data); if ((mdi->extra_info.mixer_options & WM_MO_LOOP) && (event[0].do_event == *_WM_do_meta_endoftrack)) { _WM_ResetToStart(mdi); event = mdi->current_event; } else { mdi->samples_to_mix = event->samples_to_next; event++; mdi->current_event = event; } } if (__builtin_expect((!mdi->samples_to_mix), 0)) { if (mdi->extra_info.current_sample >= mdi->extra_info.approx_total_samples) { break; } else if ((mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample) > (size >> 2)) { mdi->samples_to_mix = size >> 2; } else { mdi->samples_to_mix = mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample; } } } if (__builtin_expect((mdi->samples_to_mix > (size >> 2)), 1)) { real_samples_to_mix = size >> 2; } else { real_samples_to_mix = mdi->samples_to_mix; if (real_samples_to_mix == 0) { continue; } } /* do mixing here */ count = real_samples_to_mix; do { note_data = mdi->note; left_mix = right_mix = 0; RESAMPLE_DEBUGI("SAMPLES_TO_MIX",count); if (__builtin_expect((note_data != NULL), 1)) { RESAMPLE_DEBUGS("Processing Notes"); while (note_data) { /* * =================== * resample the sample * =================== */ data_pos = note_data->sample_pos >> FPBITS; premix = ((note_data->sample->data[data_pos] + (((note_data->sample->data[data_pos + 1] - note_data->sample->data[data_pos]) * (int32_t)(note_data->sample_pos & FPMASK)) / 1024)) * (note_data->env_level >> 12)) / 1024; left_mix += (premix * (int32_t)note_data->left_mix_volume) / 1024; right_mix += (premix * (int32_t)note_data->right_mix_volume) / 1024; /* * ======================== * sample position checking * ======================== */ #ifdef DEBUG_RESAMPLE fprintf(stderr,"\r\n%d -> INC %i, ENV %i, LEVEL %i, TARGET %d, RATE %i, SAMPLE POS %i, SAMPLE LENGTH %i, PREMIX %i (%i:%i)", (uint32_t)note_data, note_data->env_inc, note_data->env, note_data->env_level, note_data->sample->env_target[note_data->env], note_data->sample->env_rate[note_data->env], note_data->sample_pos, note_data->sample->data_length, premix, left_mix, right_mix); if (note_data->modes & SAMPLE_LOOP) fprintf(stderr,", LOOP %i + %i", note_data->sample->loop_start, note_data->sample->loop_size); fprintf(stderr,"\r\n"); #endif note_data->sample_pos += note_data->sample_inc; if (__builtin_expect((note_data->modes & SAMPLE_LOOP), 1)) { if (__builtin_expect( (note_data->sample_pos > note_data->sample->loop_end), 0)) { note_data->sample_pos = note_data->sample->loop_start + ((note_data->sample_pos - note_data->sample->loop_start) % note_data->sample->loop_size); } } else if (__builtin_expect( (note_data->sample_pos >= note_data->sample->data_length), 0)) { goto _END_THIS_NOTE; } if (__builtin_expect((note_data->env_inc == 0), 0)) { note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: 0 env_inc"); continue; } note_data->env_level += note_data->env_inc; if (note_data->env_inc < 0) { if (__builtin_expect((note_data->env_level > note_data->sample->env_target[note_data->env]), 0)) { note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: env_lvl > env_target"); continue; } } else if (note_data->env_inc > 0) { if (__builtin_expect((note_data->env_level < note_data->sample->env_target[note_data->env]), 0)) { note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: env_lvl < env_target"); continue; } } // Yes could have a condition here but // it would crete another bottleneck note_data->env_level = note_data->sample->env_target[note_data->env]; switch (note_data->env) { case 0: if (!(note_data->modes & SAMPLE_ENVELOPE)) { note_data->env_inc = 0; note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: No Envelope"); continue; } break; case 2: if (note_data->modes & SAMPLE_SUSTAIN /*|| note_data->hold*/) { note_data->env_inc = 0; note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: SAMPLE_SUSTAIN"); continue; } else if (note_data->modes & SAMPLE_CLAMPED) { note_data->env = 5; if (note_data->env_level > note_data->sample->env_target[5]) { note_data->env_inc = -note_data->sample->env_rate[5]; } else { note_data->env_inc = note_data->sample->env_rate[5]; } continue; } break; case 5: if (__builtin_expect((note_data->env_level == 0), 1)) { goto _END_THIS_NOTE; } /* sample release */ if (note_data->modes & SAMPLE_LOOP) note_data->modes ^= SAMPLE_LOOP; note_data->env_inc = 0; note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: Sample Release"); continue; case 6: _END_THIS_NOTE: if (__builtin_expect((note_data->replay != NULL), 1)) { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while (nte_array != note_data); } if (prev_note) { prev_note->next = note_data->replay; } else { mdi->note = note_data->replay; } note_data->replay->next = note_data->next; note_data = note_data->replay; note_data->active = 1; } } else { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while ((nte_array != note_data) && (nte_array)); } if (prev_note) { prev_note->next = note_data->next; } else { mdi->note = note_data->next; } note_data = note_data->next; } } RESAMPLE_DEBUGS("Next Note: Killed Off Note"); continue; } note_data->env++; if (note_data->is_off == 1) { _WM_do_note_off_extra(note_data); } else { if (note_data->env_level >= note_data->sample->env_target[note_data->env]) { note_data->env_inc = -note_data->sample->env_rate[note_data->env]; } else { note_data->env_inc = note_data->sample->env_rate[note_data->env]; } } note_data = note_data->next; #ifdef DEBUG_RESAMPLE if (note_data != NULL) RESAMPLE_DEBUGI("Next Note: Next ENV ", note_data->env); else RESAMPLE_DEBUGS("Next Note: Next ENV"); #endif continue; } } *tmp_buffer++ = left_mix; *tmp_buffer++ = right_mix; } while (--count); buffer_used += real_samples_to_mix * 4; size -= (real_samples_to_mix << 2); mdi->extra_info.current_sample += real_samples_to_mix; mdi->samples_to_mix -= real_samples_to_mix; } while (size); tmp_buffer = out_buffer; if (mdi->extra_info.mixer_options & WM_MO_REVERB) { _WM_do_reverb(mdi->reverb, tmp_buffer, (buffer_used / 2)); } //_WM_DynamicVolumeAdjust(mdi, tmp_buffer, (buffer_used/2)); for (i = 0; i < buffer_used; i += 4) { left_mix = *tmp_buffer++; right_mix = *tmp_buffer++; /* * =================== * Write to the buffer * =================== */ #ifdef WORDS_BIGENDIAN (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = left_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; #else (*buffer++) = left_mix & 0xff; (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); #endif } _WM_Unlock(&mdi->lock); return (buffer_used); } static int WM_GetOutput_Gauss(midi * handle, int8_t *buffer, uint32_t size) { uint32_t buffer_used = 0; uint32_t i; struct _mdi *mdi = (struct _mdi *) handle; uint32_t real_samples_to_mix = 0; uint32_t data_pos; int32_t premix, left_mix, right_mix; struct _note *note_data = NULL; uint32_t count; int16_t *sptr; double y, xd; double *gptr, *gend; int left, right, temp_n; int ii, jj; struct _event *event = mdi->current_event; int32_t *tmp_buffer; int32_t *out_buffer; _WM_Lock(&mdi->lock); buffer_used = 0; memset(buffer, 0, size); if ( (size / 2) > mdi->mix_buffer_size) { if ( (size / 2) <= ( mdi->mix_buffer_size * 2 )) { mdi->mix_buffer_size += MEM_CHUNK; } else { mdi->mix_buffer_size = size / 2; } mdi->mix_buffer = realloc(mdi->mix_buffer, mdi->mix_buffer_size * sizeof(int32_t)); } tmp_buffer = mdi->mix_buffer; memset(tmp_buffer, 0, ((size / 2) * sizeof(int32_t))); out_buffer = tmp_buffer; do { if (__builtin_expect((!mdi->samples_to_mix), 0)) { while ((!mdi->samples_to_mix) && (event->do_event)) { event->do_event(mdi, &event->event_data); if ((mdi->extra_info.mixer_options & WM_MO_LOOP) && (event[0].do_event == *_WM_do_meta_endoftrack)) { _WM_ResetToStart(mdi); event = mdi->current_event; } else { mdi->samples_to_mix = event->samples_to_next; event++; mdi->current_event = event; } } if (!mdi->samples_to_mix) { if (mdi->extra_info.current_sample >= mdi->extra_info.approx_total_samples) { break; } else if ((mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample) > (size >> 2)) { mdi->samples_to_mix = size >> 2; } else { mdi->samples_to_mix = mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample; } } } if (__builtin_expect((mdi->samples_to_mix > (size >> 2)), 1)) { real_samples_to_mix = size >> 2; } else { real_samples_to_mix = mdi->samples_to_mix; if (real_samples_to_mix == 0) { continue; } } /* do mixing here */ count = real_samples_to_mix; do { note_data = mdi->note; left_mix = right_mix = 0; if (__builtin_expect((note_data != NULL), 1)) { while (note_data) { /* * =================== * resample the sample * =================== */ data_pos = note_data->sample_pos >> FPBITS; /* check to see if we're near one of the ends */ left = data_pos; right = (note_data->sample->data_length >> FPBITS) - left - 1; temp_n = (right << 1) - 1; if (temp_n <= 0) temp_n = 1; if (temp_n > (left << 1) + 1) temp_n = (left << 1) + 1; /* use Newton if we can't fill the window */ if (temp_n < gauss_n) { xd = note_data->sample_pos & FPMASK; xd /= (1L << FPBITS); xd += temp_n >> 1; y = 0; sptr = note_data->sample->data + (note_data->sample_pos >> FPBITS) - (temp_n >> 1); for (ii = temp_n; ii;) { for (jj = 0; jj <= ii; jj++) y += sptr[jj] * newt_coeffs[ii][jj]; y *= xd - --ii; } y += *sptr; } else { /* otherwise, use Gauss as usual */ y = 0; gptr = &gauss_table[(note_data->sample_pos & FPMASK) * (gauss_n + 1)]; gend = gptr + gauss_n; sptr = note_data->sample->data + (note_data->sample_pos >> FPBITS) - (gauss_n >> 1); do { y += *(sptr++) * *(gptr++); } while (gptr <= gend); } premix = (int32_t)((y * (note_data->env_level >> 12)) / 1024); left_mix += (premix * (int32_t)note_data->left_mix_volume) / 1024; right_mix += (premix * (int32_t)note_data->right_mix_volume) / 1024; /* * ======================== * sample position checking * ======================== */ note_data->sample_pos += note_data->sample_inc; if (__builtin_expect( (note_data->sample_pos > note_data->sample->loop_end), 0)) { if (note_data->modes & SAMPLE_LOOP) { note_data->sample_pos = note_data->sample->loop_start + ((note_data->sample_pos - note_data->sample->loop_start) % note_data->sample->loop_size); } else if (__builtin_expect( (note_data->sample_pos >= note_data->sample->data_length), 0)) { goto _END_THIS_NOTE; } } if (__builtin_expect((note_data->env_inc == 0), 0)) { /* fprintf(stderr,"\r\nINC = 0, ENV %i, LEVEL %i, TARGET %d, RATE %i\r\n", note_data->env, note_data->env_level, note_data->sample->env_target[note_data->env], note_data->sample->env_rate[note_data->env]); */ note_data = note_data->next; continue; } note_data->env_level += note_data->env_inc; /* fprintf(stderr,"\r\nENV %i, LEVEL %i, TARGET %d, RATE %i, INC %i\r\n", note_data->env, note_data->env_level, note_data->sample->env_target[note_data->env], note_data->sample->env_rate[note_data->env], note_data->env_inc); */ if (note_data->env_inc < 0) { if (note_data->env_level > note_data->sample->env_target[note_data->env]) { note_data = note_data->next; continue; } } else if (note_data->env_inc > 0) { if (note_data->env_level < note_data->sample->env_target[note_data->env]) { note_data = note_data->next; continue; } } // Yes could have a condition here but // it would crete another bottleneck note_data->env_level = note_data->sample->env_target[note_data->env]; switch (note_data->env) { case 0: if (!(note_data->modes & SAMPLE_ENVELOPE)) { note_data->env_inc = 0; note_data = note_data->next; continue; } break; case 2: if (note_data->modes & SAMPLE_SUSTAIN /*|| note_data->hold*/) { note_data->env_inc = 0; note_data = note_data->next; continue; } else if (note_data->modes & SAMPLE_CLAMPED) { note_data->env = 5; if (note_data->env_level > note_data->sample->env_target[5]) { note_data->env_inc = -note_data->sample->env_rate[5]; } else { note_data->env_inc = note_data->sample->env_rate[5]; } continue; } break; case 5: if (__builtin_expect((note_data->env_level == 0), 1)) { goto _END_THIS_NOTE; } /* sample release */ if (note_data->modes & SAMPLE_LOOP) note_data->modes ^= SAMPLE_LOOP; note_data->env_inc = 0; note_data = note_data->next; continue; case 6: _END_THIS_NOTE: if (__builtin_expect((note_data->replay != NULL), 1)) { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while (nte_array != note_data); } if (prev_note) { prev_note->next = note_data->replay; } else { mdi->note = note_data->replay; } note_data->replay->next = note_data->next; note_data = note_data->replay; note_data->active = 1; } } else { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while ((nte_array != note_data) && (nte_array)); } if (prev_note) { prev_note->next = note_data->next; } else { mdi->note = note_data->next; } note_data = note_data->next; } } continue; } note_data->env++; if (note_data->is_off == 1) { _WM_do_note_off_extra(note_data); } else { if (note_data->env_level >= note_data->sample->env_target[note_data->env]) { note_data->env_inc = -note_data->sample->env_rate[note_data->env]; } else { note_data->env_inc = note_data->sample->env_rate[note_data->env]; } } note_data = note_data->next; continue; } } *tmp_buffer++ = left_mix; *tmp_buffer++ = right_mix; } while (--count); buffer_used += real_samples_to_mix * 4; size -= (real_samples_to_mix << 2); mdi->extra_info.current_sample += real_samples_to_mix; mdi->samples_to_mix -= real_samples_to_mix; } while (size); tmp_buffer = out_buffer; if (mdi->extra_info.mixer_options & WM_MO_REVERB) { _WM_do_reverb(mdi->reverb, tmp_buffer, (buffer_used / 2)); } // _WM_DynamicVolumeAdjust(mdi, tmp_buffer, (buffer_used/2)); for (i = 0; i < buffer_used; i += 4) { left_mix = *tmp_buffer++; right_mix = *tmp_buffer++; /* * =================== * Write to the buffer * =================== */ #ifdef WORDS_BIGENDIAN (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = left_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; #else (*buffer++) = left_mix & 0xff; (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); #endif } _WM_Unlock(&mdi->lock); return (buffer_used); } /* * ========================= * External Functions * ========================= */ WM_SYMBOL int WildMidi_ConvertToMidi (const char *file, uint8_t **out, uint32_t *size) { uint8_t *buf; int ret; if (!file) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0); return (-1); } if ((buf = (uint8_t *) _WM_BufferFile(file, size)) == NULL) { return (-1); } ret = WildMidi_ConvertBufferToMidi(buf, *size, out, size); free(buf); return ret; } WM_SYMBOL int WildMidi_ConvertBufferToMidi (uint8_t *in, uint32_t insize, uint8_t **out, uint32_t *outsize) { if (!in || !out || !outsize) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL params)", 0); return (-1); } if (!memcmp(in, "FORM", 4)) { if (_WM_xmi2midi(in, insize, out, outsize, _cvt_get_option(WM_CO_XMI_TYPE)) < 0) { return (-1); } } else if (!memcmp(in, "MUS", 3)) { if (_WM_mus2midi(in, insize, out, outsize, _cvt_get_option(WM_CO_FREQUENCY)) < 0) { return (-1); } } else if (!memcmp(in, "MThd", 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, 0, "Already a midi file", 0); return (-1); } else { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0); return (-1); } return (0); } WM_SYMBOL const char *WildMidi_GetString(uint16_t info) { static char WM_Version[] = "WildMidi Processing Library " PACKAGE_VERSION; switch (info) { case WM_GS_VERSION: return WM_Version; } return NULL; } WM_SYMBOL long WildMidi_GetVersion (void) { return (LIBWILDMIDI_VERSION); } WM_SYMBOL int WildMidi_Init(const char *config_file, uint16_t rate, uint16_t mixer_options) { if (WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_ALR_INIT, NULL, 0); return (-1); } if (config_file == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL config file pointer)", 0); return (-1); } WM_InitPatches(); if (WM_LoadConfig(config_file) == -1) { return (-1); } if (mixer_options & 0x0FF0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid option)", 0); WM_FreePatches(); return (-1); } _WM_MixerOptions = mixer_options; if (rate < 11025) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(rate out of bounds, range is 11025 - 65535)", 0); WM_FreePatches(); return (-1); } _WM_SampleRate = rate; gauss_lock = 0; _WM_patch_lock = 0; _WM_MasterVolume = 948; WM_Initialized = 1; return (0); } WM_SYMBOL int WildMidi_MasterVolume(uint8_t master_volume) { if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (master_volume > 127) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(master volume out of range, range is 0-127)", 0); return (-1); } _WM_MasterVolume = _WM_lin_volume[master_volume]; return (0); } WM_SYMBOL int WildMidi_Close(midi * handle) { struct _mdi *mdi = (struct _mdi *) handle; struct _hndl * tmp_handle; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (first_handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(no midi's open)", 0); return (-1); } _WM_Lock(&mdi->lock); if (first_handle->handle == handle) { tmp_handle = first_handle->next; free(first_handle); first_handle = tmp_handle; if (first_handle) first_handle->prev = NULL; } else { tmp_handle = first_handle; while (tmp_handle->handle != handle) { tmp_handle = tmp_handle->next; if (tmp_handle == NULL) { break; } } if (tmp_handle) { tmp_handle->prev->next = tmp_handle->next; if (tmp_handle->next) { tmp_handle->next->prev = tmp_handle->prev; } free(tmp_handle); } } _WM_freeMDI(mdi); return (0); } WM_SYMBOL midi *WildMidi_Open(const char *midifile) { uint8_t *mididata = NULL; uint32_t midisize = 0; uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midifile == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0); return (NULL); } if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) { return (NULL); } if (midisize < 18) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0); return (NULL); } if (memcmp(mididata,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(mididata, midisize); } else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(mididata, midisize); } else if (memcmp(mididata, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(mididata, midisize); } else if (memcmp(mididata, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(mididata, midisize); } else { ret = (void *) _WM_ParseNewMidi(mididata, midisize); } free(mididata); if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midibuffer == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0); return (NULL); } if (size > WM_MAXFILESIZE) { /* don't bother loading suspiciously long files */ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0); return (NULL); } if (size < 18) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0); return (NULL); } if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(midibuffer, size); } else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(midibuffer, size); } else if (memcmp(midibuffer, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(midibuffer, size); } else if (memcmp(midibuffer, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(midibuffer, size); } else { ret = (void *) _WM_ParseNewMidi(midibuffer, size); } if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } WM_SYMBOL int WildMidi_FastSeek(midi * handle, unsigned long int *sample_pos) { struct _mdi *mdi; struct _event *event; struct _note *note_data; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (sample_pos == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL seek position pointer)", 0); return (-1); } mdi = (struct _mdi *) handle; _WM_Lock(&mdi->lock); event = mdi->current_event; /* make sure we havent asked for a positions beyond the end of the song. */ if (*sample_pos > mdi->extra_info.approx_total_samples) { /* if so set the position to the end of the song */ *sample_pos = mdi->extra_info.approx_total_samples; } /* was end of song requested and are we are there? */ if (*sample_pos == mdi->extra_info.approx_total_samples) { /* yes */ _WM_Unlock(&mdi->lock); return (0); } /* did we want to fast forward? */ if (mdi->extra_info.current_sample > *sample_pos) { /* no - reset some stuff */ event = mdi->events; _WM_ResetToStart(handle); mdi->extra_info.current_sample = 0; mdi->samples_to_mix = 0; } if ((mdi->extra_info.current_sample + mdi->samples_to_mix) > *sample_pos) { mdi->samples_to_mix = (mdi->extra_info.current_sample + mdi->samples_to_mix) - *sample_pos; mdi->extra_info.current_sample = *sample_pos; } else { mdi->extra_info.current_sample += mdi->samples_to_mix; mdi->samples_to_mix = 0; while ((!mdi->samples_to_mix) && (event->do_event)) { event->do_event(mdi, &event->event_data); mdi->samples_to_mix = event->samples_to_next; if ((mdi->extra_info.current_sample + mdi->samples_to_mix) > *sample_pos) { mdi->samples_to_mix = (mdi->extra_info.current_sample + mdi->samples_to_mix) - *sample_pos; mdi->extra_info.current_sample = *sample_pos; } else { mdi->extra_info.current_sample += mdi->samples_to_mix; mdi->samples_to_mix = 0; } event++; } mdi->current_event = event; } /* * Clear notes as this is a fast seek so we only care * about new notes. * * NOTE: This function is for performance only. * Might need a WildMidi_SlowSeek if we need better accuracy. */ note_data = mdi->note; if (note_data) { do { note_data->active = 0; if (note_data->replay) { note_data->replay = NULL; } note_data = note_data->next; } while (note_data); } mdi->note = NULL; /* clear the reverb buffers since we not gonna be using them here */ _WM_reset_reverb(mdi->reverb); _WM_Unlock(&mdi->lock); return (0); } WM_SYMBOL int WildMidi_SongSeek (midi * handle, int8_t nextsong) { struct _mdi *mdi; struct _event *event; struct _event *event_new; struct _note *note_data; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } mdi = (struct _mdi *) handle; _WM_Lock(&mdi->lock); if ((!mdi->is_type2) && (nextsong != 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(Illegal use. Only usable with files detected to be type 2 compatible.", 0); _WM_Unlock(&mdi->lock); return (-1); } if ((nextsong > 1) || (nextsong < -1)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(Invalid nextsong setting. -1 is previous song, 0 start of current song, 1 is next song)", 0); _WM_Unlock(&mdi->lock); return (-1); } event = mdi->current_event; if (nextsong == -1) { /* goto start of previous song */ /* * So with this one we have to go back 2 eof's * then forward 1 event to get to the start of * the previous song. * NOTE: We will automatically stop at the start * of the data. */ uint8_t eof_cnt = 1; while (event != mdi->events) { if (event[-1].do_event == _WM_do_meta_endoftrack) { if (eof_cnt == 0) { break; } eof_cnt = 0; } event--; } event_new = event; event = mdi->events; _WM_ResetToStart(handle); } else if (nextsong == 1) { /* goto start of next song */ while (event->do_event != NULL) { if (event->do_event == _WM_do_meta_endoftrack) { event++; if (event->do_event == NULL) { event--; goto START_THIS_SONG; } else { break; } } event++; } event_new = event; event = mdi->current_event; } else { START_THIS_SONG: /* goto start of this song */ /* first find the offset */ while (event != mdi->events) { if (event[-1].do_event == _WM_do_meta_endoftrack) { break; } event--; } event_new = event; event = mdi->events; _WM_ResetToStart(handle); } while (event != event_new) { event->do_event(mdi, &event->event_data); mdi->extra_info.current_sample += event->samples_to_next; event++; } mdi->current_event = event; note_data = mdi->note; if (note_data) { do { note_data->active = 0; if (note_data->replay) { note_data->replay = NULL; } note_data = note_data->next; } while (note_data); } mdi->note = NULL; _WM_Unlock(&mdi->lock); return (0); } WM_SYMBOL int WildMidi_GetOutput(midi * handle, int8_t *buffer, uint32_t size) { if (__builtin_expect((!WM_Initialized), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (__builtin_expect((handle == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (__builtin_expect((buffer == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL buffer pointer)", 0); return (-1); } if (__builtin_expect((size == 0), 0)) { return (0); } if (__builtin_expect((!!(size % 4)), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(size not a multiple of 4)", 0); return (-1); } if (((struct _mdi *) handle)->extra_info.mixer_options & WM_MO_ENHANCED_RESAMPLING) { if (!gauss_table) init_gauss(); return (WM_GetOutput_Gauss(handle, buffer, size)); } return (WM_GetOutput_Linear(handle, buffer, size)); } WM_SYMBOL int WildMidi_GetMidiOutput(midi * handle, int8_t **buffer, uint32_t *size) { if (__builtin_expect((!WM_Initialized), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (__builtin_expect((handle == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (__builtin_expect((buffer == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL buffer pointer)", 0); return (-1); } return _WM_Event2Midi(handle, (uint8_t **)buffer, size); } WM_SYMBOL int WildMidi_SetOption(midi * handle, uint16_t options, uint16_t setting) { struct _mdi *mdi; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } mdi = (struct _mdi *) handle; _WM_Lock(&mdi->lock); if ((!(options & 0x800F)) || (options & 0x7FF0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid option)", 0); _WM_Unlock(&mdi->lock); return (-1); } if (setting & 0x7FF0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid setting)", 0); _WM_Unlock(&mdi->lock); return (-1); } mdi->extra_info.mixer_options = ((mdi->extra_info.mixer_options & (0x80FF ^ options)) | (options & setting)); if (options & WM_MO_LOG_VOLUME) { _WM_AdjustChannelVolumes(mdi, 16); // Settings greater than 15 // adjusts all channels } else if (options & WM_MO_REVERB) { _WM_reset_reverb(mdi->reverb); } _WM_Unlock(&mdi->lock); return (0); } WM_SYMBOL int WildMidi_SetCvtOption(uint16_t tag, uint16_t setting) { _WM_Lock(&WM_ConvertOptions.lock); switch (tag) { case WM_CO_XMI_TYPE: /* validation happens in xmidi.c */ WM_ConvertOptions.xmi_convert_type = setting; break; case WM_CO_FREQUENCY: /* validation happens in format */ WM_ConvertOptions.frequency = setting; break; default: _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid setting)", 0); _WM_Unlock(&WM_ConvertOptions.lock); return (-1); } _WM_Unlock(&WM_ConvertOptions.lock); return (0); } WM_SYMBOL struct _WM_Info * WildMidi_GetInfo(midi * handle) { struct _mdi *mdi = (struct _mdi *) handle; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (NULL); } _WM_Lock(&mdi->lock); if (mdi->tmp_info == NULL) { mdi->tmp_info = malloc(sizeof(struct _WM_Info)); if (mdi->tmp_info == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to set info", 0); _WM_Unlock(&mdi->lock); return (NULL); } mdi->tmp_info->copyright = NULL; } mdi->tmp_info->current_sample = mdi->extra_info.current_sample; mdi->tmp_info->approx_total_samples = mdi->extra_info.approx_total_samples; mdi->tmp_info->mixer_options = mdi->extra_info.mixer_options; mdi->tmp_info->total_midi_time = (mdi->tmp_info->approx_total_samples * 1000) / _WM_SampleRate; if (mdi->extra_info.copyright) { free(mdi->tmp_info->copyright); mdi->tmp_info->copyright = malloc(strlen(mdi->extra_info.copyright) + 1); if (mdi->tmp_info->copyright == NULL) { free(mdi->tmp_info); mdi->tmp_info = NULL; _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to set copyright", 0); _WM_Unlock(&mdi->lock); return (NULL); } else { strcpy(mdi->tmp_info->copyright, mdi->extra_info.copyright); } } else { mdi->tmp_info->copyright = NULL; } _WM_Unlock(&mdi->lock); return ((struct _WM_Info *)mdi->tmp_info); } WM_SYMBOL int WildMidi_Shutdown(void) { if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } while (first_handle) { /* closes open handle and rotates the handles list. */ WildMidi_Close((struct _mdi *) first_handle->handle); } WM_FreePatches(); free_gauss(); /* reset the globals */ _cvt_reset_options (); _WM_MasterVolume = 948; _WM_MixerOptions = 0; _WM_fix_release = 0; _WM_auto_amp = 0; _WM_auto_amp_with_amp = 0; _WM_reverb_room_width = 16.875f; _WM_reverb_room_length = 22.5f; _WM_reverb_listen_posx = 8.4375f; _WM_reverb_listen_posy = 16.875f; WM_Initialized = 0; if (_WM_Global_ErrorS != NULL) free(_WM_Global_ErrorS); return (0); } /* char * WildMidi_GetLyric(midi * handle) Returns points to a \0 terminated string that contains the data contained in the last read lyric or text meta event. Or returns NULL if no lyric is waiting to be read. Force read from text meta event by including WM_MO_TEXTASLYRIC in the options in WildMidi_Init. Programs calling this only need to read the pointer. Cleanup is done by the lib. Once WildMidi_GetLyric is called it will return NULL on subsiquent calls until the next lyric event is processed during a WildMidi_GetOutput call. */ WM_SYMBOL char * WildMidi_GetLyric (midi * handle) { struct _mdi *mdi = (struct _mdi *) handle; char * lyric = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (NULL); } _WM_Lock(&mdi->lock); lyric = mdi->lyric; mdi->lyric = NULL; _WM_Unlock(&mdi->lock); return (lyric); } /* * Return Last Error Message */ WM_SYMBOL char * WildMidi_GetError (void) { return (_WM_Global_ErrorS); } /* * Clear any error message */ WM_SYMBOL void WildMidi_ClearError (void) { _WM_Global_ErrorI = 0; if (_WM_Global_ErrorS != NULL) { free(_WM_Global_ErrorS); _WM_Global_ErrorS = NULL; } return; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2529_1
crossvul-cpp_data_good_4898_0
/* * DBD::mysql - DBI driver for the mysql database * * Copyright (c) 2004-2014 Patrick Galbraith * Copyright (c) 2013-2014 Michiel Beijen * Copyright (c) 2004-2007 Alexey Stroganov * Copyright (c) 2003-2005 Rudolf Lippan * Copyright (c) 1997-2003 Jochen Wiedmann * * You may distribute this under the terms of either the GNU General Public * License or the Artistic License, as specified in the Perl README file. */ #ifdef WIN32 #include "windows.h" #include "winsock.h" #endif #include "dbdimp.h" #include <inttypes.h> /* for PRId32 */ #if defined(WIN32) && defined(WORD) #undef WORD typedef short WORD; #endif #ifdef WIN32 #define MIN min #else #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #endif #if MYSQL_ASYNC # include <poll.h> # define ASYNC_CHECK_RETURN(h, value)\ if(imp_dbh->async_query_in_flight) {\ do_error(h, 2000, "Calling a synchronous function on an asynchronous handle", "HY000");\ return (value);\ } #else # define ASYNC_CHECK_RETURN(h, value) #endif static int parse_number(char *string, STRLEN len, char **end); DBISTATE_DECLARE; typedef struct sql_type_info_s { const char *type_name; int data_type; int column_size; const char *literal_prefix; const char *literal_suffix; const char *create_params; int nullable; int case_sensitive; int searchable; int unsigned_attribute; int fixed_prec_scale; int auto_unique_value; const char *local_type_name; int minimum_scale; int maximum_scale; int num_prec_radix; int sql_datatype; int sql_datetime_sub; int interval_precision; int native_type; int is_num; } sql_type_info_t; /* This function manually counts the number of placeholders in an SQL statement, used for emulated prepare statements < 4.1.3 */ static int count_params(imp_xxh_t *imp_xxh, pTHX_ char *statement, bool bind_comment_placeholders) { bool comment_end= false; char* ptr= statement; int num_params= 0; int comment_length= 0; char c; if (DBIc_DBISTATE(imp_xxh)->debug >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">count_params statement %s\n", statement); while ( (c = *ptr++) ) { switch (c) { /* so, this is a -- comment, so let's burn up characters */ case '-': { if (bind_comment_placeholders) { c = *ptr++; break; } else { comment_length= 1; /* let's see if the next one is a dash */ c = *ptr++; if (c == '-') { /* if two dashes, ignore everything until newline */ while ((c = *ptr)) { if (DBIc_DBISTATE(imp_xxh)->debug >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c\n", c); ptr++; comment_length++; if (c == '\n') { comment_end= true; break; } } /* if not comment_end, the comment never ended and we need to iterate back to the beginning of where we started and let the database handle whatever is in the statement */ if (! comment_end) ptr-= comment_length; } /* otherwise, only one dash/hyphen, backtrack by one */ else ptr--; break; } } /* c-type comments */ case '/': { if (bind_comment_placeholders) { c = *ptr++; break; } else { c = *ptr++; /* let's check if the next one is an asterisk */ if (c == '*') { comment_length= 0; comment_end= false; /* ignore everything until closing comment */ while ((c= *ptr)) { ptr++; comment_length++; if (c == '*') { c = *ptr++; /* alas, end of comment */ if (c == '/') { comment_end= true; break; } /* nope, just an asterisk, not so fast, not end of comment, go back one */ else ptr--; } } /* if the end of the comment was never found, we have to backtrack to wherever we first started skipping over the possible comment. This means we will pass the statement to the database to see its own fate and issue the error */ if (!comment_end) ptr -= comment_length; } else ptr--; break; } } case '`': case '"': case '\'': /* Skip string */ { char end_token = c; while ((c = *ptr) && c != end_token) { if (c == '\\') if (! *(++ptr)) continue; ++ptr; } if (c) ++ptr; break; } case '?': ++num_params; break; default: break; } } return num_params; } /* allocate memory in statement handle per number of placeholders */ static imp_sth_ph_t *alloc_param(int num_params) { imp_sth_ph_t *params; if (num_params) Newz(908, params, (unsigned int) num_params, imp_sth_ph_t); else params= NULL; return params; } #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* allocate memory in MYSQL_BIND bind structure per number of placeholders */ static MYSQL_BIND *alloc_bind(int num_params) { MYSQL_BIND *bind; if (num_params) Newz(908, bind, (unsigned int) num_params, MYSQL_BIND); else bind= NULL; return bind; } /* allocate memory in fbind imp_sth_phb_t structure per number of placeholders */ static imp_sth_phb_t *alloc_fbind(int num_params) { imp_sth_phb_t *fbind; if (num_params) Newz(908, fbind, (unsigned int) num_params, imp_sth_phb_t); else fbind= NULL; return fbind; } /* alloc memory for imp_sth_fbh_t fbuffer per number of fields */ static imp_sth_fbh_t *alloc_fbuffer(int num_fields) { imp_sth_fbh_t *fbh; if (num_fields) Newz(908, fbh, (unsigned int) num_fields, imp_sth_fbh_t); else fbh= NULL; return fbh; } /* free MYSQL_BIND bind struct */ static void free_bind(MYSQL_BIND *bind) { if (bind) Safefree(bind); } /* free imp_sth_phb_t fbind structure */ static void free_fbind(imp_sth_phb_t *fbind) { if (fbind) Safefree(fbind); } /* free imp_sth_fbh_t fbh structure */ static void free_fbuffer(imp_sth_fbh_t *fbh) { if (fbh) Safefree(fbh); } #endif /* free statement param structure per num_params */ static void free_param(pTHX_ imp_sth_ph_t *params, int num_params) { if (params) { int i; for (i= 0; i < num_params; i++) { imp_sth_ph_t *ph= params+i; if (ph->value) { (void) SvREFCNT_dec(ph->value); ph->value= NULL; } } Safefree(params); } } #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Convert a MySQL type to a type that perl can handle NOTE: In the future we may want to return a struct with a lot of information for each type */ static enum enum_field_types mysql_to_perl_type(enum enum_field_types type) { static enum enum_field_types enum_type; switch (type) { case MYSQL_TYPE_DOUBLE: case MYSQL_TYPE_FLOAT: enum_type= MYSQL_TYPE_DOUBLE; break; case MYSQL_TYPE_SHORT: case MYSQL_TYPE_TINY: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_YEAR: #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_BIT: #endif enum_type= MYSQL_TYPE_LONG; break; #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_NEWDECIMAL: #endif case MYSQL_TYPE_DECIMAL: enum_type= MYSQL_TYPE_DECIMAL; break; case MYSQL_TYPE_LONGLONG: /* No longlong in perl */ case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_VAR_STRING: #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_VARCHAR: #endif case MYSQL_TYPE_STRING: enum_type= MYSQL_TYPE_STRING; break; #if MYSQL_VERSION_ID > GEO_DATATYPE_VERSION case MYSQL_TYPE_GEOMETRY: #endif case MYSQL_TYPE_BLOB: case MYSQL_TYPE_TINY_BLOB: enum_type= MYSQL_TYPE_BLOB; break; default: enum_type= MYSQL_TYPE_STRING; /* MySQL can handle all types as strings */ } return(enum_type); } #endif #if defined(DBD_MYSQL_EMBEDDED) /* count embedded options */ int count_embedded_options(char *st) { int rc; char c; char *ptr; ptr= st; rc= 0; if (st) { while ((c= *ptr++)) { if (c == ',') rc++; } rc++; } return rc; } /* Free embedded options */ int free_embedded_options(char ** options_list, int options_count) { int i; for (i= 0; i < options_count; i++) { if (options_list[i]) free(options_list[i]); } free(options_list); return 1; } /* Print out embedded option settings */ int print_embedded_options(char ** options_list, int options_count) { int i; for (i=0; i<options_count; i++) { if (options_list[i]) PerlIO_printf(DBILOGFP, "Embedded server, parameter[%d]=%s\n", i, options_list[i]); } return 1; } /* */ char **fill_out_embedded_options(char *options, int options_type, int slen, int cnt) { int ind, len; char c; char *ptr; char **options_list= NULL; if (!(options_list= (char **) calloc(cnt, sizeof(char *)))) { PerlIO_printf(DBILOGFP, "Initialize embedded server. Out of memory \n"); return NULL; } ptr= options; ind= 0; if (options_type == 0) { /* server_groups list NULL terminated */ options_list[cnt]= (char *) NULL; } if (options_type == 1) { /* first item in server_options list is ignored. fill it with \0 */ if (!(options_list[0]= calloc(1,sizeof(char)))) return NULL; ind++; } while ((c= *ptr++)) { slen--; if (c == ',' || !slen) { len= ptr - options; if (c == ',') len--; if (!(options_list[ind]=calloc(len+1,sizeof(char)))) return NULL; strncpy(options_list[ind], options, len); ind++; options= ptr; } } return options_list; } #endif /* constructs an SQL statement previously prepared with actual values replacing placeholders */ static char *parse_params( imp_xxh_t *imp_xxh, pTHX_ MYSQL *sock, char *statement, STRLEN *slen_ptr, imp_sth_ph_t* params, int num_params, bool bind_type_guessing, bool bind_comment_placeholders) { bool comment_end= false; char *salloc, *statement_ptr; char *statement_ptr_end, *ptr, *valbuf; char *cp, *end; int alen, i; int slen= *slen_ptr; int limit_flag= 0; int comment_length=0; STRLEN vallen; imp_sth_ph_t *ph; if (DBIc_DBISTATE(imp_xxh)->debug >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">parse_params statement %s\n", statement); if (num_params == 0) return NULL; while (isspace(*statement)) { ++statement; --slen; } /* Calculate the number of bytes being allocated for the statement */ alen= slen; for (i= 0, ph= params; i < num_params; i++, ph++) { int defined= 0; if (ph->value) { if (SvMAGICAL(ph->value)) mg_get(ph->value); if (SvOK(ph->value)) defined=1; } if (!defined) alen+= 3; /* Erase '?', insert 'NULL' */ else { valbuf= SvPV(ph->value, vallen); alen+= 2+vallen+1; /* this will most likely not happen since line 214 */ /* of mysql.xs hardcodes all types to SQL_VARCHAR */ if (!ph->type) { if (bind_type_guessing) { valbuf= SvPV(ph->value, vallen); ph->type= SQL_INTEGER; if (parse_number(valbuf, vallen, &end) != 0) { ph->type= SQL_VARCHAR; } } else ph->type= SQL_VARCHAR; } } } /* Allocate memory, why *2, well, because we have ptr and statement_ptr */ New(908, salloc, alen*2, char); ptr= salloc; i= 0; /* Now create the statement string; compare count_params above */ statement_ptr_end= (statement_ptr= statement)+ slen; while (statement_ptr < statement_ptr_end) { /* LIMIT should be the last part of the query, in most cases */ if (! limit_flag) { /* it would be good to be able to handle any number of cases and orders */ if ((*statement_ptr == 'l' || *statement_ptr == 'L') && (!strncmp(statement_ptr+1, "imit ?", 6) || !strncmp(statement_ptr+1, "IMIT ?", 6))) { limit_flag = 1; } } switch (*statement_ptr) { /* comment detection. Anything goes in a comment */ case '-': { if (bind_comment_placeholders) { *ptr++= *statement_ptr++; break; } else { comment_length= 1; comment_end= false; *ptr++ = *statement_ptr++; if (*statement_ptr == '-') { /* ignore everything until newline or end of string */ while (*statement_ptr) { comment_length++; *ptr++ = *statement_ptr++; if (!*statement_ptr || *statement_ptr == '\n') { comment_end= true; break; } } /* if not end of comment, go back to where we started, no end found */ if (! comment_end) { statement_ptr -= comment_length; ptr -= comment_length; } } break; } } /* c-type comments */ case '/': { if (bind_comment_placeholders) { *ptr++= *statement_ptr++; break; } else { comment_length= 1; comment_end= false; *ptr++ = *statement_ptr++; if (*statement_ptr == '*') { /* use up characters everything until newline */ while (*statement_ptr) { *ptr++ = *statement_ptr++; comment_length++; if (!strncmp(statement_ptr, "*/", 2)) { comment_length += 2; comment_end= true; break; } } /* Go back to where started if comment end not found */ if (! comment_end) { statement_ptr -= comment_length; ptr -= comment_length; } } break; } } case '`': case '\'': case '"': /* Skip string */ { char endToken = *statement_ptr++; *ptr++ = endToken; while (statement_ptr != statement_ptr_end && *statement_ptr != endToken) { if (*statement_ptr == '\\') { *ptr++ = *statement_ptr++; if (statement_ptr == statement_ptr_end) break; } *ptr++= *statement_ptr++; } if (statement_ptr != statement_ptr_end) *ptr++= *statement_ptr++; } break; case '?': /* Insert parameter */ statement_ptr++; if (i >= num_params) { break; } ph = params+ (i++); if (!ph->value || !SvOK(ph->value)) { *ptr++ = 'N'; *ptr++ = 'U'; *ptr++ = 'L'; *ptr++ = 'L'; } else { int is_num = FALSE; valbuf= SvPV(ph->value, vallen); if (valbuf) { switch (ph->type) { case SQL_NUMERIC: case SQL_DECIMAL: case SQL_INTEGER: case SQL_SMALLINT: case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE: case SQL_BIGINT: case SQL_TINYINT: is_num = TRUE; break; } /* (note this sets *end, which we use if is_num) */ if ( parse_number(valbuf, vallen, &end) != 0 && is_num) { if (bind_type_guessing) { /* .. not a number, so apparently we guessed wrong */ is_num = 0; ph->type = SQL_VARCHAR; } } /* we're at the end of the query, so any placeholders if */ /* after a LIMIT clause will be numbers and should not be quoted */ if (limit_flag == 1) is_num = TRUE; if (!is_num) { *ptr++ = '\''; ptr += mysql_real_escape_string(sock, ptr, valbuf, vallen); *ptr++ = '\''; } else { for (cp= valbuf; cp < end; cp++) *ptr++= *cp; } } } break; /* in case this is a nested LIMIT */ case ')': limit_flag = 0; *ptr++ = *statement_ptr++; break; default: *ptr++ = *statement_ptr++; break; } } *slen_ptr = ptr - salloc; *ptr++ = '\0'; return(salloc); } int bind_param(imp_sth_ph_t *ph, SV *value, IV sql_type) { dTHX; if (ph->value) { if (SvMAGICAL(ph->value)) mg_get(ph->value); (void) SvREFCNT_dec(ph->value); } ph->value= newSVsv(value); if (sql_type) ph->type = sql_type; return TRUE; } static const sql_type_info_t SQL_GET_TYPE_INFO_values[]= { { "varchar", SQL_VARCHAR, 255, "'", "'", "max length", 1, 0, 3, 0, 0, 0, "variable length string", 0, 0, 0, SQL_VARCHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_VAR_STRING, 0, #else MYSQL_TYPE_STRING, 0, #endif }, { "decimal", SQL_DECIMAL, 15, NULL, NULL, "precision,scale", 1, 0, 3, 0, 0, 0, "double", 0, 6, 2, SQL_DECIMAL, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DECIMAL, 1 #else MYSQL_TYPE_DECIMAL, 1 #endif }, { "tinyint", SQL_TINYINT, 3, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Tiny integer", 0, 0, 10, SQL_TINYINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TINY, 1 #else MYSQL_TYPE_TINY, 1 #endif }, { "smallint", SQL_SMALLINT, 5, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Short integer", 0, 0, 10, SQL_SMALLINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_SHORT, 1 #else MYSQL_TYPE_SHORT, 1 #endif }, { "integer", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "float", SQL_REAL, 7, NULL, NULL, NULL, 1, 0, 0, 0, 0, 0, "float", 0, 2, 10, SQL_FLOAT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_FLOAT, 1 #else MYSQL_TYPE_FLOAT, 1 #endif }, { "double", SQL_FLOAT, 15, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "double", 0, 4, 2, SQL_FLOAT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DOUBLE, 1 #else MYSQL_TYPE_DOUBLE, 1 #endif }, { "double", SQL_DOUBLE, 15, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "double", 0, 4, 10, SQL_DOUBLE, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DOUBLE, 1 #else MYSQL_TYPE_DOUBLE, 1 #endif }, /* FIELD_TYPE_NULL ? */ { "timestamp", SQL_TIMESTAMP, 14, "'", "'", NULL, 0, 0, 3, 0, 0, 0, "timestamp", 0, 0, 0, SQL_TIMESTAMP, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TIMESTAMP, 0 #else MYSQL_TYPE_TIMESTAMP, 0 #endif }, { "bigint", SQL_BIGINT, 19, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Longlong integer", 0, 0, 10, SQL_BIGINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONGLONG, 1 #else MYSQL_TYPE_LONGLONG, 1 #endif }, { "mediumint", SQL_INTEGER, 8, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Medium integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_INT24, 1 #else MYSQL_TYPE_INT24, 1 #endif }, { "date", SQL_DATE, 10, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "date", 0, 0, 0, SQL_DATE, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DATE, 0 #else MYSQL_TYPE_DATE, 0 #endif }, { "time", SQL_TIME, 6, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "time", 0, 0, 0, SQL_TIME, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TIME, 0 #else MYSQL_TYPE_TIME, 0 #endif }, { "datetime", SQL_TIMESTAMP, 21, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "datetime", 0, 0, 0, SQL_TIMESTAMP, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DATETIME, 0 #else MYSQL_TYPE_DATETIME, 0 #endif }, { "year", SQL_SMALLINT, 4, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "year", 0, 0, 10, SQL_SMALLINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_YEAR, 0 #else MYSQL_TYPE_YEAR, 0 #endif }, { "date", SQL_DATE, 10, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "date", 0, 0, 0, SQL_DATE, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_NEWDATE, 0 #else MYSQL_TYPE_NEWDATE, 0 #endif }, { "enum", SQL_VARCHAR, 255, "'", "'", NULL, 1, 0, 1, 0, 0, 0, "enum(value1,value2,value3...)", 0, 0, 0, 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_ENUM, 0 #else MYSQL_TYPE_ENUM, 0 #endif }, { "set", SQL_VARCHAR, 255, "'", "'", NULL, 1, 0, 1, 0, 0, 0, "set(value1,value2,value3...)", 0, 0, 0, 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_SET, 0 #else MYSQL_TYPE_SET, 0 #endif }, { "blob", SQL_LONGVARBINARY, 65535, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object (0-65535)", 0, 0, 0, SQL_LONGVARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_BLOB, 0 #else MYSQL_TYPE_BLOB, 0 #endif }, { "tinyblob", SQL_VARBINARY, 255, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object (0-255) ", 0, 0, 0, SQL_VARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TINY_BLOB, 0 #else FIELD_TYPE_TINY_BLOB, 0 #endif }, { "mediumblob", SQL_LONGVARBINARY, 16777215, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object", 0, 0, 0, SQL_LONGVARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_MEDIUM_BLOB, 0 #else MYSQL_TYPE_MEDIUM_BLOB, 0 #endif }, { "longblob", SQL_LONGVARBINARY, 2147483647, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object, use mediumblob instead", 0, 0, 0, SQL_LONGVARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG_BLOB, 0 #else MYSQL_TYPE_LONG_BLOB, 0 #endif }, { "char", SQL_CHAR, 255, "'", "'", "max length", 1, 0, 3, 0, 0, 0, "string", 0, 0, 0, SQL_CHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_STRING, 0 #else MYSQL_TYPE_STRING, 0 #endif }, { "decimal", SQL_NUMERIC, 15, NULL, NULL, "precision,scale", 1, 0, 3, 0, 0, 0, "double", 0, 6, 2, SQL_NUMERIC, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DECIMAL, 1 #else MYSQL_TYPE_DECIMAL, 1 #endif }, { "tinyint unsigned", SQL_TINYINT, 3, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Tiny integer unsigned", 0, 0, 10, SQL_TINYINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TINY, 1 #else MYSQL_TYPE_TINY, 1 #endif }, { "smallint unsigned", SQL_SMALLINT, 5, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Short integer unsigned", 0, 0, 10, SQL_SMALLINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_SHORT, 1 #else MYSQL_TYPE_SHORT, 1 #endif }, { "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Medium integer unsigned", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_INT24, 1 #else MYSQL_TYPE_INT24, 1 #endif }, { "int unsigned", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "integer unsigned", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "int", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "integer unsigned", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "bigint unsigned", SQL_BIGINT, 20, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Longlong integer unsigned", 0, 0, 10, SQL_BIGINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONGLONG, 1 #else MYSQL_TYPE_LONGLONG, 1 #endif }, { "text", SQL_LONGVARCHAR, 65535, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "large text object (0-65535)", 0, 0, 0, SQL_LONGVARCHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_BLOB, 0 #else MYSQL_TYPE_BLOB, 0 #endif }, { "mediumtext", SQL_LONGVARCHAR, 16777215, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "large text object", 0, 0, 0, SQL_LONGVARCHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_MEDIUM_BLOB, 0 #else MYSQL_TYPE_MEDIUM_BLOB, 0 #endif }, { "mediumint unsigned auto_increment", SQL_INTEGER, 8, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "Medium integer unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1, #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1, #endif }, { "tinyint unsigned auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "tinyint unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1 #else SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1 #endif }, { "smallint auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "smallint auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1 #else SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1 #endif }, { "int unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1 #endif }, { "mediumint", SQL_INTEGER, 7, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Medium integer", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1 #endif }, { "bit", SQL_BIT, 1, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "char(1)", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIT, 0, 0, FIELD_TYPE_TINY, 0 #else SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 0 #endif }, { "numeric", SQL_NUMERIC, 19, NULL, NULL, "precision,scale", 1, 0, 3, 0, 0, 0, "numeric", 0, 19, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_NUMERIC, 0, 0, FIELD_TYPE_DECIMAL, 1, #else SQL_NUMERIC, 0, 0, MYSQL_TYPE_DECIMAL, 1, #endif }, { "integer unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1, #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1, #endif }, { "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Medium integer unsigned", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1 #endif }, { "smallint unsigned auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "smallint unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1 #else SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1 #endif }, { "int auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1 #endif }, { "long varbinary", SQL_LONGVARBINARY, 16777215, "0x", NULL, NULL, 1, 0, 3, 0, 0, 0, "mediumblob", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_LONGVARBINARY, 0, 0, FIELD_TYPE_LONG_BLOB, 0 #else SQL_LONGVARBINARY, 0, 0, MYSQL_TYPE_LONG_BLOB, 0 #endif }, { "double auto_increment", SQL_FLOAT, 15, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 2, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_FLOAT, 0, 0, FIELD_TYPE_DOUBLE, 1 #else SQL_FLOAT, 0, 0, MYSQL_TYPE_DOUBLE, 1 #endif }, { "double auto_increment", SQL_DOUBLE, 15, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_DOUBLE, 0, 0, FIELD_TYPE_DOUBLE, 1 #else SQL_DOUBLE, 0, 0, MYSQL_TYPE_DOUBLE, 1 #endif }, { "integer auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1, #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1, #endif }, { "bigint auto_increment", SQL_BIGINT, 19, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "bigint auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1 #else SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1 #endif }, { "bit auto_increment", SQL_BIT, 1, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "char(1) auto_increment", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIT, 0, 0, FIELD_TYPE_TINY, 1 #else SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 1 #endif }, { "mediumint auto_increment", SQL_INTEGER, 7, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "Medium integer auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1 #endif }, { "float auto_increment", SQL_REAL, 7, NULL, NULL, NULL, 0, 0, 0, 0, 0, 1, "float auto_increment", 0, 2, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_FLOAT, 0, 0, FIELD_TYPE_FLOAT, 1 #else SQL_FLOAT, 0, 0, MYSQL_TYPE_FLOAT, 1 #endif }, { "long varchar", SQL_LONGVARCHAR, 16777215, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "mediumtext", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_LONGVARCHAR, 0, 0, FIELD_TYPE_MEDIUM_BLOB, 1 #else SQL_LONGVARCHAR, 0, 0, MYSQL_TYPE_MEDIUM_BLOB, 1 #endif }, { "tinyint auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "tinyint auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1 #else SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1 #endif }, { "bigint unsigned auto_increment", SQL_BIGINT, 20, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "bigint unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1 #else SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1 #endif }, /* END MORE STUFF */ }; /* static const sql_type_info_t* native2sql (int t) */ static const sql_type_info_t *native2sql(int t) { switch (t) { case FIELD_TYPE_VAR_STRING: return &SQL_GET_TYPE_INFO_values[0]; case FIELD_TYPE_DECIMAL: return &SQL_GET_TYPE_INFO_values[1]; #ifdef FIELD_TYPE_NEWDECIMAL case FIELD_TYPE_NEWDECIMAL: return &SQL_GET_TYPE_INFO_values[1]; #endif case FIELD_TYPE_TINY: return &SQL_GET_TYPE_INFO_values[2]; case FIELD_TYPE_SHORT: return &SQL_GET_TYPE_INFO_values[3]; case FIELD_TYPE_LONG: return &SQL_GET_TYPE_INFO_values[4]; case FIELD_TYPE_FLOAT: return &SQL_GET_TYPE_INFO_values[5]; /* 6 */ case FIELD_TYPE_DOUBLE: return &SQL_GET_TYPE_INFO_values[7]; case FIELD_TYPE_TIMESTAMP: return &SQL_GET_TYPE_INFO_values[8]; case FIELD_TYPE_LONGLONG: return &SQL_GET_TYPE_INFO_values[9]; case FIELD_TYPE_INT24: return &SQL_GET_TYPE_INFO_values[10]; case FIELD_TYPE_DATE: return &SQL_GET_TYPE_INFO_values[11]; case FIELD_TYPE_TIME: return &SQL_GET_TYPE_INFO_values[12]; case FIELD_TYPE_DATETIME: return &SQL_GET_TYPE_INFO_values[13]; case FIELD_TYPE_YEAR: return &SQL_GET_TYPE_INFO_values[14]; case FIELD_TYPE_NEWDATE: return &SQL_GET_TYPE_INFO_values[15]; case FIELD_TYPE_ENUM: return &SQL_GET_TYPE_INFO_values[16]; case FIELD_TYPE_SET: return &SQL_GET_TYPE_INFO_values[17]; case FIELD_TYPE_BLOB: return &SQL_GET_TYPE_INFO_values[18]; case FIELD_TYPE_TINY_BLOB: return &SQL_GET_TYPE_INFO_values[19]; case FIELD_TYPE_MEDIUM_BLOB: return &SQL_GET_TYPE_INFO_values[20]; case FIELD_TYPE_LONG_BLOB: return &SQL_GET_TYPE_INFO_values[21]; case FIELD_TYPE_STRING: return &SQL_GET_TYPE_INFO_values[22]; default: return &SQL_GET_TYPE_INFO_values[0]; } } #define SQL_GET_TYPE_INFO_num \ (sizeof(SQL_GET_TYPE_INFO_values)/sizeof(sql_type_info_t)) /*************************************************************************** * * Name: dbd_init * * Purpose: Called when the driver is installed by DBI * * Input: dbistate - pointer to the DBI state variable, used for some * DBI internal things * * Returns: Nothing * **************************************************************************/ void dbd_init(dbistate_t* dbistate) { dTHX; DBISTATE_INIT; } /************************************************************************** * * Name: do_error, do_warn * * Purpose: Called to associate an error code and an error message * to some handle * * Input: h - the handle in error condition * rc - the error code * what - the error message * * Returns: Nothing * **************************************************************************/ void do_error(SV* h, int rc, const char* what, const char* sqlstate) { dTHX; D_imp_xxh(h); STRLEN lna; SV *errstr; SV *errstate; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t--> do_error\n"); errstr= DBIc_ERRSTR(imp_xxh); sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */ sv_setpv(errstr, what); #if MYSQL_VERSION_ID >= SQL_STATE_VERSION if (sqlstate) { errstate= DBIc_STATE(imp_xxh); sv_setpvn(errstate, sqlstate, 5); } #endif /* NO EFFECT DBIh_EVENT2(h, ERROR_event, DBIc_ERR(imp_xxh), errstr); */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s error %d recorded: %s\n", what, rc, SvPV(errstr,lna)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t<-- do_error\n"); } /* void do_warn(SV* h, int rc, char* what) */ void do_warn(SV* h, int rc, char* what) { dTHX; D_imp_xxh(h); STRLEN lna; SV *errstr = DBIc_ERRSTR(imp_xxh); sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */ sv_setpv(errstr, what); /* NO EFFECT DBIh_EVENT2(h, WARN_event, DBIc_ERR(imp_xxh), errstr);*/ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s warning %d recorded: %s\n", what, rc, SvPV(errstr,lna)); warn("%s", what); } #if defined(DBD_MYSQL_EMBEDDED) #define DBD_MYSQL_NAMESPACE "DBD::mysqlEmb::QUIET"; #else #define DBD_MYSQL_NAMESPACE "DBD::mysql::QUIET"; #endif #define doquietwarn(s) \ { \ SV* sv = perl_get_sv(DBD_MYSQL_NAMESPACE, FALSE); \ if (!sv || !SvTRUE(sv)) { \ warn s; \ } \ } /*************************************************************************** * * Name: mysql_dr_connect * * Purpose: Replacement for mysql_connect * * Input: MYSQL* sock - Pointer to a MYSQL structure being * initialized * char* mysql_socket - Name of a UNIX socket being used * or NULL * char* host - Host name being used or NULL for localhost * char* port - Port number being used or NULL for default * char* user - User name being used or NULL * char* password - Password being used or NULL * char* dbname - Database name being used or NULL * char* imp_dbh - Pointer to internal dbh structure * * Returns: The sock argument for success, NULL otherwise; * you have to call do_error in the latter case. * **************************************************************************/ MYSQL *mysql_dr_connect( SV* dbh, MYSQL* sock, char* mysql_socket, char* host, char* port, char* user, char* password, char* dbname, imp_dbh_t *imp_dbh) { int portNr; unsigned int client_flag; MYSQL* result; dTHX; D_imp_xxh(dbh); /* per Monty, already in client.c in API */ /* but still not exist in libmysqld.c */ #if defined(DBD_MYSQL_EMBEDDED) if (host && !*host) host = NULL; #endif portNr= (port && *port) ? atoi(port) : 0; /* already in client.c in API */ /* if (user && !*user) user = NULL; */ /* if (password && !*password) password = NULL; */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: host = |%s|, port = %d," \ " uid = %s, pwd = %s\n", host ? host : "NULL", portNr, user ? user : "NULL", password ? password : "NULL"); { #if defined(DBD_MYSQL_EMBEDDED) if (imp_dbh) { D_imp_drh_from_dbh; SV* sv = DBIc_IMP_DATA(imp_dbh); if (sv && SvROK(sv)) { SV** svp; STRLEN lna; char * options; int server_args_cnt= 0; int server_groups_cnt= 0; int rc= 0; char ** server_args = NULL; char ** server_groups = NULL; HV* hv = (HV*) SvRV(sv); if (SvTYPE(hv) != SVt_PVHV) return NULL; if (!imp_drh->embedded.state) { /* Init embedded server */ if ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) && *svp && SvTRUE(*svp)) { options = SvPV(*svp, lna); imp_drh->embedded.groups=newSVsv(*svp); if ((server_groups_cnt=count_embedded_options(options))) { /* number of server_groups always server_groups+1 */ server_groups=fill_out_embedded_options(options, 0, (int)lna, ++server_groups_cnt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Groups names passed to embedded server:\n"); print_embedded_options(DBIc_LOGPIO(imp_xxh), server_groups, server_groups_cnt); } } } if ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) && *svp && SvTRUE(*svp)) { options = SvPV(*svp, lna); imp_drh->embedded.args=newSVsv(*svp); if ((server_args_cnt=count_embedded_options(options))) { /* number of server_options always server_options+1 */ server_args=fill_out_embedded_options(options, 1, (int)lna, ++server_args_cnt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Server options passed to embedded server:\n"); print_embedded_options(DBIc_LOGPIO(imp_xxh), server_args, server_args_cnt); } } } if (mysql_server_init(server_args_cnt, server_args, server_groups)) { do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was not started. \ Could not initialize environment."); return NULL; } imp_drh->embedded.state=1; if (server_args_cnt) free_embedded_options(server_args, server_args_cnt); if (server_groups_cnt) free_embedded_options(server_groups, server_groups_cnt); } else { /* * Check if embedded parameters passed to connect() differ from * first ones */ if ( ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) && *svp && SvTRUE(*svp))) rc =+ abs(sv_cmp(*svp, imp_drh->embedded.groups)); if ( ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) && *svp && SvTRUE(*svp)) ) rc =+ abs(sv_cmp(*svp, imp_drh->embedded.args)); if (rc) { do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was already started. You cannot pass init\ parameters to embedded server once"); return NULL; } } } } #endif #ifdef MYSQL_NO_CLIENT_FOUND_ROWS client_flag = 0; #else client_flag = CLIENT_FOUND_ROWS; #endif mysql_init(sock); if (imp_dbh) { SV* sv = DBIc_IMP_DATA(imp_dbh); DBIc_set(imp_dbh, DBIcf_AutoCommit, TRUE); if (sv && SvROK(sv)) { HV* hv = (HV*) SvRV(sv); SV** svp; STRLEN lna; /* thanks to Peter John Edwards for mysql_init_command */ if ((svp = hv_fetch(hv, "mysql_init_command", 18, FALSE)) && *svp && SvTRUE(*svp)) { char* df = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " init command (%s).\n", df); mysql_options(sock, MYSQL_INIT_COMMAND, df); } if ((svp = hv_fetch(hv, "mysql_compression", 17, FALSE)) && *svp && SvTRUE(*svp)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Enabling" \ " compression.\n"); mysql_options(sock, MYSQL_OPT_COMPRESS, NULL); } if ((svp = hv_fetch(hv, "mysql_connect_timeout", 21, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " connect timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_write_timeout", 19, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " write timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_WRITE_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_read_timeout", 18, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " read timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_READ_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_skip_secure_auth", 22, FALSE)) && *svp && SvTRUE(*svp)) { my_bool secauth = 0; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Skipping" \ " secure auth\n"); mysql_options(sock, MYSQL_SECURE_AUTH, &secauth); } if ((svp = hv_fetch(hv, "mysql_read_default_file", 23, FALSE)) && *svp && SvTRUE(*svp)) { char* df = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Reading" \ " default file %s.\n", df); mysql_options(sock, MYSQL_READ_DEFAULT_FILE, df); } if ((svp = hv_fetch(hv, "mysql_read_default_group", 24, FALSE)) && *svp && SvTRUE(*svp)) { char* gr = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Using" \ " default group %s.\n", gr); mysql_options(sock, MYSQL_READ_DEFAULT_GROUP, gr); } #if (MYSQL_VERSION_ID >= 50606) if ((svp = hv_fetch(hv, "mysql_conn_attrs", 16, FALSE)) && *svp) { HV* attrs = (HV*) SvRV(*svp); HE* entry = NULL; I32 num_entries = hv_iterinit(attrs); while (num_entries && (entry = hv_iternext(attrs))) { I32 retlen = 0; char *attr_name = hv_iterkey(entry, &retlen); SV *sv_attr_val = hv_iterval(attrs, entry); char *attr_val = SvPV(sv_attr_val, lna); mysql_options4(sock, MYSQL_OPT_CONNECT_ATTR_ADD, attr_name, attr_val); } } #endif if ((svp = hv_fetch(hv, "mysql_client_found_rows", 23, FALSE)) && *svp) { if (SvTRUE(*svp)) client_flag |= CLIENT_FOUND_ROWS; else client_flag &= ~CLIENT_FOUND_ROWS; } if ((svp = hv_fetch(hv, "mysql_use_result", 16, FALSE)) && *svp) { imp_dbh->use_mysql_use_result = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_mysql_use_result: %d\n", imp_dbh->use_mysql_use_result); } if ((svp = hv_fetch(hv, "mysql_bind_type_guessing", 24, TRUE)) && *svp) { imp_dbh->bind_type_guessing= SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->bind_type_guessing: %d\n", imp_dbh->bind_type_guessing); } if ((svp = hv_fetch(hv, "mysql_bind_comment_placeholders", 31, FALSE)) && *svp) { imp_dbh->bind_comment_placeholders = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->bind_comment_placeholders: %d\n", imp_dbh->bind_comment_placeholders); } if ((svp = hv_fetch(hv, "mysql_no_autocommit_cmd", 23, FALSE)) && *svp) { imp_dbh->no_autocommit_cmd= SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->no_autocommit_cmd: %d\n", imp_dbh->no_autocommit_cmd); } #if FABRIC_SUPPORT if ((svp = hv_fetch(hv, "mysql_use_fabric", 16, FALSE)) && *svp && SvTRUE(*svp)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_fabric: Enabling use of" \ " MySQL Fabric.\n"); mysql_options(sock, MYSQL_OPT_USE_FABRIC, NULL); } #endif #if defined(CLIENT_MULTI_STATEMENTS) if ((svp = hv_fetch(hv, "mysql_multi_statements", 22, FALSE)) && *svp) { if (SvTRUE(*svp)) client_flag |= CLIENT_MULTI_STATEMENTS; else client_flag &= ~CLIENT_MULTI_STATEMENTS; } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* took out client_flag |= CLIENT_PROTOCOL_41; */ /* because libmysql.c already sets this no matter what */ if ((svp = hv_fetch(hv, "mysql_server_prepare", 20, FALSE)) && *svp) { if (SvTRUE(*svp)) { client_flag |= CLIENT_PROTOCOL_41; imp_dbh->use_server_side_prepare = TRUE; } else { client_flag &= ~CLIENT_PROTOCOL_41; imp_dbh->use_server_side_prepare = FALSE; } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_server_side_prepare: %d\n", imp_dbh->use_server_side_prepare); #endif /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if ((svp = hv_fetch(hv, "mysql_enable_utf8mb4", 20, FALSE)) && *svp && SvTRUE(*svp)) { mysql_options(sock, MYSQL_SET_CHARSET_NAME, "utf8mb4"); } else if ((svp = hv_fetch(hv, "mysql_enable_utf8", 17, FALSE)) && *svp) { /* Do not touch imp_dbh->enable_utf8 as we are called earlier * than it is set and mysql_options() must be before: * mysql_real_connect() */ mysql_options(sock, MYSQL_SET_CHARSET_NAME, (SvTRUE(*svp) ? "utf8" : "latin1")); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_options: MYSQL_SET_CHARSET_NAME=%s\n", (SvTRUE(*svp) ? "utf8" : "latin1")); } #endif #if defined(DBD_MYSQL_WITH_SSL) && !defined(DBD_MYSQL_EMBEDDED) && \ (defined(CLIENT_SSL) || (MYSQL_VERSION_ID >= 40000)) if ((svp = hv_fetch(hv, "mysql_ssl", 9, FALSE)) && *svp) { if (SvTRUE(*svp)) { char *client_key = NULL; char *client_cert = NULL; char *ca_file = NULL; char *ca_path = NULL; char *cipher = NULL; STRLEN lna; #if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION /* New code to utilise MySQLs new feature that verifies that the server's hostname that the client connects to matches that of the certificate */ my_bool ssl_verify_true = 0; if ((svp = hv_fetch(hv, "mysql_ssl_verify_server_cert", 28, FALSE)) && *svp) ssl_verify_true = SvTRUE(*svp); #endif if ((svp = hv_fetch(hv, "mysql_ssl_client_key", 20, FALSE)) && *svp) client_key = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_client_cert", 21, FALSE)) && *svp) client_cert = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_ca_file", 17, FALSE)) && *svp) ca_file = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_ca_path", 17, FALSE)) && *svp) ca_path = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_cipher", 16, FALSE)) && *svp) cipher = SvPV(*svp, lna); mysql_ssl_set(sock, client_key, client_cert, ca_file, ca_path, cipher); #if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION mysql_options(sock, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &ssl_verify_true); #endif client_flag |= CLIENT_SSL; } } #endif #if (MYSQL_VERSION_ID >= 32349) /* * MySQL 3.23.49 disables LOAD DATA LOCAL by default. Use * mysql_local_infile=1 in the DSN to enable it. */ if ((svp = hv_fetch( hv, "mysql_local_infile", 18, FALSE)) && *svp) { unsigned int flag = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Using" \ " local infile %u.\n", flag); mysql_options(sock, MYSQL_OPT_LOCAL_INFILE, (const char *) &flag); } #endif } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: client_flags = %d\n", client_flag); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION client_flag|= CLIENT_MULTI_RESULTS; #endif result = mysql_real_connect(sock, host, user, password, dbname, portNr, mysql_socket, client_flag); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: <-"); if (result) { #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* connection succeeded. */ /* imp_dbh == NULL when mysql_dr_connect() is called from mysql.xs functions (_admin_internal(),_ListDBs()). */ if (!(result->client_flag & CLIENT_PROTOCOL_41) && imp_dbh) imp_dbh->use_server_side_prepare = FALSE; #endif #if MYSQL_ASYNC if(imp_dbh) { imp_dbh->async_query_in_flight = NULL; } #endif /* we turn off Mysql's auto reconnect and handle re-connecting ourselves so that we can keep track of when this happens. */ result->reconnect=0; } else { /* sock was allocated with mysql_init() fixes: https://rt.cpan.org/Ticket/Display.html?id=86153 Safefree(sock); rurban: No, we still need this handle later in mysql_dr_error(). RT #97625. It will be freed as imp_dbh->pmysql in dbd_db_destroy(), which is called by the DESTROY handler. */ } return result; } } /* safe_hv_fetch */ static char *safe_hv_fetch(pTHX_ HV *hv, const char *name, int name_length) { SV** svp; STRLEN len; char *res= NULL; if ((svp= hv_fetch(hv, name, name_length, FALSE))) { res= SvPV(*svp, len); if (!len) res= NULL; } return res; } /* Frontend for mysql_dr_connect */ static int my_login(pTHX_ SV* dbh, imp_dbh_t *imp_dbh) { SV* sv; HV* hv; char* dbname; char* host; char* port; char* user; char* password; char* mysql_socket; int result; int fresh = 0; D_imp_xxh(dbh); /* TODO- resolve this so that it is set only if DBI is 1.607 */ #define TAKE_IMP_DATA_VERSION 1 #if TAKE_IMP_DATA_VERSION if (DBIc_has(imp_dbh, DBIcf_IMPSET)) { /* eg from take_imp_data() */ if (DBIc_has(imp_dbh, DBIcf_ACTIVE)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "my_login skip connect\n"); /* tell our parent we've adopted an active child */ ++DBIc_ACTIVE_KIDS(DBIc_PARENT_COM(imp_dbh)); return TRUE; } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "my_login IMPSET but not ACTIVE so connect not skipped\n"); } #endif sv = DBIc_IMP_DATA(imp_dbh); if (!sv || !SvROK(sv)) return FALSE; hv = (HV*) SvRV(sv); if (SvTYPE(hv) != SVt_PVHV) return FALSE; host= safe_hv_fetch(aTHX_ hv, "host", 4); port= safe_hv_fetch(aTHX_ hv, "port", 4); user= safe_hv_fetch(aTHX_ hv, "user", 4); password= safe_hv_fetch(aTHX_ hv, "password", 8); dbname= safe_hv_fetch(aTHX_ hv, "database", 8); mysql_socket= safe_hv_fetch(aTHX_ hv, "mysql_socket", 12); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->my_login : dbname = %s, uid = %s, pwd = %s," \ "host = %s, port = %s\n", dbname ? dbname : "NULL", user ? user : "NULL", password ? password : "NULL", host ? host : "NULL", port ? port : "NULL"); if (!imp_dbh->pmysql) { fresh = 1; Newz(908, imp_dbh->pmysql, 1, MYSQL); } result = mysql_dr_connect(dbh, imp_dbh->pmysql, mysql_socket, host, port, user, password, dbname, imp_dbh) ? TRUE : FALSE; return result; } /************************************************************************** * * Name: dbd_db_login * * Purpose: Called for connecting to a database and logging in. * * Input: dbh - database handle being initialized * imp_dbh - drivers private database handle data * dbname - the database we want to log into; may be like * "dbname:host" or "dbname:host:port" * user - user name to connect as * password - password to connect with * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_db_login(SV* dbh, imp_dbh_t* imp_dbh, char* dbname, char* user, char* password) { #ifdef dTHR dTHR; #endif dTHX; D_imp_xxh(dbh); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->connect: dsn = %s, uid = %s, pwd = %s\n", dbname ? dbname : "NULL", user ? user : "NULL", password ? password : "NULL"); imp_dbh->stats.auto_reconnects_ok= 0; imp_dbh->stats.auto_reconnects_failed= 0; imp_dbh->bind_type_guessing= FALSE; imp_dbh->bind_comment_placeholders= FALSE; imp_dbh->has_transactions= TRUE; /* Safer we flip this to TRUE perl side if we detect a mod_perl env. */ imp_dbh->auto_reconnect = FALSE; /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION imp_dbh->enable_utf8 = FALSE; /* initialize mysql_enable_utf8 */ imp_dbh->enable_utf8mb4 = FALSE; /* initialize mysql_enable_utf8mb4 */ #endif if (!my_login(aTHX_ dbh, imp_dbh)) { if(imp_dbh->pmysql) { do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql)); Safefree(imp_dbh->pmysql); } return FALSE; } /* * Tell DBI, that dbh->disconnect should be called for this handle */ DBIc_ACTIVE_on(imp_dbh); /* Tell DBI, that dbh->destroy should be called for this handle */ DBIc_on(imp_dbh, DBIcf_IMPSET); return TRUE; } /*************************************************************************** * * Name: dbd_db_commit * dbd_db_rollback * * Purpose: You guess what they should do. * * Input: dbh - database handle being committed or rolled back * imp_dbh - drivers private database handle data * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_db_commit(SV* dbh, imp_dbh_t* imp_dbh) { if (DBIc_has(imp_dbh, DBIcf_AutoCommit)) return FALSE; ASYNC_CHECK_RETURN(dbh, FALSE); if (imp_dbh->has_transactions) { #if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION if (mysql_real_query(imp_dbh->pmysql, "COMMIT", 6)) #else if (mysql_commit(imp_dbh->pmysql)) #endif { do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql)); return FALSE; } } else do_warn(dbh, JW_ERR_NOT_IMPLEMENTED, "Commit ineffective because transactions are not available"); return TRUE; } /* dbd_db_rollback */ int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh) { /* croak, if not in AutoCommit mode */ if (DBIc_has(imp_dbh, DBIcf_AutoCommit)) return FALSE; ASYNC_CHECK_RETURN(dbh, FALSE); if (imp_dbh->has_transactions) { #if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION if (mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8)) #else if (mysql_rollback(imp_dbh->pmysql)) #endif { do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql)); return FALSE; } } else do_error(dbh, JW_ERR_NOT_IMPLEMENTED, "Rollback ineffective because transactions are not available" ,NULL); return TRUE; } /* *************************************************************************** * * Name: dbd_db_disconnect * * Purpose: Disconnect a database handle from its database * * Input: dbh - database handle being disconnected * imp_dbh - drivers private database handle data * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh) { #ifdef dTHR dTHR; #endif dTHX; D_imp_xxh(dbh); /* We assume that disconnect will always work */ /* since most errors imply already disconnected. */ DBIc_ACTIVE_off(imp_dbh); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->pmysql: %lx\n", (long) imp_dbh->pmysql); mysql_close(imp_dbh->pmysql ); /* We don't free imp_dbh since a reference still exists */ /* The DESTROY method is the only one to 'free' memory. */ return TRUE; } /*************************************************************************** * * Name: dbd_discon_all * * Purpose: Disconnect all database handles at shutdown time * * Input: dbh - database handle being disconnected * imp_dbh - drivers private database handle data * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_discon_all (SV *drh, imp_drh_t *imp_drh) { #if defined(dTHR) dTHR; #endif dTHX; D_imp_xxh(drh); #if defined(DBD_MYSQL_EMBEDDED) if (imp_drh->embedded.state) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Stop embedded server\n"); mysql_server_end(); if (imp_drh->embedded.groups) { (void) SvREFCNT_dec(imp_drh->embedded.groups); imp_drh->embedded.groups = NULL; } if (imp_drh->embedded.args) { (void) SvREFCNT_dec(imp_drh->embedded.args); imp_drh->embedded.args = NULL; } } #else mysql_server_end(); #endif /* The disconnect_all concept is flawed and needs more work */ if (!PL_dirty && !SvTRUE(perl_get_sv("DBI::PERL_ENDING",0))) { sv_setiv(DBIc_ERR(imp_drh), (IV)1); sv_setpv(DBIc_ERRSTR(imp_drh), (char*)"disconnect_all not implemented"); /* NO EFFECT DBIh_EVENT2(drh, ERROR_event, DBIc_ERR(imp_drh), DBIc_ERRSTR(imp_drh)); */ return FALSE; } PL_perl_destruct_level = 0; return FALSE; } /**************************************************************************** * * Name: dbd_db_destroy * * Purpose: Our part of the dbh destructor * * Input: dbh - database handle being destroyed * imp_dbh - drivers private database handle data * * Returns: Nothing * **************************************************************************/ void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh) { /* * Being on the safe side never hurts ... */ if (DBIc_ACTIVE(imp_dbh)) { if (imp_dbh->has_transactions) { if (!DBIc_has(imp_dbh, DBIcf_AutoCommit)) #if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION if ( mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8)) #else if (mysql_rollback(imp_dbh->pmysql)) #endif do_error(dbh, TX_ERR_ROLLBACK,"ROLLBACK failed" ,NULL); } dbd_db_disconnect(dbh, imp_dbh); } Safefree(imp_dbh->pmysql); /* Tell DBI, that dbh->destroy must no longer be called */ DBIc_off(imp_dbh, DBIcf_IMPSET); } /* *************************************************************************** * * Name: dbd_db_STORE_attrib * * Purpose: Function for storing dbh attributes; we currently support * just nothing. :-) * * Input: dbh - database handle being modified * imp_dbh - drivers private database handle data * keysv - the attribute name * valuesv - the attribute value * * Returns: TRUE for success, FALSE otherwise * **************************************************************************/ int dbd_db_STORE_attrib( SV* dbh, imp_dbh_t* imp_dbh, SV* keysv, SV* valuesv ) { dTHX; STRLEN kl; char *key = SvPV(keysv, kl); SV *cachesv = Nullsv; int cacheit = FALSE; const bool bool_value = SvTRUE(valuesv); if (kl==10 && strEQ(key, "AutoCommit")) { if (imp_dbh->has_transactions) { bool oldval = DBIc_has(imp_dbh,DBIcf_AutoCommit) ? 1 : 0; if (bool_value == oldval) return TRUE; /* if setting AutoCommit on ... */ if (!imp_dbh->no_autocommit_cmd) { if ( #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION mysql_autocommit(imp_dbh->pmysql, bool_value) #else mysql_real_query(imp_dbh->pmysql, bool_value ? "SET AUTOCOMMIT=1" : "SET AUTOCOMMIT=0", 16) #endif ) { do_error(dbh, TX_ERR_AUTOCOMMIT, bool_value ? "Turning on AutoCommit failed" : "Turning off AutoCommit failed" ,NULL); return TRUE; /* TRUE means we handled it - important to avoid spurious errors */ } } DBIc_set(imp_dbh, DBIcf_AutoCommit, bool_value); } else { /* * We do support neither transactions nor "AutoCommit". * But we stub it. :-) */ if (!bool_value) { do_error(dbh, JW_ERR_NOT_IMPLEMENTED, "Transactions not supported by database" ,NULL); croak("Transactions not supported by database"); } } } else if (kl == 16 && strEQ(key,"mysql_use_result")) imp_dbh->use_mysql_use_result = bool_value; else if (kl == 20 && strEQ(key,"mysql_auto_reconnect")) imp_dbh->auto_reconnect = bool_value; else if (kl == 20 && strEQ(key, "mysql_server_prepare")) imp_dbh->use_server_side_prepare = bool_value; else if (kl == 23 && strEQ(key,"mysql_no_autocommit_cmd")) imp_dbh->no_autocommit_cmd = bool_value; else if (kl == 24 && strEQ(key,"mysql_bind_type_guessing")) imp_dbh->bind_type_guessing = bool_value; else if (kl == 31 && strEQ(key,"mysql_bind_comment_placeholders")) imp_dbh->bind_type_guessing = bool_value; #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION else if (kl == 17 && strEQ(key, "mysql_enable_utf8")) imp_dbh->enable_utf8 = bool_value; else if (kl == 20 && strEQ(key, "mysql_enable_utf8mb4")) imp_dbh->enable_utf8mb4 = bool_value; #endif #if FABRIC_SUPPORT else if (kl == 22 && strEQ(key, "mysql_fabric_opt_group")) mysql_options(imp_dbh->pmysql, FABRIC_OPT_GROUP, (void *)SvPVbyte_nolen(valuesv)); else if (kl == 29 && strEQ(key, "mysql_fabric_opt_default_mode")) { if (SvOK(valuesv)) { STRLEN len; const char *str = SvPVbyte(valuesv, len); if ( len == 0 || ( len == 2 && (strnEQ(str, "ro", 3) || strnEQ(str, "rw", 3)) ) ) mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, len == 0 ? NULL : str); else croak("Valid settings for FABRIC_OPT_DEFAULT_MODE are 'ro', 'rw', or undef/empty string"); } else { mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, NULL); } } else if (kl == 21 && strEQ(key, "mysql_fabric_opt_mode")) { STRLEN len; const char *str = SvPVbyte(valuesv, len); if (len != 2 || (strnNE(str, "ro", 3) && strnNE(str, "rw", 3))) croak("Valid settings for FABRIC_OPT_MODE are 'ro' or 'rw'"); mysql_options(imp_dbh->pmysql, FABRIC_OPT_MODE, str); } else if (kl == 34 && strEQ(key, "mysql_fabric_opt_group_credentials")) { croak("'fabric_opt_group_credentials' is not supported"); } #endif else return FALSE; /* Unknown key */ if (cacheit) /* cache value for later DBI 'quick' fetch? */ hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0); return TRUE; } /*************************************************************************** * * Name: dbd_db_FETCH_attrib * * Purpose: Function for fetching dbh attributes * * Input: dbh - database handle being queried * imp_dbh - drivers private database handle data * keysv - the attribute name * * Returns: An SV*, if successful; NULL otherwise * * Notes: Do not forget to call sv_2mortal in the former case! * **************************************************************************/ static SV* my_ulonglong2str(pTHX_ my_ulonglong val) { char buf[64]; char *ptr = buf + sizeof(buf) - 1; if (val == 0) return newSVpv("0", 1); *ptr = '\0'; while (val > 0) { *(--ptr) = ('0' + (val % 10)); val = val / 10; } return newSVpv(ptr, (buf+ sizeof(buf) - 1) - ptr); } SV* dbd_db_FETCH_attrib(SV *dbh, imp_dbh_t *imp_dbh, SV *keysv) { dTHX; STRLEN kl; char *key = SvPV(keysv, kl); char* fine_key = NULL; SV* result = NULL; dbh= dbh; switch (*key) { case 'A': if (strEQ(key, "AutoCommit")) { if (imp_dbh->has_transactions) return sv_2mortal(boolSV(DBIc_has(imp_dbh,DBIcf_AutoCommit))); /* Default */ return &PL_sv_yes; } break; } if (strncmp(key, "mysql_", 6) == 0) { fine_key = key; key = key+6; kl = kl-6; } /* MONTY: Check if kl should not be used or used everywhere */ switch(*key) { case 'a': if (kl == strlen("auto_reconnect") && strEQ(key, "auto_reconnect")) result= sv_2mortal(newSViv(imp_dbh->auto_reconnect)); break; case 'b': if (kl == strlen("bind_type_guessing") && strEQ(key, "bind_type_guessing")) { result = sv_2mortal(newSViv(imp_dbh->bind_type_guessing)); } else if (kl == strlen("bind_comment_placeholders") && strEQ(key, "bind_comment_placeholders")) { result = sv_2mortal(newSViv(imp_dbh->bind_comment_placeholders)); } break; case 'c': if (kl == 10 && strEQ(key, "clientinfo")) { const char* clientinfo = mysql_get_client_info(); result= clientinfo ? sv_2mortal(newSVpv(clientinfo, strlen(clientinfo))) : &PL_sv_undef; } else if (kl == 13 && strEQ(key, "clientversion")) { result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_client_version())); } break; case 'e': if (strEQ(key, "errno")) result= sv_2mortal(newSViv((IV)mysql_errno(imp_dbh->pmysql))); else if ( strEQ(key, "error") || strEQ(key, "errmsg")) { /* Note that errmsg is obsolete, as of 2.09! */ const char* msg = mysql_error(imp_dbh->pmysql); result= sv_2mortal(newSVpv(msg, strlen(msg))); } /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION else if (kl == strlen("enable_utf8mb4") && strEQ(key, "enable_utf8mb4")) result = sv_2mortal(newSViv(imp_dbh->enable_utf8mb4)); else if (kl == strlen("enable_utf8") && strEQ(key, "enable_utf8")) result = sv_2mortal(newSViv(imp_dbh->enable_utf8)); #endif break; case 'd': if (strEQ(key, "dbd_stats")) { HV* hv = newHV(); hv_store( hv, "auto_reconnects_ok", strlen("auto_reconnects_ok"), newSViv(imp_dbh->stats.auto_reconnects_ok), 0 ); hv_store( hv, "auto_reconnects_failed", strlen("auto_reconnects_failed"), newSViv(imp_dbh->stats.auto_reconnects_failed), 0 ); result= sv_2mortal((newRV_noinc((SV*)hv))); } case 'h': if (strEQ(key, "hostinfo")) { const char* hostinfo = mysql_get_host_info(imp_dbh->pmysql); result= hostinfo ? sv_2mortal(newSVpv(hostinfo, strlen(hostinfo))) : &PL_sv_undef; } break; case 'i': if (strEQ(key, "info")) { const char* info = mysql_info(imp_dbh->pmysql); result= info ? sv_2mortal(newSVpv(info, strlen(info))) : &PL_sv_undef; } else if (kl == 8 && strEQ(key, "insertid")) /* We cannot return an IV, because the insertid is a long. */ result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql))); break; case 'n': if (kl == strlen("no_autocommit_cmd") && strEQ(key, "no_autocommit_cmd")) result = sv_2mortal(newSViv(imp_dbh->no_autocommit_cmd)); break; case 'p': if (kl == 9 && strEQ(key, "protoinfo")) result= sv_2mortal(newSViv(mysql_get_proto_info(imp_dbh->pmysql))); break; case 's': if (kl == 10 && strEQ(key, "serverinfo")) { const char* serverinfo = mysql_get_server_info(imp_dbh->pmysql); result= serverinfo ? sv_2mortal(newSVpv(serverinfo, strlen(serverinfo))) : &PL_sv_undef; } else if (kl == 13 && strEQ(key, "serverversion")) result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_server_version(imp_dbh->pmysql))); else if (strEQ(key, "sock")) result= sv_2mortal(newSViv((IV) imp_dbh->pmysql)); else if (strEQ(key, "sockfd")) result= sv_2mortal(newSViv((IV) imp_dbh->pmysql->net.fd)); else if (strEQ(key, "stat")) { const char* stats = mysql_stat(imp_dbh->pmysql); result= stats ? sv_2mortal(newSVpv(stats, strlen(stats))) : &PL_sv_undef; } else if (strEQ(key, "stats")) { /* Obsolete, as of 2.09 */ const char* stats = mysql_stat(imp_dbh->pmysql); result= stats ? sv_2mortal(newSVpv(stats, strlen(stats))) : &PL_sv_undef; } else if (kl == 14 && strEQ(key,"server_prepare")) result= sv_2mortal(newSViv((IV) imp_dbh->use_server_side_prepare)); break; case 't': if (kl == 9 && strEQ(key, "thread_id")) result= sv_2mortal(newSViv(mysql_thread_id(imp_dbh->pmysql))); break; case 'w': if (kl == 13 && strEQ(key, "warning_count")) result= sv_2mortal(newSViv(mysql_warning_count(imp_dbh->pmysql))); break; case 'u': if (strEQ(key, "use_result")) { result= sv_2mortal(newSViv((IV) imp_dbh->use_mysql_use_result)); } break; } if (result== NULL) return Nullsv; return result; } /* ************************************************************************** * * Name: dbd_st_prepare * * Purpose: Called for preparing an SQL statement; our part of the * statement handle constructor * * Input: sth - statement handle being initialized * imp_sth - drivers private statement handle data * statement - pointer to string with SQL statement * attribs - statement attributes, currently not in use * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_prepare( SV *sth, imp_sth_t *imp_sth, char *statement, SV *attribs) { int i; SV **svp; dTHX; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION char *str_ptr, *str_last_ptr; #endif int col_type, prepare_retval, limit_flag=0; MYSQL_BIND *bind, *bind_end; imp_sth_phb_t *fbind; #endif D_imp_xxh(sth); D_imp_dbh_from_sth; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n", MYSQL_VERSION_ID, statement); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Set default value of 'mysql_server_prepare' attribute for sth from dbh */ imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare; if (attribs) { svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_server_prepare", 20); imp_sth->use_server_side_prepare = (svp) ? SvTRUE(*svp) : imp_dbh->use_server_side_prepare; svp = DBD_ATTRIB_GET_SVP(attribs, "async", 5); if(svp && SvTRUE(*svp)) { #if MYSQL_ASYNC imp_sth->is_async = TRUE; imp_sth->use_server_side_prepare = FALSE; #else do_error(sth, 2000, "Async support was not built into this version of DBD::mysql", "HY000"); return 0; #endif } } imp_sth->fetch_done= 0; #endif imp_sth->done_desc= 0; imp_sth->result= NULL; imp_sth->currow= 0; /* Set default value of 'mysql_use_result' attribute for sth from dbh */ svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_use_result", 16); imp_sth->use_mysql_use_result= svp ? SvTRUE(*svp) : imp_dbh->use_mysql_use_result; for (i= 0; i < AV_ATTRIB_LAST; i++) imp_sth->av_attr[i]= Nullav; /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets(sth, imp_sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tuse_server_side_prepare set, check restrictions\n"); /* This code is here because placeholder support is not implemented for statements with :- 1. LIMIT < 5.0.7 2. CALL < 5.5.3 (Added support for out & inout parameters) In these cases we have to disable server side prepared statements NOTE: These checks could cause a false positive on statements which include columns / table names that match "call " or " limit " */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION "\t\tneed to test for LIMIT & CALL\n"); #else "\t\tneed to test for restrictions\n"); #endif str_last_ptr = statement + strlen(statement); for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++) { #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION /* Place holders not supported in LIMIT's */ if (limit_flag) { if (*str_ptr == '?') { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tLIMIT and ? found, set to use_server_side_prepare=0\n"); /* ... then we do not want to try server side prepare (use emulation) */ imp_sth->use_server_side_prepare= 0; break; } } else if (str_ptr < str_last_ptr - 6 && isspace(*(str_ptr + 0)) && tolower(*(str_ptr + 1)) == 'l' && tolower(*(str_ptr + 2)) == 'i' && tolower(*(str_ptr + 3)) == 'm' && tolower(*(str_ptr + 4)) == 'i' && tolower(*(str_ptr + 5)) == 't' && isspace(*(str_ptr + 6))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "LIMIT set limit flag to 1\n"); limit_flag= 1; } #endif /* Place holders not supported in CALL's */ if (str_ptr < str_last_ptr - 4 && tolower(*(str_ptr + 0)) == 'c' && tolower(*(str_ptr + 1)) == 'a' && tolower(*(str_ptr + 2)) == 'l' && tolower(*(str_ptr + 3)) == 'l' && isspace(*(str_ptr + 4))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Disable PS mode for CALL()\n"); imp_sth->use_server_side_prepare= 0; break; } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tuse_server_side_prepare set\n"); /* do we really need this? If we do, we should return, not just continue */ if (imp_sth->stmt) fprintf(stderr, "ERROR: Trying to prepare new stmt while we have \ already not closed one \n"); imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql); if (! imp_sth->stmt) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tERROR: Unable to return MYSQL_STMT structure \ from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n", mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql)); } prepare_retval= mysql_stmt_prepare(imp_sth->stmt, statement, strlen(statement)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_stmt_prepare returned %d\n", prepare_retval); if (prepare_retval) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_stmt_prepare %d %s\n", mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt)); /* For commands that are not supported by server side prepared statement mechanism lets try to pass them through regular API */ if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tSETTING imp_sth->use_server_side_prepare to 0\n"); imp_sth->use_server_side_prepare= 0; } else { do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_sqlstate(imp_dbh->pmysql)); mysql_stmt_close(imp_sth->stmt); imp_sth->stmt= NULL; return FALSE; } } else { DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt); /* mysql_stmt_param_count */ if (DBIc_NUM_PARAMS(imp_sth) > 0) { int has_statement_fields= imp_sth->stmt->fields != 0; /* Allocate memory for bind variables */ imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->has_been_bound= 0; /* Initialize ph variables with NULL values */ for (i= 0, bind= imp_sth->bind, fbind= imp_sth->fbind, bind_end= bind+DBIc_NUM_PARAMS(imp_sth); bind < bind_end ; bind++, fbind++, i++ ) { /* if this statement has a result set, field types will be correctly identified. If there is no result set, such as with an INSERT, fields will not be defined, and all buffer_type will default to MYSQL_TYPE_VAR_STRING */ col_type= (has_statement_fields ? imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING); bind->buffer_type= mysql_to_perl_type(col_type); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n", col_type); bind->buffer= NULL; bind->length= &(fbind->length); bind->is_null= (char*) &(fbind->is_null); fbind->is_null= 1; fbind->length= 0; } } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Count the number of parameters (driver, vs server-side) */ if (imp_sth->use_server_side_prepare == 0) DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #else DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #endif /* Allocate memory for parameters */ imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth)); DBIc_IMPSET_on(imp_sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_prepare\n"); return 1; } /*************************************************************************** * Name: dbd_st_free_result_sets * * Purpose: Clean-up single or multiple result sets (if any) * * Inputs: sth - Statement handle * imp_sth - driver's private statement handle * * Returns: 1 ok * 0 error *************************************************************************/ int mysql_st_free_result_sets (SV * sth, imp_sth_t * imp_sth) { dTHX; D_imp_dbh_from_sth; D_imp_xxh(sth); int next_result_rc= -1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t>- dbd_st_free_result_sets\n"); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION do { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets RC %d\n", next_result_rc); if (next_result_rc == 0) { if (!(imp_sth->result = mysql_use_result(imp_dbh->pmysql))) { /* Check for possible error */ if (mysql_field_count(imp_dbh->pmysql)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets ERROR: %s\n", mysql_error(imp_dbh->pmysql)); do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); return 0; } } } if (imp_sth->result) { mysql_free_result(imp_sth->result); imp_sth->result=NULL; } } while ((next_result_rc=mysql_next_result(imp_dbh->pmysql))==0); if (next_result_rc > 0) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets: Error while processing multi-result set: %s\n", mysql_error(imp_dbh->pmysql)); do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); } #else if (imp_sth->result) { mysql_free_result(imp_sth->result); imp_sth->result=NULL; } #endif if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets\n"); return 1; } #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION /*************************************************************************** * Name: dbd_st_more_results * * Purpose: Move onto the next result set (if any) * * Inputs: sth - Statement handle * imp_sth - driver's private statement handle * * Returns: 1 if there are more results sets * 0 if there are not * -1 for errors. *************************************************************************/ int dbd_st_more_results(SV* sth, imp_sth_t* imp_sth) { dTHX; D_imp_dbh_from_sth; D_imp_xxh(sth); int use_mysql_use_result=imp_sth->use_mysql_use_result; int next_result_return_code, i; MYSQL* svsock= imp_dbh->pmysql; if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV) croak("Expected hash array"); if (!mysql_more_results(svsock)) { /* No more pending result set(s)*/ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n <- dbs_st_more_results no more results\n"); return 0; } if (imp_sth->use_server_side_prepare) { do_warn(sth, JW_ERR_NOT_IMPLEMENTED, "Processing of multiple result set is not possible with server side prepare"); return 0; } /* * Free cached array attributes */ for (i= 0; i < AV_ATTRIB_LAST; i++) { if (imp_sth->av_attr[i]) SvREFCNT_dec(imp_sth->av_attr[i]); imp_sth->av_attr[i]= Nullav; } /* Release previous MySQL result*/ if (imp_sth->result) mysql_free_result(imp_sth->result); if (DBIc_ACTIVE(imp_sth)) DBIc_ACTIVE_off(imp_sth); next_result_return_code= mysql_next_result(svsock); imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql); /* mysql_next_result returns 0 if there are more results -1 if there are no more results >0 if there was an error */ if (next_result_return_code > 0) { do_error(sth, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); return 0; } else if(next_result_return_code == -1) { return 0; } else { /* Store the result from the Query */ imp_sth->result = use_mysql_use_result ? mysql_use_result(svsock) : mysql_store_result(svsock); if (mysql_errno(svsock)) { do_error(sth, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); return 0; } imp_sth->row_num= mysql_affected_rows(imp_dbh->pmysql); if (imp_sth->result == NULL) { /* No "real" rowset*/ DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */ DBIS->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0, sv_2mortal(newSViv(0))); return 1; } else { /* We have a new rowset */ imp_sth->currow=0; /* delete cached handle attributes */ /* XXX should be driven by a list to ease maintenance */ hv_delete((HV*)SvRV(sth), "NAME", 4, G_DISCARD); hv_delete((HV*)SvRV(sth), "NULLABLE", 8, G_DISCARD); hv_delete((HV*)SvRV(sth), "NUM_OF_FIELDS", 13, G_DISCARD); hv_delete((HV*)SvRV(sth), "PRECISION", 9, G_DISCARD); hv_delete((HV*)SvRV(sth), "SCALE", 5, G_DISCARD); hv_delete((HV*)SvRV(sth), "TYPE", 4, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_insertid", 14, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_is_auto_increment", 23, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_is_blob", 13, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_is_key", 12, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_is_num", 12, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_is_pri_key", 16, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_length", 12, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_max_length", 16, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_table", 11, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_type", 10, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_type_name", 15, G_DISCARD); hv_delete((HV*)SvRV(sth), "mysql_warning_count", 20, G_DISCARD); /* Adjust NUM_OF_FIELDS - which also adjusts the row buffer size */ DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */ DBIc_DBISTATE(imp_sth)->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0, sv_2mortal(newSViv(mysql_num_fields(imp_sth->result))) ); DBIc_ACTIVE_on(imp_sth); imp_sth->done_desc = 0; } imp_dbh->pmysql->net.last_errno= 0; return 1; } } #endif /************************************************************************** * * Name: mysql_st_internal_execute * * Purpose: Internal version for executing a statement, called both from * within the "do" and the "execute" method. * * Inputs: h - object handle, for storing error messages * statement - query being executed * attribs - statement attributes, currently ignored * num_params - number of parameters being bound * params - parameter array * result - where to store results, if any * svsock - socket connected to the database * **************************************************************************/ my_ulonglong mysql_st_internal_execute( SV *h, /* could be sth or dbh */ SV *statement, SV *attribs, int num_params, imp_sth_ph_t *params, MYSQL_RES **result, MYSQL *svsock, int use_mysql_use_result ) { dTHX; bool bind_type_guessing= FALSE; bool bind_comment_placeholders= TRUE; STRLEN slen; char *sbuf = SvPV(statement, slen); char *table; char *salloc; int htype; int errno; #if MYSQL_ASYNC bool async = FALSE; #endif my_ulonglong rows= 0; /* thank you DBI.c for this info! */ D_imp_xxh(h); attribs= attribs; htype= DBIc_TYPE(imp_xxh); /* It is important to import imp_dbh properly according to the htype that it is! Also, one might ask why bind_type_guessing is assigned in each block. Well, it's because D_imp_ macros called in these blocks make it so imp_dbh is not "visible" or defined outside of the if/else (when compiled, it fails for imp_dbh not being defined). */ /* h is a dbh */ if (htype == DBIt_DB) { D_imp_dbh(h); /* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */ if (imp_dbh && imp_dbh->bind_type_guessing) { bind_type_guessing= imp_dbh->bind_type_guessing; bind_comment_placeholders= bind_comment_placeholders; } #if MYSQL_ASYNC async = (bool) (imp_dbh->async_query_in_flight != NULL); #endif } /* h is a sth */ else { D_imp_sth(h); D_imp_dbh_from_sth; /* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */ if (imp_dbh) { bind_type_guessing= imp_dbh->bind_type_guessing; bind_comment_placeholders= imp_dbh->bind_comment_placeholders; } #if MYSQL_ASYNC async = imp_sth->is_async; if(async) { imp_dbh->async_query_in_flight = imp_sth; } else { imp_dbh->async_query_in_flight = NULL; } #endif } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_st_internal_execute MYSQL_VERSION_ID %d\n", MYSQL_VERSION_ID ); salloc= parse_params(imp_xxh, aTHX_ svsock, sbuf, &slen, params, num_params, bind_type_guessing, bind_comment_placeholders); if (salloc) { sbuf= salloc; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Binding parameters: %s\n", sbuf); } if (slen >= 11 && (!strncmp(sbuf, "listfields ", 11) || !strncmp(sbuf, "LISTFIELDS ", 11))) { /* remove pre-space */ slen-= 10; sbuf+= 10; while (slen && isspace(*sbuf)) { --slen; ++sbuf; } if (!slen) { do_error(h, JW_ERR_QUERY, "Missing table name" ,NULL); return -2; } if (!(table= malloc(slen+1))) { do_error(h, JW_ERR_MEM, "Out of memory" ,NULL); return -2; } strncpy(table, sbuf, slen); sbuf= table; while (slen && !isspace(*sbuf)) { --slen; ++sbuf; } *sbuf++= '\0'; *result= mysql_list_fields(svsock, table, NULL); free(table); if (!(*result)) { do_error(h, mysql_errno(svsock), mysql_error(svsock) ,mysql_sqlstate(svsock)); return -2; } return 0; } #if MYSQL_ASYNC if(async) { if((mysql_send_query(svsock, sbuf, slen)) && (!mysql_db_reconnect(h) || (mysql_send_query(svsock, sbuf, slen)))) { rows = -2; } else { rows = 0; } } else { #endif if ((mysql_real_query(svsock, sbuf, slen)) && (!mysql_db_reconnect(h) || (mysql_real_query(svsock, sbuf, slen)))) { rows = -2; } else { /** Store the result from the Query */ *result= use_mysql_use_result ? mysql_use_result(svsock) : mysql_store_result(svsock); if (mysql_errno(svsock)) rows = -2; else if (*result) rows = mysql_num_rows(*result); else { rows = mysql_affected_rows(svsock); /* mysql_affected_rows(): -1 indicates that the query returned an error */ if (rows == (my_ulonglong)-1) rows = -2; } } #if MYSQL_ASYNC } #endif if (salloc) Safefree(salloc); if(rows == -2) { do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "IGNORING ERROR errno %d\n", errno); } return(rows); } /************************************************************************** * * Name: mysql_st_internal_execute41 * * Purpose: Internal version for executing a prepared statement, called both * from within the "do" and the "execute" method. * MYSQL 4.1 API * * * Inputs: h - object handle, for storing error messages * statement - query being executed * attribs - statement attributes, currently ignored * num_params - number of parameters being bound * params - parameter array * result - where to store results, if any * svsock - socket connected to the database * **************************************************************************/ #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION my_ulonglong mysql_st_internal_execute41( SV *sth, int num_params, MYSQL_RES **result, MYSQL_STMT *stmt, MYSQL_BIND *bind, int *has_been_bound ) { int i; enum enum_field_types enum_type; dTHX; int execute_retval; my_ulonglong rows=0; D_imp_xxh(sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> mysql_st_internal_execute41\n"); /* free result if exists */ if (*result) { mysql_free_result(*result); *result= 0; } /* If were performed any changes with ph variables we have to rebind them */ if (num_params > 0 && !(*has_been_bound)) { if (mysql_stmt_bind_param(stmt,bind)) goto error; *has_been_bound= 1; } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_st_internal_execute41 calling mysql_execute with %d num_params\n", num_params); execute_retval= mysql_stmt_execute(stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_stmt_execute returned %d\n", execute_retval); if (execute_retval) goto error; /* This statement does not return a result set (INSERT, UPDATE...) */ if (!(*result= mysql_stmt_result_metadata(stmt))) { if (mysql_stmt_errno(stmt)) goto error; rows= mysql_stmt_affected_rows(stmt); /* mysql_stmt_affected_rows(): -1 indicates that the query returned an error */ if (rows == (my_ulonglong)-1) goto error; } /* This statement returns a result set (SELECT...) */ else { for (i = mysql_stmt_field_count(stmt) - 1; i >=0; --i) { enum_type = mysql_to_perl_type(stmt->fields[i].type); if (enum_type != MYSQL_TYPE_DOUBLE && enum_type != MYSQL_TYPE_LONG) { /* mysql_stmt_store_result to update MYSQL_FIELD->max_length */ my_bool on = 1; mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &on); break; } } /* Get the total rows affected and return */ if (mysql_stmt_store_result(stmt)) goto error; else rows= mysql_stmt_num_rows(stmt); } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- mysql_internal_execute_41 returning %d rows\n", (int) rows); return(rows); error: if (*result) { mysql_free_result(*result); *result= 0; } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " errno %d err message %s\n", mysql_stmt_errno(stmt), mysql_stmt_error(stmt)); do_error(sth, mysql_stmt_errno(stmt), mysql_stmt_error(stmt), mysql_stmt_sqlstate(stmt)); mysql_stmt_reset(stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- mysql_st_internal_execute41\n"); return -2; } #endif /*************************************************************************** * * Name: dbd_st_execute * * Purpose: Called for preparing an SQL statement; our part of the * statement handle constructor * * Input: sth - statement handle being initialized * imp_sth - drivers private statement handle data * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_execute(SV* sth, imp_sth_t* imp_sth) { dTHX; char actual_row_num[64]; int i; SV **statement; D_imp_dbh_from_sth; D_imp_xxh(sth); #if defined (dTHR) dTHR; #endif ASYNC_CHECK_RETURN(sth, -2); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " -> dbd_st_execute for %08lx\n", (u_long) sth); if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV) croak("Expected hash array"); /* Free cached array attributes */ for (i= 0; i < AV_ATTRIB_LAST; i++) { if (imp_sth->av_attr[i]) SvREFCNT_dec(imp_sth->av_attr[i]); imp_sth->av_attr[i]= Nullav; } statement= hv_fetch((HV*) SvRV(sth), "Statement", 9, FALSE); /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets (sth, imp_sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare && ! imp_sth->use_mysql_use_result) { imp_sth->row_num= mysql_st_internal_execute41( sth, DBIc_NUM_PARAMS(imp_sth), &imp_sth->result, imp_sth->stmt, imp_sth->bind, &imp_sth->has_been_bound ); } else { #endif imp_sth->row_num= mysql_st_internal_execute( sth, *statement, NULL, DBIc_NUM_PARAMS(imp_sth), imp_sth->params, &imp_sth->result, imp_dbh->pmysql, imp_sth->use_mysql_use_result ); #if MYSQL_ASYNC if(imp_dbh->async_query_in_flight) { DBIc_ACTIVE_on(imp_sth); return 0; } #endif } if (imp_sth->row_num+1 != (my_ulonglong)-1) { if (!imp_sth->result) { imp_sth->insertid= mysql_insert_id(imp_dbh->pmysql); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if (mysql_more_results(imp_dbh->pmysql)) DBIc_ACTIVE_on(imp_sth); #endif } else { /** Store the result in the current statement handle */ DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result); DBIc_ACTIVE_on(imp_sth); if (!imp_sth->use_server_side_prepare) imp_sth->done_desc= 0; imp_sth->fetch_done= 0; } } imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { /* PerlIO_printf doesn't always handle imp_sth->row_num %llu consistently!! */ sprintf(actual_row_num, "%llu", imp_sth->row_num); PerlIO_printf(DBIc_LOGPIO(imp_xxh), " <- dbd_st_execute returning imp_sth->row_num %s\n", actual_row_num); } return (int)imp_sth->row_num; } /************************************************************************** * * Name: dbd_describe * * Purpose: Called from within the fetch method to describe the result * * Input: sth - statement handle being initialized * imp_sth - our part of the statement handle, there's no * need for supplying both; Tim just doesn't remove it * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_describe(SV* sth, imp_sth_t* imp_sth) { dTHX; D_imp_xxh(sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t--> dbd_describe\n"); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { int i; int col_type; int num_fields= DBIc_NUM_FIELDS(imp_sth); imp_sth_fbh_t *fbh; MYSQL_BIND *buffer; MYSQL_FIELD *fields; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_describe() num_fields %d\n", num_fields); if (imp_sth->done_desc) return TRUE; if (!num_fields || !imp_sth->result) { /* no metadata */ do_error(sth, JW_ERR_SEQUENCE, "no metadata information while trying describe result set", NULL); return 0; } /* allocate fields buffers */ if ( !(imp_sth->fbh= alloc_fbuffer(num_fields)) || !(imp_sth->buffer= alloc_bind(num_fields)) ) { /* Out of memory */ do_error(sth, JW_ERR_SEQUENCE, "Out of memory in dbd_sescribe()",NULL); return 0; } fields= mysql_fetch_fields(imp_sth->result); for ( fbh= imp_sth->fbh, buffer= (MYSQL_BIND*)imp_sth->buffer, i= 0; i < num_fields; i++, fbh++, buffer++ ) { /* get the column type */ col_type = fields ? fields[i].type : MYSQL_TYPE_STRING; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\ti %d col_type %d fbh->length %lu\n", i, col_type, fbh->length); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tfields[i].length %lu fields[i].max_length %lu fields[i].type %d fields[i].charsetnr %d\n", (long unsigned int) fields[i].length, (long unsigned int) fields[i].max_length, fields[i].type, fields[i].charsetnr); } fbh->charsetnr = fields[i].charsetnr; #if MYSQL_VERSION_ID < FIELD_CHARSETNR_VERSION fbh->flags = fields[i].flags; #endif buffer->buffer_type= mysql_to_perl_type(col_type); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n", col_type); buffer->length= &(fbh->length); buffer->is_null= (my_bool*) &(fbh->is_null); buffer->error= (my_bool*) &(fbh->error); switch (buffer->buffer_type) { case MYSQL_TYPE_DOUBLE: buffer->buffer_length= sizeof(fbh->ddata); buffer->buffer= (char*) &fbh->ddata; break; case MYSQL_TYPE_LONG: buffer->buffer_length= sizeof(fbh->ldata); buffer->buffer= (char*) &fbh->ldata; buffer->is_unsigned= (fields[i].flags & UNSIGNED_FLAG) ? 1 : 0; break; default: buffer->buffer_length= fields[i].max_length ? fields[i].max_length : 1; Newz(908, fbh->data, buffer->buffer_length, char); buffer->buffer= (char *) fbh->data; } } if (mysql_stmt_bind_result(imp_sth->stmt, imp_sth->buffer)) { do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); return 0; } } #endif imp_sth->done_desc= 1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_describe\n"); return TRUE; } /************************************************************************** * * Name: dbd_st_fetch * * Purpose: Called for fetching a result row * * Input: sth - statement handle being initialized * imp_sth - drivers private statement handle data * * Returns: array of columns; the array is allocated by DBI via * DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth), even the values * of the array are prepared, we just need to modify them * appropriately * **************************************************************************/ AV* dbd_st_fetch(SV *sth, imp_sth_t* imp_sth) { dTHX; int num_fields, ChopBlanks, i, rc; unsigned long *lengths; AV *av; int av_length, av_readonly; MYSQL_ROW cols; D_imp_dbh_from_sth; MYSQL* svsock= imp_dbh->pmysql; imp_sth_fbh_t *fbh; D_imp_xxh(sth); #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION MYSQL_BIND *buffer; #endif MYSQL_FIELD *fields; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> dbd_st_fetch\n"); #if MYSQL_ASYNC if(imp_dbh->async_query_in_flight) { if(mysql_db_async_result(sth, &imp_sth->result) <= 0) { return Nullav; } } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (!DBIc_ACTIVE(imp_sth) ) { do_error(sth, JW_ERR_SEQUENCE, "no statement executing\n",NULL); return Nullav; } if (imp_sth->fetch_done) { do_error(sth, JW_ERR_SEQUENCE, "fetch() but fetch already done",NULL); return Nullav; } if (!imp_sth->done_desc) { if (!dbd_describe(sth, imp_sth)) { do_error(sth, JW_ERR_SEQUENCE, "Error while describe result set.", NULL); return Nullav; } } } #endif ChopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch for %08lx, chopblanks %d\n", (u_long) sth, ChopBlanks); if (!imp_sth->result) { do_error(sth, JW_ERR_SEQUENCE, "fetch() without execute()" ,NULL); return Nullav; } /* fix from 2.9008 */ imp_dbh->pmysql->net.last_errno = 0; #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch calling mysql_fetch\n"); if ((rc= mysql_stmt_fetch(imp_sth->stmt))) { if (rc == 1) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); #if MYSQL_VERSION_ID >= MYSQL_VERSION_5_0 if (rc == MYSQL_DATA_TRUNCATED) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch data truncated\n"); goto process; } #endif if (rc == MYSQL_NO_DATA) { /* Update row_num to affected_rows value */ imp_sth->row_num= mysql_stmt_affected_rows(imp_sth->stmt); imp_sth->fetch_done=1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch no data\n"); } dbd_st_finish(sth, imp_sth); return Nullav; } process: imp_sth->currow++; av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); num_fields=mysql_stmt_field_count(imp_sth->stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch called mysql_fetch, rc %d num_fields %d\n", rc, num_fields); for ( buffer= imp_sth->buffer, fbh= imp_sth->fbh, i= 0; i < num_fields; i++, fbh++, buffer++ ) { SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ STRLEN len; /* This is wrong, null is not being set correctly * This is not the way to determine length (this would break blobs!) */ if (fbh->is_null) (void) SvOK_off(sv); /* Field is NULL, return undef */ else { /* In case of BLOB/TEXT fields we allocate only 8192 bytes in dbd_describe() for data. Here we know real size of field so we should increase buffer size and refetch column value */ if (fbh->length > buffer->buffer_length || fbh->error) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tRefetch BLOB/TEXT column: %d, length: %lu, error: %d\n", i, fbh->length, fbh->error); Renew(fbh->data, fbh->length, char); buffer->buffer_length= fbh->length; buffer->buffer= (char *) fbh->data; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tbefore buffer->buffer: "); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n"); } /*TODO: Use offset instead of 0 to fetch only remain part of data*/ if (mysql_stmt_fetch_column(imp_sth->stmt, buffer , i, 0)) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tafter buffer->buffer: "); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n"); } } /* This does look a lot like Georg's PHP driver doesn't it? --Brian */ /* Credit due to Georg - mysqli_api.c ;) --PMG */ switch (buffer->buffer_type) { case MYSQL_TYPE_DOUBLE: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch double data %f\n", fbh->ddata); sv_setnv(sv, fbh->ddata); break; case MYSQL_TYPE_LONG: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch int data %"PRId32", unsigned? %d\n", fbh->ldata, buffer->is_unsigned); if (buffer->is_unsigned) sv_setuv(sv, fbh->ldata); else sv_setiv(sv, fbh->ldata); break; default: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tERROR IN st_fetch_string"); len= fbh->length; /* ChopBlanks server-side prepared statement */ if (ChopBlanks) { /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if (fbh->charsetnr != 63) while (len && fbh->data[len-1] == ' ') { --len; } } /* END OF ChopBlanks */ sv_setpvn(sv, fbh->data, len); /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID >= FIELD_CHARSETNR_VERSION /* SHOW COLLATION WHERE Id = 63; -- 63 == charset binary, collation binary */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fbh->charsetnr != 63) #else if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && !(fbh->flags & BINARY_FLAG)) #endif sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields); return av; } else { #endif imp_sth->currow++; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch result set details\n"); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\timp_sth->result=%08lx\n",(long unsigned int) imp_sth->result); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_fields=%llu\n", (long long unsigned int) mysql_num_fields(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_rows=%llu\n", mysql_num_rows(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_affected_rows=%llu\n", mysql_affected_rows(imp_dbh->pmysql)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch for %08lx, currow= %d\n", (u_long) sth,imp_sth->currow); } if (!(cols= mysql_fetch_row(imp_sth->result))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch, no more rows to fetch"); } if (mysql_errno(imp_dbh->pmysql)) do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if (!mysql_more_results(svsock)) #endif dbd_st_finish(sth, imp_sth); return Nullav; } num_fields= mysql_num_fields(imp_sth->result); fields= mysql_fetch_fields(imp_sth->result); lengths= mysql_fetch_lengths(imp_sth->result); if ((av= DBIc_FIELDS_AV(imp_sth)) != Nullav) { av_length= av_len(av)+1; if (av_length != num_fields) /* Resize array if necessary */ { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, size of results array(%d) != num_fields(%d)\n", av_length, num_fields); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, result fields(%d)\n", DBIc_NUM_FIELDS(imp_sth)); av_readonly = SvREADONLY(av); if (av_readonly) SvREADONLY_off( av ); /* DBI sets this readonly */ while (av_length < num_fields) { av_store(av, av_length++, newSV(0)); } while (av_length > num_fields) { SvREFCNT_dec(av_pop(av)); av_length--; } if (av_readonly) SvREADONLY_on(av); } } av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); for (i= 0; i < num_fields; ++i) { char *col= cols[i]; SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ if (col) { STRLEN len= lengths[i]; if (ChopBlanks) { while (len && col[len-1] == ' ') { --len; } } sv_setpvn(sv, col, len); /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fields[i].charsetnr != 63) sv_utf8_decode(sv); #endif /* END OF UTF8 */ } else (void) SvOK_off(sv); /* Field is NULL, return undef */ } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields); return av; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION } #endif } #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* We have to fetch all data from stmt There is may be useful for 2 cases: 1. st_finish when we have undef statement 2. call st_execute again when we have some unfetched data in stmt */ int mysql_st_clean_cursor(SV* sth, imp_sth_t* imp_sth) { if (DBIc_ACTIVE(imp_sth) && dbd_describe(sth, imp_sth) && !imp_sth->fetch_done) mysql_stmt_free_result(imp_sth->stmt); return 1; } #endif /*************************************************************************** * * Name: dbd_st_finish * * Purpose: Called for freeing a mysql result * * Input: sth - statement handle being finished * imp_sth - drivers private statement handle data * * Returns: TRUE for success, FALSE otherwise; do_error() will * be called in the latter case * **************************************************************************/ int dbd_st_finish(SV* sth, imp_sth_t* imp_sth) { dTHX; D_imp_xxh(sth); #if defined (dTHR) dTHR; #endif #if MYSQL_ASYNC D_imp_dbh_from_sth; if(imp_dbh->async_query_in_flight) { mysql_db_async_result(sth, &imp_sth->result); } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n--> dbd_st_finish\n"); } if (imp_sth->use_server_side_prepare) { if (imp_sth && imp_sth->stmt) { if (!mysql_st_clean_cursor(sth, imp_sth)) { do_error(sth, JW_ERR_SEQUENCE, "Error happened while tried to clean up stmt",NULL); return 0; } } } #endif /* Cancel further fetches from this cursor. We don't close the cursor till DESTROY. The application may re execute it. */ if (imp_sth && DBIc_ACTIVE(imp_sth)) { /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets(sth, imp_sth); } DBIc_ACTIVE_off(imp_sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n<-- dbd_st_finish\n"); } return 1; } /************************************************************************** * * Name: dbd_st_destroy * * Purpose: Our part of the statement handles destructor * * Input: sth - statement handle being destroyed * imp_sth - drivers private statement handle data * * Returns: Nothing * **************************************************************************/ void dbd_st_destroy(SV *sth, imp_sth_t *imp_sth) { dTHX; D_imp_xxh(sth); #if defined (dTHR) dTHR; #endif int i; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION imp_sth_fbh_t *fbh; int n; n= DBIc_NUM_PARAMS(imp_sth); if (n) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tFreeing %d parameters, bind %p fbind %p\n", n, imp_sth->bind, imp_sth->fbind); free_bind(imp_sth->bind); free_fbind(imp_sth->fbind); } fbh= imp_sth->fbh; if (fbh) { n = DBIc_NUM_FIELDS(imp_sth); i = 0; while (i < n) { if (fbh[i].data) Safefree(fbh[i].data); ++i; } free_fbuffer(fbh); if (imp_sth->buffer) free_bind(imp_sth->buffer); } if (imp_sth->stmt) { if (mysql_stmt_close(imp_sth->stmt)) { do_error(DBIc_PARENT_H(imp_sth), mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); } } #endif /* dbd_st_finish has already been called by .xs code if needed. */ /* Free values allocated by dbd_bind_ph */ if (imp_sth->params) { free_param(aTHX_ imp_sth->params, DBIc_NUM_PARAMS(imp_sth)); imp_sth->params= NULL; } /* Free cached array attributes */ for (i= 0; i < AV_ATTRIB_LAST; i++) { if (imp_sth->av_attr[i]) SvREFCNT_dec(imp_sth->av_attr[i]); imp_sth->av_attr[i]= Nullav; } /* let DBI know we've done it */ DBIc_IMPSET_off(imp_sth); } /* ************************************************************************** * * Name: dbd_st_STORE_attrib * * Purpose: Modifies a statement handles attributes; we currently * support just nothing * * Input: sth - statement handle being destroyed * imp_sth - drivers private statement handle data * keysv - attribute name * valuesv - attribute value * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_STORE_attrib( SV *sth, imp_sth_t *imp_sth, SV *keysv, SV *valuesv ) { dTHX; STRLEN(kl); char *key= SvPV(keysv, kl); int retval= FALSE; D_imp_xxh(sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t-> dbd_st_STORE_attrib for %08lx, key %s\n", (u_long) sth, key); if (strEQ(key, "mysql_use_result")) { imp_sth->use_mysql_use_result= SvTRUE(valuesv); } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t<- dbd_st_STORE_attrib for %08lx, result %d\n", (u_long) sth, retval); return retval; } /* ************************************************************************** * * Name: dbd_st_FETCH_internal * * Purpose: Retrieves a statement handles array attributes; we use * a separate function, because creating the array * attributes shares much code and it aids in supporting * enhanced features like caching. * * Input: sth - statement handle; may even be a database handle, * in which case this will be used for storing error * messages only. This is only valid, if cacheit (the * last argument) is set to TRUE. * what - internal attribute number * res - pointer to a DBMS result * cacheit - TRUE, if results may be cached in the sth. * * Returns: RV pointing to result array in case of success, NULL * otherwise; do_error has already been called in the latter * case. * **************************************************************************/ #ifndef IS_KEY #define IS_KEY(A) (((A) & (PRI_KEY_FLAG | UNIQUE_KEY_FLAG | MULTIPLE_KEY_FLAG)) != 0) #endif #if !defined(IS_AUTO_INCREMENT) && defined(AUTO_INCREMENT_FLAG) #define IS_AUTO_INCREMENT(A) (((A) & AUTO_INCREMENT_FLAG) != 0) #endif SV* dbd_st_FETCH_internal( SV *sth, int what, MYSQL_RES *res, int cacheit ) { dTHX; D_imp_sth(sth); AV *av= Nullav; MYSQL_FIELD *curField; /* Are we asking for a legal value? */ if (what < 0 || what >= AV_ATTRIB_LAST) do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Not implemented", NULL); /* Return cached value, if possible */ else if (cacheit && imp_sth->av_attr[what]) av= imp_sth->av_attr[what]; /* Does this sth really have a result? */ else if (!res) do_error(sth, JW_ERR_NOT_ACTIVE, "statement contains no result" ,NULL); /* Do the real work. */ else { av= newAV(); mysql_field_seek(res, 0); while ((curField= mysql_fetch_field(res))) { SV *sv; switch(what) { case AV_ATTRIB_NAME: sv= newSVpv(curField->name, strlen(curField->name)); break; case AV_ATTRIB_TABLE: sv= newSVpv(curField->table, strlen(curField->table)); break; case AV_ATTRIB_TYPE: sv= newSViv((int) curField->type); break; case AV_ATTRIB_SQL_TYPE: sv= newSViv((int) native2sql(curField->type)->data_type); break; case AV_ATTRIB_IS_PRI_KEY: sv= boolSV(IS_PRI_KEY(curField->flags)); break; case AV_ATTRIB_IS_NOT_NULL: sv= boolSV(IS_NOT_NULL(curField->flags)); break; case AV_ATTRIB_NULLABLE: sv= boolSV(!IS_NOT_NULL(curField->flags)); break; case AV_ATTRIB_LENGTH: sv= newSViv((int) curField->length); break; case AV_ATTRIB_IS_NUM: sv= newSViv((int) native2sql(curField->type)->is_num); break; case AV_ATTRIB_TYPE_NAME: sv= newSVpv((char*) native2sql(curField->type)->type_name, 0); break; case AV_ATTRIB_MAX_LENGTH: sv= newSViv((int) curField->max_length); break; case AV_ATTRIB_IS_AUTO_INCREMENT: #if defined(AUTO_INCREMENT_FLAG) sv= boolSV(IS_AUTO_INCREMENT(curField->flags)); break; #else croak("AUTO_INCREMENT_FLAG is not supported on this machine"); #endif case AV_ATTRIB_IS_KEY: sv= boolSV(IS_KEY(curField->flags)); break; case AV_ATTRIB_IS_BLOB: sv= boolSV(IS_BLOB(curField->flags)); break; case AV_ATTRIB_SCALE: sv= newSViv((int) curField->decimals); break; case AV_ATTRIB_PRECISION: sv= newSViv((int) (curField->length > curField->max_length) ? curField->length : curField->max_length); break; default: sv= &PL_sv_undef; break; } av_push(av, sv); } /* Ensure that this value is kept, decremented in * dbd_st_destroy and dbd_st_execute. */ if (!cacheit) return sv_2mortal(newRV_noinc((SV*)av)); imp_sth->av_attr[what]= av; } if (av == Nullav) return &PL_sv_undef; return sv_2mortal(newRV_inc((SV*)av)); } /* ************************************************************************** * * Name: dbd_st_FETCH_attrib * * Purpose: Retrieves a statement handles attributes * * Input: sth - statement handle being destroyed * imp_sth - drivers private statement handle data * keysv - attribute name * * Returns: NULL for an unknown attribute, "undef" for error, * attribute value otherwise. * **************************************************************************/ #define ST_FETCH_AV(what) \ dbd_st_FETCH_internal(sth, (what), imp_sth->result, TRUE) SV* dbd_st_FETCH_attrib( SV *sth, imp_sth_t *imp_sth, SV *keysv ) { dTHX; STRLEN(kl); char *key= SvPV(keysv, kl); SV *retsv= Nullsv; D_imp_xxh(sth); if (kl < 2) return Nullsv; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " -> dbd_st_FETCH_attrib for %08lx, key %s\n", (u_long) sth, key); switch (*key) { case 'N': if (strEQ(key, "NAME")) retsv= ST_FETCH_AV(AV_ATTRIB_NAME); else if (strEQ(key, "NULLABLE")) retsv= ST_FETCH_AV(AV_ATTRIB_NULLABLE); break; case 'P': if (strEQ(key, "PRECISION")) retsv= ST_FETCH_AV(AV_ATTRIB_PRECISION); if (strEQ(key, "ParamValues")) { HV *pvhv= newHV(); if (DBIc_NUM_PARAMS(imp_sth)) { int n; char key[100]; I32 keylen; for (n= 0; n < DBIc_NUM_PARAMS(imp_sth); n++) { keylen= sprintf(key, "%d", n); hv_store(pvhv, key, keylen, newSVsv(imp_sth->params[n].value), 0); } } retsv= sv_2mortal(newRV_noinc((SV*)pvhv)); } break; case 'S': if (strEQ(key, "SCALE")) retsv= ST_FETCH_AV(AV_ATTRIB_SCALE); break; case 'T': if (strEQ(key, "TYPE")) retsv= ST_FETCH_AV(AV_ATTRIB_SQL_TYPE); break; case 'm': switch (kl) { case 10: if (strEQ(key, "mysql_type")) retsv= ST_FETCH_AV(AV_ATTRIB_TYPE); break; case 11: if (strEQ(key, "mysql_table")) retsv= ST_FETCH_AV(AV_ATTRIB_TABLE); break; case 12: if ( strEQ(key, "mysql_is_key")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_KEY); else if (strEQ(key, "mysql_is_num")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_NUM); else if (strEQ(key, "mysql_length")) retsv= ST_FETCH_AV(AV_ATTRIB_LENGTH); else if (strEQ(key, "mysql_result")) retsv= sv_2mortal(newSViv((IV) imp_sth->result)); break; case 13: if (strEQ(key, "mysql_is_blob")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_BLOB); break; case 14: if (strEQ(key, "mysql_insertid")) { /* We cannot return an IV, because the insertid is a long. */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "INSERT ID %d\n", (int) imp_sth->insertid); return sv_2mortal(my_ulonglong2str(aTHX_ imp_sth->insertid)); } break; case 15: if (strEQ(key, "mysql_type_name")) retsv = ST_FETCH_AV(AV_ATTRIB_TYPE_NAME); break; case 16: if ( strEQ(key, "mysql_is_pri_key")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_PRI_KEY); else if (strEQ(key, "mysql_max_length")) retsv= ST_FETCH_AV(AV_ATTRIB_MAX_LENGTH); else if (strEQ(key, "mysql_use_result")) retsv= boolSV(imp_sth->use_mysql_use_result); break; case 19: if (strEQ(key, "mysql_warning_count")) retsv= sv_2mortal(newSViv((IV) imp_sth->warning_count)); break; case 20: if (strEQ(key, "mysql_server_prepare")) #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION retsv= sv_2mortal(newSViv((IV) imp_sth->use_server_side_prepare)); #else retsv= boolSV(0); #endif break; case 23: if (strEQ(key, "mysql_is_auto_increment")) retsv = ST_FETCH_AV(AV_ATTRIB_IS_AUTO_INCREMENT); break; } break; } return retsv; } /*************************************************************************** * * Name: dbd_st_blob_read * * Purpose: Used for blob reads if the statement handles "LongTruncOk" * attribute (currently not supported by DBD::mysql) * * Input: SV* - statement handle from which a blob will be fetched * imp_sth - drivers private statement handle data * field - field number of the blob (note, that a row may * contain more than one blob) * offset - the offset of the field, where to start reading * len - maximum number of bytes to read * destrv - RV* that tells us where to store * destoffset - destination offset * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_blob_read ( SV *sth, imp_sth_t *imp_sth, int field, long offset, long len, SV *destrv, long destoffset) { /* quell warnings */ sth= sth; imp_sth=imp_sth; field= field; offset= offset; len= len; destrv= destrv; destoffset= destoffset; return FALSE; } /*************************************************************************** * * Name: dbd_bind_ph * * Purpose: Binds a statement value to a parameter * * Input: sth - statement handle * imp_sth - drivers private statement handle data * param - parameter number, counting starts with 1 * value - value being inserted for parameter "param" * sql_type - SQL type of the value * attribs - bind parameter attributes, currently this must be * one of the values SQL_CHAR, ... * inout - TRUE, if parameter is an output variable (currently * this is not supported) * maxlen - ??? * * Returns: TRUE for success, FALSE otherwise * **************************************************************************/ int dbd_bind_ph(SV *sth, imp_sth_t *imp_sth, SV *param, SV *value, IV sql_type, SV *attribs, int is_inout, IV maxlen) { dTHX; int rc; int param_num= SvIV(param); int idx= param_num - 1; char *err_msg; D_imp_xxh(sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION STRLEN slen; char *buffer= NULL; int buffer_is_null= 0; int buffer_length= slen; unsigned int buffer_type= 0; IV tmp; #endif D_imp_dbh_from_sth; ASYNC_CHECK_RETURN(sth, FALSE); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " Called: dbd_bind_ph\n"); attribs= attribs; maxlen= maxlen; if (param_num <= 0 || param_num > DBIc_NUM_PARAMS(imp_sth)) { do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, "Illegal parameter number", NULL); return FALSE; } /* This fixes the bug whereby no warning was issued upon binding a defined non-numeric as numeric */ if (SvOK(value) && (sql_type == SQL_NUMERIC || sql_type == SQL_DECIMAL || sql_type == SQL_INTEGER || sql_type == SQL_SMALLINT || sql_type == SQL_FLOAT || sql_type == SQL_REAL || sql_type == SQL_DOUBLE) ) { if (! looks_like_number(value)) { err_msg = SvPVX(sv_2mortal(newSVpvf( "Binding non-numeric field %d, value %s as a numeric!", param_num, neatsvpv(value,0)))); do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, err_msg, NULL); } } if (is_inout) { do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Output parameters not implemented", NULL); return FALSE; } rc = bind_param(&imp_sth->params[idx], value, sql_type); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { switch(sql_type) { case SQL_NUMERIC: case SQL_INTEGER: case SQL_SMALLINT: case SQL_BIGINT: case SQL_TINYINT: buffer_type= MYSQL_TYPE_LONG; break; case SQL_DOUBLE: case SQL_DECIMAL: case SQL_FLOAT: case SQL_REAL: buffer_type= MYSQL_TYPE_DOUBLE; break; case SQL_CHAR: case SQL_VARCHAR: case SQL_DATE: case SQL_TIME: case SQL_TIMESTAMP: case SQL_LONGVARCHAR: case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: buffer_type= MYSQL_TYPE_BLOB; break; default: buffer_type= MYSQL_TYPE_STRING; } buffer_is_null = !(SvOK(imp_sth->params[idx].value) && imp_sth->params[idx].value); if (! buffer_is_null) { switch(buffer_type) { case MYSQL_TYPE_LONG: /* INT */ if (!SvIOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND AN INT NUMBER\n"); buffer_length = sizeof imp_sth->fbind[idx].numeric_val.lval; tmp = SvIV(imp_sth->params[idx].value); if (tmp > INT32_MAX) croak("Could not bind %ld: Integer too large for MYSQL_TYPE_LONG", tmp); imp_sth->fbind[idx].numeric_val.lval= tmp; buffer=(void*)&(imp_sth->fbind[idx].numeric_val.lval); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type %d ->%"PRId32"<- IS A INT NUMBER\n", (int) sql_type, *(int32_t *)buffer); break; case MYSQL_TYPE_DOUBLE: if (!SvNOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND A FLOAT NUMBER\n"); buffer_length = sizeof imp_sth->fbind[idx].numeric_val.dval; imp_sth->fbind[idx].numeric_val.dval= SvNV(imp_sth->params[idx].value); buffer=(char*)&(imp_sth->fbind[idx].numeric_val.dval); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type %d ->%f<- IS A FLOAT NUMBER\n", (int) sql_type, (double)(*buffer)); break; case MYSQL_TYPE_BLOB: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type BLOB\n"); break; case MYSQL_TYPE_STRING: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type STRING %d, buffertype=%d\n", (int) sql_type, buffer_type); break; default: croak("Bug in DBD::Mysql file dbdimp.c#dbd_bind_ph: do not know how to handle unknown buffer type."); } if (buffer_type == MYSQL_TYPE_STRING || buffer_type == MYSQL_TYPE_BLOB) { buffer= SvPV(imp_sth->params[idx].value, slen); buffer_length= slen; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type %d ->length %d<- IS A STRING or BLOB\n", (int) sql_type, buffer_length); } } else { /*case: buffer_is_null != 0*/ buffer= NULL; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR NULL VALUE: buffer type is: %d\n", buffer_type); } /* Type of column was changed. Force to rebind */ if (imp_sth->bind[idx].buffer_type != buffer_type) { /* Note: this looks like being another bug: * if type of parameter N changes, then a bind is triggered * with an only partially filled bind structure ?? */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " FORCE REBIND: buffer type changed from %d to %d, sql-type=%d\n", (int) imp_sth->bind[idx].buffer_type, buffer_type, (int) sql_type); imp_sth->has_been_bound = 0; } /* prepare has not been called */ if (imp_sth->has_been_bound == 0) { imp_sth->bind[idx].buffer_type= buffer_type; imp_sth->bind[idx].buffer= buffer; imp_sth->bind[idx].buffer_length= buffer_length; } else /* prepare has been called */ { imp_sth->stmt->params[idx].buffer= buffer; imp_sth->stmt->params[idx].buffer_length= buffer_length; } imp_sth->fbind[idx].length= buffer_length; imp_sth->fbind[idx].is_null= buffer_is_null; } #endif return rc; } /*************************************************************************** * * Name: mysql_db_reconnect * * Purpose: If the server has disconnected, try to reconnect. * * Input: h - database or statement handle * * Returns: TRUE for success, FALSE otherwise * **************************************************************************/ int mysql_db_reconnect(SV* h) { dTHX; D_imp_xxh(h); imp_dbh_t* imp_dbh; MYSQL save_socket; if (DBIc_TYPE(imp_xxh) == DBIt_ST) { imp_dbh = (imp_dbh_t*) DBIc_PARENT_COM(imp_xxh); h = DBIc_PARENT_H(imp_xxh); } else imp_dbh= (imp_dbh_t*) imp_xxh; if (mysql_errno(imp_dbh->pmysql) != CR_SERVER_GONE_ERROR) /* Other error */ return FALSE; if (!DBIc_has(imp_dbh, DBIcf_AutoCommit) || !imp_dbh->auto_reconnect) { /* We never reconnect if AutoCommit is turned off. * Otherwise we might get an inconsistent transaction * state. */ return FALSE; } /* my_login will blow away imp_dbh->mysql so we save a copy of * imp_dbh->mysql and put it back where it belongs if the reconnect * fail. Think server is down & reconnect fails but the application eval{}s * the execute, so next time $dbh->quote() gets called, instant SIGSEGV! */ save_socket= *(imp_dbh->pmysql); memcpy (&save_socket, imp_dbh->pmysql,sizeof(save_socket)); memset (imp_dbh->pmysql,0,sizeof(*(imp_dbh->pmysql))); /* we should disconnect the db handle before reconnecting, this will * prevent my_login from thinking it's adopting an active child which * would prevent the handle from actually reconnecting */ if (!dbd_db_disconnect(h, imp_dbh) || !my_login(aTHX_ h, imp_dbh)) { do_error(h, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); memcpy (imp_dbh->pmysql, &save_socket, sizeof(save_socket)); ++imp_dbh->stats.auto_reconnects_failed; return FALSE; } /* * Tell DBI, that dbh->disconnect should be called for this handle */ DBIc_ACTIVE_on(imp_dbh); ++imp_dbh->stats.auto_reconnects_ok; return TRUE; } /************************************************************************** * * Name: dbd_db_type_info_all * * Purpose: Implements $dbh->type_info_all * * Input: dbh - database handle * imp_sth - drivers private database handle data * * Returns: RV to AV of types * **************************************************************************/ #define PV_PUSH(c) \ if (c) { \ sv= newSVpv((char*) (c), 0); \ SvREADONLY_on(sv); \ } else { \ sv= &PL_sv_undef; \ } \ av_push(row, sv); #define IV_PUSH(i) sv= newSViv((i)); SvREADONLY_on(sv); av_push(row, sv); AV *dbd_db_type_info_all(SV *dbh, imp_dbh_t *imp_dbh) { dTHX; AV *av= newAV(); AV *row; HV *hv; SV *sv; int i; const char *cols[] = { "TYPE_NAME", "DATA_TYPE", "COLUMN_SIZE", "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS", "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE", "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_UNIQUE_VALUE", "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE", "NUM_PREC_RADIX", "SQL_DATATYPE", "SQL_DATETIME_SUB", "INTERVAL_PRECISION", "mysql_native_type", "mysql_is_num" }; dbh= dbh; imp_dbh= imp_dbh; hv= newHV(); av_push(av, newRV_noinc((SV*) hv)); for (i= 0; i < (int)(sizeof(cols) / sizeof(const char*)); i++) { if (!hv_store(hv, (char*) cols[i], strlen(cols[i]), newSViv(i), 0)) { SvREFCNT_dec((SV*) av); return Nullav; } } for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++) { const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i]; row= newAV(); av_push(av, newRV_noinc((SV*) row)); PV_PUSH(t->type_name); IV_PUSH(t->data_type); IV_PUSH(t->column_size); PV_PUSH(t->literal_prefix); PV_PUSH(t->literal_suffix); PV_PUSH(t->create_params); IV_PUSH(t->nullable); IV_PUSH(t->case_sensitive); IV_PUSH(t->searchable); IV_PUSH(t->unsigned_attribute); IV_PUSH(t->fixed_prec_scale); IV_PUSH(t->auto_unique_value); PV_PUSH(t->local_type_name); IV_PUSH(t->minimum_scale); IV_PUSH(t->maximum_scale); if (t->num_prec_radix) { IV_PUSH(t->num_prec_radix); } else av_push(row, &PL_sv_undef); IV_PUSH(t->sql_datatype); /* SQL_DATATYPE*/ IV_PUSH(t->sql_datetime_sub); /* SQL_DATETIME_SUB*/ IV_PUSH(t->interval_precision); /* INTERVAL_PERCISION */ IV_PUSH(t->native_type); IV_PUSH(t->is_num); } return av; } /* dbd_db_quote Properly quotes a value */ SV* dbd_db_quote(SV *dbh, SV *str, SV *type) { dTHX; SV *result; if (SvGMAGICAL(str)) mg_get(str); if (!SvOK(str)) result= newSVpv("NULL", 4); else { char *ptr, *sptr; STRLEN len; D_imp_dbh(dbh); if (type && SvMAGICAL(type)) mg_get(type); if (type && SvOK(type)) { int i; int tp= SvIV(type); for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++) { const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i]; if (t->data_type == tp) { if (!t->literal_prefix) return Nullsv; break; } } } ptr= SvPV(str, len); result= newSV(len*2+3); #ifdef SvUTF8 if (SvUTF8(str)) SvUTF8_on(result); #endif sptr= SvPVX(result); *sptr++ = '\''; sptr+= mysql_real_escape_string(imp_dbh->pmysql, sptr, ptr, len); *sptr++= '\''; SvPOK_on(result); SvCUR_set(result, sptr - SvPVX(result)); /* Never hurts NUL terminating a Per string */ *sptr++= '\0'; } return result; } #ifdef DBD_MYSQL_INSERT_ID_IS_GOOD SV *mysql_db_last_insert_id(SV *dbh, imp_dbh_t *imp_dbh, SV *catalog, SV *schema, SV *table, SV *field, SV *attr) { dTHX; /* all these non-op settings are to stifle OS X compile warnings */ imp_dbh= imp_dbh; dbh= dbh; catalog= catalog; schema= schema; table= table; field= field; attr= attr; ASYNC_CHECK_RETURN(dbh, &PL_sv_undef); return sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql))); } #endif #if MYSQL_ASYNC int mysql_db_async_result(SV* h, MYSQL_RES** resp) { dTHX; D_imp_xxh(h); imp_dbh_t* dbh; MYSQL* svsock = NULL; MYSQL_RES* _res; int retval = 0; int htype; if(! resp) { resp = &_res; } htype = DBIc_TYPE(imp_xxh); if(htype == DBIt_DB) { D_imp_dbh(h); dbh = imp_dbh; } else { D_imp_sth(h); D_imp_dbh_from_sth; dbh = imp_dbh; } if(! dbh->async_query_in_flight) { do_error(h, 2000, "Gathering asynchronous results for a synchronous handle", "HY000"); return -1; } if(dbh->async_query_in_flight != imp_xxh) { do_error(h, 2000, "Gathering async_query_in_flight results for the wrong handle", "HY000"); return -1; } dbh->async_query_in_flight = NULL; svsock= dbh->pmysql; retval= mysql_read_query_result(svsock); if(! retval) { *resp= mysql_store_result(svsock); if (mysql_errno(svsock)) do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); if (!*resp) retval= mysql_affected_rows(svsock); else { retval= mysql_num_rows(*resp); if(resp == &_res) { mysql_free_result(*resp); } } if(htype == DBIt_ST) { D_imp_sth(h); D_imp_dbh_from_sth; if(retval+1 != (my_ulonglong)-1) { if(! *resp) { imp_sth->insertid= mysql_insert_id(svsock); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if(! mysql_more_results(svsock)) DBIc_ACTIVE_off(imp_sth); #endif } else { DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result); imp_sth->done_desc= 0; imp_sth->fetch_done= 0; } } imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql); } } else { do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); return -1; } return retval; } int mysql_db_async_ready(SV* h) { dTHX; D_imp_xxh(h); imp_dbh_t* dbh; int htype; htype = DBIc_TYPE(imp_xxh); if(htype == DBIt_DB) { D_imp_dbh(h); dbh = imp_dbh; } else { D_imp_sth(h); D_imp_dbh_from_sth; dbh = imp_dbh; } if(dbh->async_query_in_flight) { if(dbh->async_query_in_flight == imp_xxh) { struct pollfd fds; int retval; fds.fd = dbh->pmysql->net.fd; fds.events = POLLIN; retval = poll(&fds, 1, 0); if(retval < 0) { do_error(h, errno, strerror(errno), "HY000"); } return retval; } else { do_error(h, 2000, "Calling mysql_async_ready on the wrong handle", "HY000"); return -1; } } else { do_error(h, 2000, "Handle is not in asynchronous mode", "HY000"); return -1; } } #endif static int parse_number(char *string, STRLEN len, char **end) { int seen_neg; int seen_dec; int seen_e; int seen_plus; int seen_digit; char *cp; seen_neg= seen_dec= seen_e= seen_plus= seen_digit= 0; if (len <= 0) { len= strlen(string); } cp= string; /* Skip leading whitespace */ while (*cp && isspace(*cp)) cp++; for ( ; *cp; cp++) { if ('-' == *cp) { if (seen_neg >= 2) { /* third '-'. number can contains two '-'. because -1e-10 is valid number */ break; } seen_neg += 1; } else if ('.' == *cp) { if (seen_dec) { /* second '.' */ break; } seen_dec= 1; } else if ('e' == *cp) { if (seen_e) { /* second 'e' */ break; } seen_e= 1; } else if ('+' == *cp) { if (seen_plus) { /* second '+' */ break; } seen_plus= 1; } else if (!isdigit(*cp)) { /* Not sure why this was changed */ /* seen_digit= 1; */ break; } } *end= cp; /* length 0 -> not a number */ /* Need to revisit this */ /*if (len == 0 || cp - string < (int) len || seen_digit == 0) {*/ if (len == 0 || cp - string < (int) len) { return -1; } return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4898_0
crossvul-cpp_data_good_3407_1
/* ext2.c - Second Extended filesystem */ /* * GRUB -- GRand Unified Bootloader * Copyright (C) 2003,2004,2005,2007,2008,2009 Free Software Foundation, Inc. * * GRUB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GRUB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GRUB. If not, see <http://www.gnu.org/licenses/>. */ /* Magic value used to identify an ext2 filesystem. */ #define EXT2_MAGIC 0xEF53 /* Amount of indirect blocks in an inode. */ #define INDIRECT_BLOCKS 12 /* Maximum length of a pathname. */ #define EXT2_PATH_MAX 4096 /* Maximum nesting of symlinks, used to prevent a loop. */ #define EXT2_MAX_SYMLINKCNT 8 /* The good old revision and the default inode size. */ #define EXT2_GOOD_OLD_REVISION 0 #define EXT2_GOOD_OLD_INODE_SIZE 128 /* Filetype used in directory entry. */ #define FILETYPE_UNKNOWN 0 #define FILETYPE_REG 1 #define FILETYPE_DIRECTORY 2 #define FILETYPE_SYMLINK 7 /* Filetype information as used in inodes. */ #define FILETYPE_INO_MASK 0170000 #define FILETYPE_INO_REG 0100000 #define FILETYPE_INO_DIRECTORY 0040000 #define FILETYPE_INO_SYMLINK 0120000 #include <stdlib.h> #include <grub/err.h> #include <grub/file.h> #include <grub/mm.h> #include <grub/misc.h> #include <grub/disk.h> #include <grub/dl.h> #include <grub/types.h> #include <grub/fshelp.h> /* Log2 size of ext2 block in 512 blocks. */ #define LOG2_EXT2_BLOCK_SIZE(data) \ (grub_le_to_cpu32 (data->sblock.log2_block_size) + 1) /* Log2 size of ext2 block in bytes. */ #define LOG2_BLOCK_SIZE(data) \ (grub_le_to_cpu32 (data->sblock.log2_block_size) + 10) /* The size of an ext2 block in bytes. */ #define EXT2_BLOCK_SIZE(data) (1 << LOG2_BLOCK_SIZE (data)) /* The revision level. */ #define EXT2_REVISION(data) grub_le_to_cpu32 (data->sblock.revision_level) /* The inode size. */ #define EXT2_INODE_SIZE(data) \ (EXT2_REVISION (data) == EXT2_GOOD_OLD_REVISION \ ? EXT2_GOOD_OLD_INODE_SIZE \ : grub_le_to_cpu16 (data->sblock.inode_size)) /* Superblock filesystem feature flags (RW compatible) * A filesystem with any of these enabled can be read and written by a driver * that does not understand them without causing metadata/data corruption. */ #define EXT2_FEATURE_COMPAT_DIR_PREALLOC 0x0001 #define EXT2_FEATURE_COMPAT_IMAGIC_INODES 0x0002 #define EXT3_FEATURE_COMPAT_HAS_JOURNAL 0x0004 #define EXT2_FEATURE_COMPAT_EXT_ATTR 0x0008 #define EXT2_FEATURE_COMPAT_RESIZE_INODE 0x0010 #define EXT2_FEATURE_COMPAT_DIR_INDEX 0x0020 /* Superblock filesystem feature flags (RO compatible) * A filesystem with any of these enabled can be safely read by a driver that * does not understand them, but should not be written to, usually because * additional metadata is required. */ #define EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001 #define EXT2_FEATURE_RO_COMPAT_LARGE_FILE 0x0002 #define EXT2_FEATURE_RO_COMPAT_BTREE_DIR 0x0004 #define EXT4_FEATURE_RO_COMPAT_GDT_CSUM 0x0010 #define EXT4_FEATURE_RO_COMPAT_DIR_NLINK 0x0020 #define EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE 0x0040 /* Superblock filesystem feature flags (back-incompatible) * A filesystem with any of these enabled should not be attempted to be read * by a driver that does not understand them, since they usually indicate * metadata format changes that might confuse the reader. */ #define EXT2_FEATURE_INCOMPAT_COMPRESSION 0x0001 #define EXT2_FEATURE_INCOMPAT_FILETYPE 0x0002 #define EXT3_FEATURE_INCOMPAT_RECOVER 0x0004 /* Needs recovery */ #define EXT3_FEATURE_INCOMPAT_JOURNAL_DEV 0x0008 /* Volume is journal device */ #define EXT2_FEATURE_INCOMPAT_META_BG 0x0010 #define EXT4_FEATURE_INCOMPAT_EXTENTS 0x0040 /* Extents used */ #define EXT4_FEATURE_INCOMPAT_64BIT 0x0080 #define EXT4_FEATURE_INCOMPAT_FLEX_BG 0x0200 /* The set of back-incompatible features this driver DOES support. Add (OR) * flags here as the related features are implemented into the driver. */ #define EXT2_DRIVER_SUPPORTED_INCOMPAT ( EXT2_FEATURE_INCOMPAT_FILETYPE \ | EXT4_FEATURE_INCOMPAT_EXTENTS \ | EXT4_FEATURE_INCOMPAT_FLEX_BG ) /* List of rationales for the ignored "incompatible" features: * needs_recovery: Not really back-incompatible - was added as such to forbid * ext2 drivers from mounting an ext3 volume with a dirty * journal because they will ignore the journal, but the next * ext3 driver to mount the volume will find the journal and * replay it, potentially corrupting the metadata written by * the ext2 drivers. Safe to ignore for this RO driver. */ #define EXT2_DRIVER_IGNORED_INCOMPAT ( EXT3_FEATURE_INCOMPAT_RECOVER ) #define EXT3_JOURNAL_MAGIC_NUMBER 0xc03b3998U #define EXT3_JOURNAL_DESCRIPTOR_BLOCK 1 #define EXT3_JOURNAL_COMMIT_BLOCK 2 #define EXT3_JOURNAL_SUPERBLOCK_V1 3 #define EXT3_JOURNAL_SUPERBLOCK_V2 4 #define EXT3_JOURNAL_REVOKE_BLOCK 5 #define EXT3_JOURNAL_FLAG_ESCAPE 1 #define EXT3_JOURNAL_FLAG_SAME_UUID 2 #define EXT3_JOURNAL_FLAG_DELETED 4 #define EXT3_JOURNAL_FLAG_LAST_TAG 8 #define EXT4_EXTENTS_FLAG 0x80000 /* The ext2 superblock. */ struct grub_ext2_sblock { grub_uint32_t total_inodes; grub_uint32_t total_blocks; grub_uint32_t reserved_blocks; grub_uint32_t free_blocks; grub_uint32_t free_inodes; grub_uint32_t first_data_block; grub_uint32_t log2_block_size; grub_uint32_t log2_fragment_size; grub_uint32_t blocks_per_group; grub_uint32_t fragments_per_group; grub_uint32_t inodes_per_group; grub_uint32_t mtime; grub_uint32_t utime; grub_uint16_t mnt_count; grub_uint16_t max_mnt_count; grub_uint16_t magic; grub_uint16_t fs_state; grub_uint16_t error_handling; grub_uint16_t minor_revision_level; grub_uint32_t lastcheck; grub_uint32_t checkinterval; grub_uint32_t creator_os; grub_uint32_t revision_level; grub_uint16_t uid_reserved; grub_uint16_t gid_reserved; grub_uint32_t first_inode; grub_uint16_t inode_size; grub_uint16_t block_group_number; grub_uint32_t feature_compatibility; grub_uint32_t feature_incompat; grub_uint32_t feature_ro_compat; grub_uint16_t uuid[8]; char volume_name[16]; char last_mounted_on[64]; grub_uint32_t compression_info; grub_uint8_t prealloc_blocks; grub_uint8_t prealloc_dir_blocks; grub_uint16_t reserved_gdt_blocks; grub_uint8_t journal_uuid[16]; grub_uint32_t journal_inum; grub_uint32_t journal_dev; grub_uint32_t last_orphan; grub_uint32_t hash_seed[4]; grub_uint8_t def_hash_version; grub_uint8_t jnl_backup_type; grub_uint16_t reserved_word_pad; grub_uint32_t default_mount_opts; grub_uint32_t first_meta_bg; grub_uint32_t mkfs_time; grub_uint32_t jnl_blocks[17]; }; /* The ext2 blockgroup. */ struct grub_ext2_block_group { grub_uint32_t block_id; grub_uint32_t inode_id; grub_uint32_t inode_table_id; grub_uint16_t free_blocks; grub_uint16_t free_inodes; grub_uint16_t used_dirs; grub_uint16_t pad; grub_uint32_t reserved[3]; }; /* The ext2 inode. */ struct grub_ext2_inode { grub_uint16_t mode; grub_uint16_t uid; grub_uint32_t size; grub_uint32_t atime; grub_uint32_t ctime; grub_uint32_t mtime; grub_uint32_t dtime; grub_uint16_t gid; grub_uint16_t nlinks; grub_uint32_t blockcnt; /* Blocks of 512 bytes!! */ grub_uint32_t flags; grub_uint32_t osd1; union { struct datablocks { grub_uint32_t dir_blocks[INDIRECT_BLOCKS]; grub_uint32_t indir_block; grub_uint32_t double_indir_block; grub_uint32_t triple_indir_block; } blocks; char symlink[60]; }; grub_uint32_t version; grub_uint32_t acl; grub_uint32_t dir_acl; grub_uint32_t fragment_addr; grub_uint32_t osd2[3]; }; /* The header of an ext2 directory entry. */ struct ext2_dirent { grub_uint32_t inode; grub_uint16_t direntlen; grub_uint8_t namelen; grub_uint8_t filetype; }; struct grub_ext3_journal_header { grub_uint32_t magic; grub_uint32_t block_type; grub_uint32_t sequence; }; struct grub_ext3_journal_revoke_header { struct grub_ext3_journal_header header; grub_uint32_t count; grub_uint32_t data[0]; }; struct grub_ext3_journal_block_tag { grub_uint32_t block; grub_uint32_t flags; }; struct grub_ext3_journal_sblock { struct grub_ext3_journal_header header; grub_uint32_t block_size; grub_uint32_t maxlen; grub_uint32_t first; grub_uint32_t sequence; grub_uint32_t start; }; #define EXT4_EXT_MAGIC 0xf30a struct grub_ext4_extent_header { grub_uint16_t magic; grub_uint16_t entries; grub_uint16_t max; grub_uint16_t depth; grub_uint32_t generation; }; struct grub_ext4_extent { grub_uint32_t block; grub_uint16_t len; grub_uint16_t start_hi; grub_uint32_t start; }; struct grub_ext4_extent_idx { grub_uint32_t block; grub_uint32_t leaf; grub_uint16_t leaf_hi; grub_uint16_t unused; }; struct grub_fshelp_node { struct grub_ext2_data *data; struct grub_ext2_inode inode; int ino; int inode_read; }; /* Information about a "mounted" ext2 filesystem. */ struct grub_ext2_data { struct grub_ext2_sblock sblock; grub_disk_t disk; struct grub_ext2_inode *inode; struct grub_fshelp_node diropen; }; static grub_dl_t my_mod; /* Read into BLKGRP the blockgroup descriptor of blockgroup GROUP of the mounted filesystem DATA. */ inline static grub_err_t grub_ext2_blockgroup (struct grub_ext2_data *data, int group, struct grub_ext2_block_group *blkgrp) { return grub_disk_read (data->disk, ((grub_le_to_cpu32 (data->sblock.first_data_block) + 1) << LOG2_EXT2_BLOCK_SIZE (data)), group * sizeof (struct grub_ext2_block_group), sizeof (struct grub_ext2_block_group), blkgrp); } static struct grub_ext4_extent_header * grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) { return 0; } ext_block = (struct grub_ext4_extent_header *) buf; } } static grub_disk_addr_t grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) { struct grub_ext2_data *data = node->data; struct grub_ext2_inode *inode = &node->inode; int blknr = -1; unsigned int blksz = EXT2_BLOCK_SIZE (data); int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) { char * buf = grub_malloc (EXT2_BLOCK_SIZE (data)); if (!buf) { return -1; } struct grub_ext4_extent_header *leaf; struct grub_ext4_extent *ext; int i; leaf = grub_ext4_find_leaf (data, buf, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, fileblock); if (! leaf) { grub_error (GRUB_ERR_BAD_FS, "invalid extent"); free (buf); return -1; } ext = (struct grub_ext4_extent *) (leaf + 1); for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) { if (fileblock < grub_le_to_cpu32 (ext[i].block)) break; } if (--i >= 0) { fileblock -= grub_le_to_cpu32 (ext[i].block); if (fileblock >= grub_le_to_cpu16 (ext[i].len)) { free (buf); return 0; } else { grub_disk_addr_t start; start = grub_le_to_cpu16 (ext[i].start_hi); start = (start << 32) + grub_le_to_cpu32 (ext[i].start); free (buf); return fileblock + start; } } else { grub_error (GRUB_ERR_BAD_FS, "something wrong with extent"); free (buf); return -1; } free (buf); } /* Direct blocks. */ if (fileblock < INDIRECT_BLOCKS) { blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); /* Indirect. */ } else if (fileblock < INDIRECT_BLOCKS + blksz / 4) { grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) { return grub_errno; } if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.indir_block)) << log2_blksz, 0, blksz, indir)) { return grub_errno; } blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); grub_free (indir); } /* Double indirect. */ else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ * (grub_disk_addr_t)(blksz / 4 + 1)) { unsigned int perblock = blksz / 4; unsigned int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4); grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) { return grub_errno; } if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.double_indir_block)) << log2_blksz, 0, blksz, indir)) { return grub_errno; } if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (indir[rblock / perblock])) << log2_blksz, 0, blksz, indir)) { return grub_errno; } blknr = grub_le_to_cpu32 (indir[rblock % perblock]); grub_free (indir); } /* triple indirect. */ else { grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "ext2fs doesn't support triple indirect blocks"); } return blknr; } /* Read LEN bytes from the file described by DATA starting with byte POS. Return the amount of read bytes in READ. */ static grub_ssize_t grub_ext2_read_file (grub_fshelp_node_t node, void (*read_hook) (grub_disk_addr_t sector, unsigned offset, unsigned length, void *closure), void *closure, int flags, int pos, grub_size_t len, char *buf) { return grub_fshelp_read_file (node->data->disk, node, read_hook, closure, flags, pos, len, buf, grub_ext2_read_block, node->inode.size, LOG2_EXT2_BLOCK_SIZE (node->data)); } /* Read the inode INO for the file described by DATA into INODE. */ static grub_err_t grub_ext2_read_inode (struct grub_ext2_data *data, int ino, struct grub_ext2_inode *inode) { struct grub_ext2_block_group blkgrp; struct grub_ext2_sblock *sblock = &data->sblock; int inodes_per_block; unsigned int blkno; unsigned int blkoff; /* It is easier to calculate if the first inode is 0. */ ino--; int div = grub_le_to_cpu32 (sblock->inodes_per_group); if (div < 1) { return grub_errno = GRUB_ERR_BAD_FS; } grub_ext2_blockgroup (data, ino / div, &blkgrp); if (grub_errno) return grub_errno; int inode_size = EXT2_INODE_SIZE (data); if (inode_size < 1) { return grub_errno = GRUB_ERR_BAD_FS; } inodes_per_block = EXT2_BLOCK_SIZE (data) / inode_size; if (inodes_per_block < 1) { return grub_errno = GRUB_ERR_BAD_FS; } blkno = (ino % grub_le_to_cpu32 (sblock->inodes_per_group)) / inodes_per_block; blkoff = (ino % grub_le_to_cpu32 (sblock->inodes_per_group)) % inodes_per_block; /* Read the inode. */ if (grub_disk_read (data->disk, ((grub_le_to_cpu32 (blkgrp.inode_table_id) + blkno) << LOG2_EXT2_BLOCK_SIZE (data)), EXT2_INODE_SIZE (data) * blkoff, sizeof (struct grub_ext2_inode), inode)) return grub_errno; return 0; } static struct grub_ext2_data * grub_ext2_mount (grub_disk_t disk) { struct grub_ext2_data *data; data = grub_malloc (sizeof (struct grub_ext2_data)); if (!data) return 0; /* Read the superblock. */ grub_disk_read (disk, 1 * 2, 0, sizeof (struct grub_ext2_sblock), &data->sblock); if (grub_errno) goto fail; /* Make sure this is an ext2 filesystem. */ if (grub_le_to_cpu16 (data->sblock.magic) != EXT2_MAGIC) { grub_error (GRUB_ERR_BAD_FS, "not an ext2 filesystem"); goto fail; } /* Check the FS doesn't have feature bits enabled that we don't support. */ if (grub_le_to_cpu32 (data->sblock.feature_incompat) & ~(EXT2_DRIVER_SUPPORTED_INCOMPAT | EXT2_DRIVER_IGNORED_INCOMPAT)) { grub_error (GRUB_ERR_BAD_FS, "filesystem has unsupported incompatible features"); goto fail; } data->disk = disk; data->diropen.data = data; data->diropen.ino = 2; data->diropen.inode_read = 1; data->inode = &data->diropen.inode; grub_ext2_read_inode (data, 2, data->inode); if (grub_errno) goto fail; return data; fail: if (grub_errno == GRUB_ERR_OUT_OF_RANGE) grub_error (GRUB_ERR_BAD_FS, "not an ext2 filesystem"); grub_free (data); return 0; } static char * grub_ext2_read_symlink (grub_fshelp_node_t node) { char *symlink; struct grub_fshelp_node *diro = node; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } symlink = grub_malloc (grub_le_to_cpu32 (diro->inode.size) + 1); if (! symlink) return 0; /* If the filesize of the symlink is bigger than 60 the symlink is stored in a separate block, otherwise it is stored in the inode. */ if (grub_le_to_cpu32 (diro->inode.size) <= 60) grub_strncpy (symlink, diro->inode.symlink, grub_le_to_cpu32 (diro->inode.size)); else { grub_ext2_read_file (diro, 0, 0, 0, 0, grub_le_to_cpu32 (diro->inode.size), symlink); if (grub_errno) { grub_free (symlink); return 0; } } symlink[grub_le_to_cpu32 (diro->inode.size)] = '\0'; return symlink; } static int grub_ext2_iterate_dir (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure) { unsigned int fpos = 0; struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } /* Search the file. */ if (hook) while (fpos < grub_le_to_cpu32 (diro->inode.size)) { struct ext2_dirent dirent; grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent), (char *) &dirent); if (grub_errno) return 0; if (dirent.direntlen == 0) return 0; if (dirent.namelen != 0) { char * filename = grub_malloc (dirent.namelen + 1); struct grub_fshelp_node *fdiro; enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN; if (!filename) { break; } grub_ext2_read_file (diro, 0, 0, 0, fpos + sizeof (struct ext2_dirent), dirent.namelen, filename); if (grub_errno) { grub_free (filename); return 0; } fdiro = grub_malloc (sizeof (struct grub_fshelp_node)); if (! fdiro) { grub_free (filename); return 0; } fdiro->data = diro->data; fdiro->ino = grub_le_to_cpu32 (dirent.inode); filename[dirent.namelen] = '\0'; if (dirent.filetype != FILETYPE_UNKNOWN) { fdiro->inode_read = 0; if (dirent.filetype == FILETYPE_DIRECTORY) type = GRUB_FSHELP_DIR; else if (dirent.filetype == FILETYPE_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if (dirent.filetype == FILETYPE_REG) type = GRUB_FSHELP_REG; } else { /* The filetype can not be read from the dirent, read the inode to get more information. */ grub_ext2_read_inode (diro->data, grub_le_to_cpu32 (dirent.inode), &fdiro->inode); if (grub_errno) { grub_free (filename); grub_free (fdiro); return 0; } fdiro->inode_read = 1; if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY) type = GRUB_FSHELP_DIR; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_REG) type = GRUB_FSHELP_REG; } if (hook (filename, type, fdiro, closure)) { grub_free (filename); return 1; } grub_free (filename); } fpos += grub_le_to_cpu16 (dirent.direntlen); } return 0; } /* Open a file named NAME and initialize FILE. */ static grub_err_t grub_ext2_open (struct grub_file *file, const char *name) { struct grub_ext2_data *data; struct grub_fshelp_node *fdiro = 0; grub_dl_ref (my_mod); data = grub_ext2_mount (file->device->disk); if (! data) goto fail; grub_fshelp_find_file (name, &data->diropen, &fdiro, grub_ext2_iterate_dir, 0, grub_ext2_read_symlink, GRUB_FSHELP_REG); if (grub_errno) goto fail; if (! fdiro->inode_read) { grub_ext2_read_inode (data, fdiro->ino, &fdiro->inode); if (grub_errno) goto fail; } grub_memcpy (data->inode, &fdiro->inode, sizeof (struct grub_ext2_inode)); grub_free (fdiro); file->size = grub_le_to_cpu32 (data->inode->size); file->data = data; file->offset = 0; return 0; fail: if (fdiro != &data->diropen) grub_free (fdiro); grub_free (data); grub_dl_unref (my_mod); return grub_errno; } static grub_err_t grub_ext2_close (grub_file_t file) { grub_free (file->data); grub_dl_unref (my_mod); return GRUB_ERR_NONE; } /* Read LEN bytes data from FILE into BUF. */ static grub_ssize_t grub_ext2_read (grub_file_t file, char *buf, grub_size_t len) { struct grub_ext2_data *data = (struct grub_ext2_data *) file->data; return grub_ext2_read_file (&data->diropen, file->read_hook, file->closure, file->flags, file->offset, len, buf); } struct grub_ext2_dir_closure { int (*hook) (const char *filename, const struct grub_dirhook_info *info, void *closure); void *closure; struct grub_ext2_data *data; }; static int iterate (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure) { struct grub_ext2_dir_closure *c = closure; struct grub_dirhook_info info; grub_memset (&info, 0, sizeof (info)); if (! node->inode_read) { grub_ext2_read_inode (c->data, node->ino, &node->inode); if (!grub_errno) node->inode_read = 1; grub_errno = GRUB_ERR_NONE; } if (node->inode_read) { info.mtimeset = 1; info.mtime = grub_le_to_cpu32 (node->inode.mtime); } info.dir = ((filetype & GRUB_FSHELP_TYPE_MASK) == GRUB_FSHELP_DIR); grub_free (node); return (c->hook != NULL)? c->hook (filename, &info, c->closure): 0; } static grub_err_t grub_ext2_dir (grub_device_t device, const char *path, int (*hook) (const char *filename, const struct grub_dirhook_info *info, void *closure), void *closure) { struct grub_ext2_data *data = 0; struct grub_fshelp_node *fdiro = 0; struct grub_ext2_dir_closure c; grub_dl_ref (my_mod); data = grub_ext2_mount (device->disk); if (! data) goto fail; grub_fshelp_find_file (path, &data->diropen, &fdiro, grub_ext2_iterate_dir, 0, grub_ext2_read_symlink, GRUB_FSHELP_DIR); if (grub_errno) goto fail; c.hook = hook; c.closure = closure; c.data = data; grub_ext2_iterate_dir (fdiro, iterate, &c); fail: if (fdiro != &data->diropen) grub_free (fdiro); grub_free (data); grub_dl_unref (my_mod); return grub_errno; } static grub_err_t grub_ext2_label (grub_device_t device, char **label) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (data) *label = grub_strndup (data->sblock.volume_name, 14); else *label = NULL; grub_dl_unref (my_mod); grub_free (data); return grub_errno; } static grub_err_t grub_ext2_uuid (grub_device_t device, char **uuid) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (data) { *uuid = grub_xasprintf ("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", grub_be_to_cpu16 (data->sblock.uuid[0]), grub_be_to_cpu16 (data->sblock.uuid[1]), grub_be_to_cpu16 (data->sblock.uuid[2]), grub_be_to_cpu16 (data->sblock.uuid[3]), grub_be_to_cpu16 (data->sblock.uuid[4]), grub_be_to_cpu16 (data->sblock.uuid[5]), grub_be_to_cpu16 (data->sblock.uuid[6]), grub_be_to_cpu16 (data->sblock.uuid[7])); } else *uuid = NULL; grub_dl_unref (my_mod); grub_free (data); return grub_errno; } /* Get mtime. */ static grub_err_t grub_ext2_mtime (grub_device_t device, grub_int32_t *tm) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (!data) *tm = 0; else *tm = grub_le_to_cpu32 (data->sblock.utime); grub_dl_unref (my_mod); grub_free (data); return grub_errno; } struct grub_fs grub_ext2_fs = { .name = "ext2", .dir = grub_ext2_dir, .open = grub_ext2_open, .read = grub_ext2_read, .close = grub_ext2_close, .label = grub_ext2_label, .uuid = grub_ext2_uuid, .mtime = grub_ext2_mtime, #ifdef GRUB_UTIL .reserved_first_sector = 1, #endif .next = 0 };
./CrossVul/dataset_final_sorted/CWE-119/c/good_3407_1
crossvul-cpp_data_bad_2637_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriatally. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; register ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1 << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); (void) InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ClutImage) #endif proceed=SetImageProgress(image,ClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; register ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; GetNextToken(p,&p,MagickPathExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ColorDecisionListImageChannel) #endif proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, red; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastImage) #endif proceed=SetImageProgress(image,ContrastImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by 'stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % 'enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black)); white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else if (black[i] != white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (black[j] == white[j]) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastStretchImage) #endif proceed=SetImageProgress(image,ContrastStretchImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const 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); enhance_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; if (GetPixelWriteMask(image,p) == 0) { SetPixelBackgoundColor(enhance_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); continue; } GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); SetPixelViaPixelInfo(image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EnhanceImage) #endif proceed=SetImageProgress(image,EnhanceImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaCorrectImageTag "GammaCorrect/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) ResetMagickMemory(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,1.0/gamma))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ #if !defined(MAGICKCORE_HDRI_SUPPORT) if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; #else if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].red,1.0/gamma); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].green,1.0/gamma); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].blue,1.0/gamma); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=QuantumRange*gamma_pow(QuantumScale* image->colormap[i].alpha,1.0/gamma); #endif } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; #if !defined(MAGICKCORE_HDRI_SUPPORT) q[j]=gamma_map[ScaleQuantumToMap(q[j])]; #else q[j]=QuantumRange*gamma_pow(QuantumScale*q[j],1.0/gamma); #endif } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GammaImage) #endif proceed=SetImageProgress(image,GammaCorrectImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GrayscaleImage) #endif proceed=SetImageProgress(image,GrayscaleImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=point.x+level*floor(point.y)+cube_size*floor(point.z); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); pixel1=zero; (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); pixel2=zero; (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); pixel3=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel3); offset+=cube_size; (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); (void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel4); pixel=zero; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, point.z,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_HaldClutImage) #endif proceed=SetImageProgress(image,HaldClutImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; if (fabs(white_point-black_point) < MagickEpsilon) return(pixel); scale=1.0/(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), 1.0/gamma); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_LevelImage) #endif proceed=SetImageProgress(image,LevelImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImage() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used to de-contrast a greyscale image to the exact levels % specified. Or by using specific levels for each channel of an image you % can convert a gray-scale image to any linear color gradient, according to % those levels. % % The format of the LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_LevelizeImage) #endif proceed=SetImageProgress(image,LevelizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() maps the given color to "black" and "white" values, % linearly spreading out the colors, and level values on a channel by channel % bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) == MagickFalse) || (IsGrayColorspace(white_color->colorspace) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) ResetMagickMemory(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,double *red, double *green,double *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=fmod((percent_hue-100.0),200.0)/200.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; register ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ModulateImage) #endif proceed=SetImageProgress(image,ModulateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if( grayscale != MagickFalse ) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if ((GetPixelWriteMask(image,q) == 0) || IsPixelGray(image,q) != MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_NegateImage) #endif proceed=SetImageProgress(image,NegateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_NegateImage) #endif proceed=SetImageProgress(image,NegateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { register ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SigmoidalContrastImage) #endif proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2637_0
crossvul-cpp_data_good_4787_19
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF IIIII TTTTT SSSSS % % F I T SS % % FFF I T SSS % % F I T SS % % F IIIII T SSSSS % % % % % % Read/Write Flexible Image Transport System Images. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" /* Forward declarations. */ #define FITSBlocksize 2880UL /* Forward declarations. */ static MagickBooleanType WriteFITSImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s F I T S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsFITS() returns MagickTrue if the image format type, identified by the % magick string, is FITS. % % The format of the IsFITS method is: % % MagickBooleanType IsFITS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsFITS(const unsigned char *magick,const size_t length) { if (length < 6) return(MagickFalse); if (LocaleNCompare((const char *) magick,"IT0",3) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"SIMPLE",6) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d F I T S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadFITSImage() reads a FITS image file and returns it. It allocates the % memory necessary for the new Image structure and returns a pointer to the % new image. % % The format of the ReadFITSImage method is: % % Image *ReadFITSImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline double GetFITSPixel(Image *image,int bits_per_pixel) { switch (image->depth >> 3) { case 1: return((double) ReadBlobByte(image)); case 2: return((double) ((short) ReadBlobShort(image))); case 4: { if (bits_per_pixel > 0) return((double) ((int) ReadBlobLong(image))); return((double) ReadBlobFloat(image)); } case 8: { if (bits_per_pixel > 0) return((double) ((MagickOffsetType) ReadBlobLongLong(image))); } default: break; } return(ReadBlobDouble(image)); } static MagickOffsetType GetFITSPixelExtrema(Image *image, const int bits_per_pixel,double *minima,double *maxima) { double pixel; MagickOffsetType offset; MagickSizeType number_pixels; register MagickOffsetType i; offset=TellBlob(image); if (offset == -1) return(-1); number_pixels=(MagickSizeType) image->columns*image->rows; *minima=GetFITSPixel(image,bits_per_pixel); *maxima=(*minima); for (i=1; i < (MagickOffsetType) number_pixels; i++) { pixel=GetFITSPixel(image,bits_per_pixel); if (pixel < *minima) *minima=pixel; if (pixel > *maxima) *maxima=pixel; } return(SeekBlob(image,offset,SEEK_SET)); } static inline double GetFITSPixelRange(const size_t depth) { return((double) ((MagickOffsetType) GetQuantumRange(depth))); } static void SetFITSUnsignedPixels(const size_t length, const size_t bits_per_pixel,const EndianType endian,unsigned char *pixels) { register ssize_t i; if (endian != MSBEndian) pixels+=(bits_per_pixel >> 3)-1; for (i=0; i < (ssize_t) length; i++) { *pixels^=0x80; pixels+=bits_per_pixel >> 3; } } static Image *ReadFITSImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct _FITSInfo { MagickBooleanType extend, simple; int bits_per_pixel, columns, rows, number_axes, number_planes; double min_data, max_data, zero, scale; EndianType endian; } FITSInfo; char *comment, keyword[9], property[MaxTextExtent], value[73]; double pixel, scale; FITSInfo fits_info; Image *image; int c; MagickBooleanType status; MagickSizeType number_pixels; register ssize_t i, x; register PixelPacket *q; ssize_t count, scene, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image header. */ (void) ResetMagickMemory(&fits_info,0,sizeof(fits_info)); fits_info.extend=MagickFalse; fits_info.simple=MagickFalse; fits_info.bits_per_pixel=8; fits_info.columns=1; fits_info.rows=1; fits_info.rows=1; fits_info.number_planes=1; fits_info.min_data=0.0; fits_info.max_data=0.0; fits_info.zero=0.0; fits_info.scale=1.0; fits_info.endian=MSBEndian; /* Decode image header. */ for (comment=(char *) NULL; EOFBlob(image) == MagickFalse; ) { for ( ; EOFBlob(image) == MagickFalse; ) { register char *p; count=ReadBlob(image,8,(unsigned char *) keyword); if (count != 8) break; for (i=0; i < 8; i++) { if (isspace((int) ((unsigned char) keyword[i])) != 0) break; keyword[i]=tolower((int) ((unsigned char) keyword[i])); } keyword[i]='\0'; count=ReadBlob(image,72,(unsigned char *) value); value[72]='\0'; if (count != 72) break; p=value; if (*p == '=') { p+=2; while (isspace((int) ((unsigned char) *p)) != 0) p++; } if (LocaleCompare(keyword,"end") == 0) break; if (LocaleCompare(keyword,"extend") == 0) fits_info.extend=(*p == 'T') || (*p == 't') ? MagickTrue : MagickFalse; if (LocaleCompare(keyword,"simple") == 0) fits_info.simple=(*p == 'T') || (*p == 't') ? MagickTrue : MagickFalse; if (LocaleCompare(keyword,"bitpix") == 0) fits_info.bits_per_pixel=StringToLong(p); if (LocaleCompare(keyword,"naxis") == 0) fits_info.number_axes=StringToLong(p); if (LocaleCompare(keyword,"naxis1") == 0) fits_info.columns=StringToLong(p); if (LocaleCompare(keyword,"naxis2") == 0) fits_info.rows=StringToLong(p); if (LocaleCompare(keyword,"naxis3") == 0) fits_info.number_planes=StringToLong(p); if (LocaleCompare(keyword,"datamax") == 0) fits_info.max_data=StringToDouble(p,(char **) NULL); if (LocaleCompare(keyword,"datamin") == 0) fits_info.min_data=StringToDouble(p,(char **) NULL); if (LocaleCompare(keyword,"bzero") == 0) fits_info.zero=StringToDouble(p,(char **) NULL); if (LocaleCompare(keyword,"bscale") == 0) fits_info.scale=StringToDouble(p,(char **) NULL); if (LocaleCompare(keyword,"comment") == 0) { if (comment == (char *) NULL) comment=ConstantString(p); else (void) ConcatenateString(&comment,p); } if (LocaleCompare(keyword,"xendian") == 0) { if (LocaleNCompare(p,"big",3) == 0) fits_info.endian=MSBEndian; else fits_info.endian=LSBEndian; } (void) FormatLocaleString(property,MaxTextExtent,"fits:%s",keyword); (void) SetImageProperty(image,property,p); } c=0; while (((TellBlob(image) % FITSBlocksize) != 0) && (c != EOF)) c=ReadBlobByte(image); if (fits_info.extend == MagickFalse) break; number_pixels=(MagickSizeType) fits_info.columns*fits_info.rows; if ((fits_info.simple != MagickFalse) && (fits_info.number_axes >= 1) && (fits_info.number_axes <= 4) && (number_pixels != 0)) break; } /* Verify that required image information is defined. */ if (comment != (char *) NULL) { (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); number_pixels=(MagickSizeType) fits_info.columns*fits_info.rows; if ((fits_info.simple == MagickFalse) || (fits_info.number_axes < 1) || (fits_info.number_axes > 4) || (number_pixels == 0)) ThrowReaderException(CorruptImageError,"ImageTypeNotSupported"); for (scene=0; scene < (ssize_t) fits_info.number_planes; scene++) { image->columns=(size_t) fits_info.columns; image->rows=(size_t) fits_info.rows; image->depth=(size_t) (fits_info.bits_per_pixel < 0 ? -1 : 1)* fits_info.bits_per_pixel; image->endian=fits_info.endian; image->scene=(size_t) scene; 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)); } /* Initialize image structure. */ (void) SetImageColorspace(image,GRAYColorspace); if ((fits_info.min_data == 0.0) && (fits_info.max_data == 0.0)) { if (fits_info.zero == 0.0) (void) GetFITSPixelExtrema(image,fits_info.bits_per_pixel, &fits_info.min_data,&fits_info.max_data); else fits_info.max_data=GetFITSPixelRange((size_t) fits_info.bits_per_pixel); } else fits_info.max_data=GetFITSPixelRange((size_t) fits_info.bits_per_pixel); /* Convert FITS pixels to pixel packets. */ scale=QuantumRange/(fits_info.max_data-fits_info.min_data); for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=GetFITSPixel(image,fits_info.bits_per_pixel); if ((image->depth == 16) || (image->depth == 32) || (image->depth == 64)) SetFITSUnsignedPixels(1,image->depth,image->endian,(unsigned char *) &pixel); SetPixelRed(q,ClampToQuantum(scale*(fits_info.scale*(pixel- fits_info.min_data)+fits_info.zero))); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); 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 (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 (scene < (ssize_t) (fits_info.number_planes-1)) { /* 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; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r F I T S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterFITSImage() adds attributes for the FITS image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterFITSImage method is: % % size_t RegisterFITSImage(void) % */ ModuleExport size_t RegisterFITSImage(void) { MagickInfo *entry; entry=SetMagickInfo("FITS"); entry->decoder=(DecodeImageHandler *) ReadFITSImage; entry->encoder=(EncodeImageHandler *) WriteFITSImage; entry->magick=(IsImageFormatHandler *) IsFITS; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Flexible Image Transport System"); entry->module=ConstantString("FITS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("FTS"); entry->decoder=(DecodeImageHandler *) ReadFITSImage; entry->encoder=(EncodeImageHandler *) WriteFITSImage; entry->magick=(IsImageFormatHandler *) IsFITS; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Flexible Image Transport System"); entry->module=ConstantString("FTS"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r F I T S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterFITSImage() removes format registrations made by the % FITS module from the list of supported formats. % % The format of the UnregisterFITSImage method is: % % UnregisterFITSImage(void) % */ ModuleExport void UnregisterFITSImage(void) { (void) UnregisterMagickInfo("FITS"); (void) UnregisterMagickInfo("FTS"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e F I T S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteFITSImage() writes a Flexible Image Transport System image to a % file as gray scale intensities [0..255]. % % The format of the WriteFITSImage method is: % % MagickBooleanType WriteFITSImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteFITSImage(const ImageInfo *image_info, Image *image) { char header[FITSBlocksize], *fits_info; MagickBooleanType status; QuantumInfo *quantum_info; register const PixelPacket *p; size_t length; ssize_t count, offset, y; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Allocate image memory. */ fits_info=(char *) AcquireQuantumMemory(FITSBlocksize,sizeof(*fits_info)); if (fits_info == (char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(fits_info,' ',FITSBlocksize*sizeof(*fits_info)); /* Initialize image header. */ image->depth=GetImageQuantumDepth(image,MagickFalse); image->endian=MSBEndian; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); offset=0; (void) FormatLocaleString(header,FITSBlocksize, "SIMPLE = T"); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"BITPIX = %10ld", (long) ((quantum_info->format == FloatingPointQuantumFormat ? -1 : 1)* image->depth)); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"NAXIS = %10lu", IsGrayImage(image,&image->exception) != MagickFalse ? 2UL : 3UL); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"NAXIS1 = %10lu", (unsigned long) image->columns); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"NAXIS2 = %10lu", (unsigned long) image->rows); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; if (IsGrayImage(image,&image->exception) == MagickFalse) { (void) FormatLocaleString(header,FITSBlocksize, "NAXIS3 = %10lu",3UL); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; } (void) FormatLocaleString(header,FITSBlocksize,"BSCALE = %E",1.0); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"BZERO = %E", image->depth > 8 ? GetFITSPixelRange(image->depth)/2.0 : 0.0); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"DATAMAX = %E", 1.0*((MagickOffsetType) GetQuantumRange(image->depth))); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) FormatLocaleString(header,FITSBlocksize,"DATAMIN = %E",0.0); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; if (image->endian == LSBEndian) { (void) FormatLocaleString(header,FITSBlocksize,"XENDIAN = 'SMALL'"); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; } (void) FormatLocaleString(header,FITSBlocksize,"HISTORY %.72s", GetMagickVersion((size_t *) NULL)); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) strncpy(header,"END",FITSBlocksize); (void) strncpy(fits_info+offset,header,strlen(header)); offset+=80; (void) WriteBlob(image,FITSBlocksize,(unsigned char *) fits_info); /* Convert image to fits scale PseudoColor class. */ pixels=GetQuantumPixels(quantum_info); if (IsGrayImage(image,&image->exception) != MagickFalse) { length=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,pixels,&image->exception); if (image->depth == 16) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); if (((image->depth == 32) || (image->depth == 64)) && (quantum_info->format != FloatingPointQuantumFormat)) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { length=GetQuantumExtent(image,quantum_info,RedQuantum); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, RedQuantum,pixels,&image->exception); if (image->depth == 16) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); if (((image->depth == 32) || (image->depth == 64)) && (quantum_info->format != FloatingPointQuantumFormat)) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } length=GetQuantumExtent(image,quantum_info,GreenQuantum); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GreenQuantum,pixels,&image->exception); if (image->depth == 16) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); if (((image->depth == 32) || (image->depth == 64)) && (quantum_info->format != FloatingPointQuantumFormat)) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } length=GetQuantumExtent(image,quantum_info,BlueQuantum); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, BlueQuantum,pixels,&image->exception); if (image->depth == 16) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); if (((image->depth == 32) || (image->depth == 64)) && (quantum_info->format != FloatingPointQuantumFormat)) SetFITSUnsignedPixels(image->columns,image->depth,image->endian, pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); length=(size_t) (FITSBlocksize-TellBlob(image) % FITSBlocksize); if (length != 0) { (void) ResetMagickMemory(fits_info,0,length*sizeof(*fits_info)); (void) WriteBlob(image,length,(unsigned char *) fits_info); } fits_info=DestroyString(fits_info); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_19
crossvul-cpp_data_bad_2135_0
/* * Copyright (c) Ian F. Darwin 1986-1995. * Software written by Ian F. Darwin and others; * maintained 1995-present by Christos Zoulas and others. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * softmagic - interpret variable magic from MAGIC */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: softmagic.c,v 1.189 2014/05/30 16:47:44 christos Exp $") #endif /* lint */ #include "magic.h" #include <assert.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <time.h> #if defined(HAVE_LOCALE_H) #include <locale.h> #endif private int match(struct magic_set *, struct magic *, uint32_t, const unsigned char *, size_t, size_t, int, int, int, int, int *, int *, int *); private int mget(struct magic_set *, const unsigned char *, struct magic *, size_t, size_t, unsigned int, int, int, int, int, int *, int *, int *); private int magiccheck(struct magic_set *, struct magic *); private int32_t mprint(struct magic_set *, struct magic *); private int32_t moffset(struct magic_set *, struct magic *); private void mdebug(uint32_t, const char *, size_t); private int mcopy(struct magic_set *, union VALUETYPE *, int, int, const unsigned char *, uint32_t, size_t, struct magic *); private int mconvert(struct magic_set *, struct magic *, int); private int print_sep(struct magic_set *, int); private int handle_annotation(struct magic_set *, struct magic *); private void cvt_8(union VALUETYPE *, const struct magic *); private void cvt_16(union VALUETYPE *, const struct magic *); private void cvt_32(union VALUETYPE *, const struct magic *); private void cvt_64(union VALUETYPE *, const struct magic *); #define OFFSET_OOB(n, o, i) ((n) < (o) || (i) > ((n) - (o))) /* * softmagic - lookup one file in parsed, in-memory copy of database * Passed the name and FILE * of one file to be typed. */ /*ARGSUSED1*/ /* nbytes passed for regularity, maybe need later */ protected int file_softmagic(struct magic_set *ms, const unsigned char *buf, size_t nbytes, size_t level, int mode, int text) { struct mlist *ml; int rv, printed_something = 0, need_separator = 0; for (ml = ms->mlist[0]->next; ml != ms->mlist[0]; ml = ml->next) if ((rv = match(ms, ml->magic, ml->nmagic, buf, nbytes, 0, mode, text, 0, level, &printed_something, &need_separator, NULL)) != 0) return rv; return 0; } #define FILE_FMTDEBUG #ifdef FILE_FMTDEBUG #define F(a, b, c) file_fmtcheck((a), (b), (c), __FILE__, __LINE__) private const char * __attribute__((__format_arg__(3))) file_fmtcheck(struct magic_set *ms, const struct magic *m, const char *def, const char *file, size_t line) { const char *ptr = fmtcheck(m->desc, def); if (ptr == def) file_magerror(ms, "%s, %zu: format `%s' does not match with `%s'", file, line, m->desc, def); return ptr; } #else #define F(a, b, c) fmtcheck((b)->desc, (c)) #endif /* * Go through the whole list, stopping if you find a match. Process all * the continuations of that match before returning. * * We support multi-level continuations: * * At any time when processing a successful top-level match, there is a * current continuation level; it represents the level of the last * successfully matched continuation. * * Continuations above that level are skipped as, if we see one, it * means that the continuation that controls them - i.e, the * lower-level continuation preceding them - failed to match. * * Continuations below that level are processed as, if we see one, * it means we've finished processing or skipping higher-level * continuations under the control of a successful or unsuccessful * lower-level continuation, and are now seeing the next lower-level * continuation and should process it. The current continuation * level reverts to the level of the one we're seeing. * * Continuations at the current level are processed as, if we see * one, there's no lower-level continuation that may have failed. * * If a continuation matches, we bump the current continuation level * so that higher-level continuations are processed. */ private int match(struct magic_set *ms, struct magic *magic, uint32_t nmagic, const unsigned char *s, size_t nbytes, size_t offset, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t magindex = 0; unsigned int cont_level = 0; int returnvalv = 0, e; /* if a match is found it is set to 1*/ int firstline = 1; /* a flag to print X\n X\n- X */ int print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0; if (returnval == NULL) returnval = &returnvalv; if (file_check_mem(ms, cont_level) == -1) return -1; for (magindex = 0; magindex < nmagic; magindex++) { int flush = 0; struct magic *m = &magic[magindex]; if (m->type != FILE_NAME) if ((IS_STRING(m->type) && #define FLT (STRING_BINTEST | STRING_TEXTTEST) ((text && (m->str_flags & FLT) == STRING_BINTEST) || (!text && (m->str_flags & FLT) == STRING_TEXTTEST))) || (m->flag & mode) != mode) { /* Skip sub-tests */ while (magindex + 1 < nmagic && magic[magindex + 1].cont_level != 0 && ++magindex) continue; continue; /* Skip to next top-level test*/ } ms->offset = m->offset; ms->line = m->lineno; /* if main entry matches, print it... */ switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text, flip, recursion_level + 1, printed_something, need_separator, returnval)) { case -1: return -1; case 0: flush = m->reln != '!'; break; default: if (m->type == FILE_INDIRECT) *returnval = 1; switch (magiccheck(ms, m)) { case -1: return -1; case 0: flush++; break; default: flush = 0; break; } break; } if (flush) { /* * main entry didn't match, * flush its continuations */ while (magindex < nmagic - 1 && magic[magindex + 1].cont_level != 0) magindex++; continue; } if ((e = handle_annotation(ms, m)) != 0) { *need_separator = 1; *printed_something = 1; *returnval = 1; return e; } /* * If we are going to print something, we'll need to print * a blank before we print something else. */ if (*m->desc) { *need_separator = 1; *printed_something = 1; if (print_sep(ms, firstline) == -1) return -1; } if (print && mprint(ms, m) == -1) return -1; ms->c.li[cont_level].off = moffset(ms, m); /* and any continuations that match */ if (file_check_mem(ms, ++cont_level) == -1) return -1; while (++magindex < nmagic && magic[magindex].cont_level != 0) { m = &magic[magindex]; ms->line = m->lineno; /* for messages */ if (cont_level < m->cont_level) continue; if (cont_level > m->cont_level) { /* * We're at the end of the level * "cont_level" continuations. */ cont_level = m->cont_level; } ms->offset = m->offset; if (m->flag & OFFADD) { ms->offset += ms->c.li[cont_level - 1].off; } #ifdef ENABLE_CONDITIONALS if (m->cond == COND_ELSE || m->cond == COND_ELIF) { if (ms->c.li[cont_level].last_match == 1) continue; } #endif switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text, flip, recursion_level + 1, printed_something, need_separator, returnval)) { case -1: return -1; case 0: if (m->reln != '!') continue; flush = 1; break; default: if (m->type == FILE_INDIRECT) *returnval = 1; flush = 0; break; } switch (flush ? 1 : magiccheck(ms, m)) { case -1: return -1; case 0: #ifdef ENABLE_CONDITIONALS ms->c.li[cont_level].last_match = 0; #endif break; default: #ifdef ENABLE_CONDITIONALS ms->c.li[cont_level].last_match = 1; #endif if (m->type == FILE_CLEAR) ms->c.li[cont_level].got_match = 0; else if (ms->c.li[cont_level].got_match) { if (m->type == FILE_DEFAULT) break; } else ms->c.li[cont_level].got_match = 1; if ((e = handle_annotation(ms, m)) != 0) { *need_separator = 1; *printed_something = 1; *returnval = 1; return e; } /* * If we are going to print something, * make sure that we have a separator first. */ if (*m->desc) { if (!*printed_something) { *printed_something = 1; if (print_sep(ms, firstline) == -1) return -1; } } /* * This continuation matched. Print * its message, with a blank before it * if the previous item printed and * this item isn't empty. */ /* space if previous printed */ if (*need_separator && ((m->flag & NOSPACE) == 0) && *m->desc) { if (print && file_printf(ms, " ") == -1) return -1; *need_separator = 0; } if (print && mprint(ms, m) == -1) return -1; ms->c.li[cont_level].off = moffset(ms, m); if (*m->desc) *need_separator = 1; /* * If we see any continuations * at a higher level, * process them. */ if (file_check_mem(ms, ++cont_level) == -1) return -1; break; } } if (*printed_something) { firstline = 0; if (print) *returnval = 1; } if ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) { return *returnval; /* don't keep searching */ } } return *returnval; /* This is hit if -k is set or there is no match */ } private int check_fmt(struct magic_set *ms, struct magic *m) { file_regex_t rx; int rc, rv = -1; if (strchr(m->desc, '%') == NULL) return 0; rc = file_regcomp(&rx, "%[-0-9\\.]*s", REG_EXTENDED|REG_NOSUB); if (rc) { file_regerror(&rx, rc, ms); } else { rc = file_regexec(&rx, m->desc, 0, 0, 0); rv = !rc; } file_regfree(&rx); return rv; } #ifndef HAVE_STRNDUP char * strndup(const char *, size_t); char * strndup(const char *str, size_t n) { size_t len; char *copy; for (len = 0; len < n && str[len]; len++) continue; if ((copy = malloc(len + 1)) == NULL) return NULL; (void)memcpy(copy, str, len); copy[len] = '\0'; return copy; } #endif /* HAVE_STRNDUP */ private int32_t mprint(struct magic_set *ms, struct magic *m) { uint64_t v; float vf; double vd; int64_t t = 0; char buf[128], tbuf[26]; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = file_signextend(ms, m, (uint64_t)p->b); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%d", (unsigned char)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%d"), (unsigned char) v) == -1) return -1; break; } t = ms->offset + sizeof(char); break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = file_signextend(ms, m, (uint64_t)p->h); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%u", (unsigned short)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%u"), (unsigned short) v) == -1) return -1; break; } t = ms->offset + sizeof(short); break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: v = file_signextend(ms, m, (uint64_t)p->l); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%u", (uint32_t) v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%u"), (uint32_t) v) == -1) return -1; break; } t = ms->offset + sizeof(int32_t); break; case FILE_QUAD: case FILE_BEQUAD: case FILE_LEQUAD: v = file_signextend(ms, m, p->q); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%" INT64_T_FORMAT "u", (unsigned long long)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%" INT64_T_FORMAT "u"), (unsigned long long) v) == -1) return -1; break; } t = ms->offset + sizeof(int64_t); break; case FILE_STRING: case FILE_PSTRING: case FILE_BESTRING16: case FILE_LESTRING16: if (m->reln == '=' || m->reln == '!') { if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1) return -1; t = ms->offset + m->vallen; } else { char *str = p->s; /* compute t before we mangle the string? */ t = ms->offset + strlen(str); if (*m->value.s == '\0') str[strcspn(str, "\n")] = '\0'; if (m->str_flags & STRING_TRIM) { char *last; while (isspace((unsigned char)*str)) str++; last = str; while (*last) last++; --last; while (isspace((unsigned char)*last)) last--; *++last = '\0'; } if (file_printf(ms, F(ms, m, "%s"), str) == -1) return -1; if (m->type == FILE_PSTRING) t += file_pstring_length_size(m); } break; case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->l + m->num_mask, FILE_T_LOCAL, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint32_t); break; case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->l + m->num_mask, 0, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint32_t); break; case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q + m->num_mask, FILE_T_LOCAL, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q + m->num_mask, 0, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q + m->num_mask, FILE_T_WINDOWS, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: vf = p->f; switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%g", vf); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%g"), vf) == -1) return -1; break; } t = ms->offset + sizeof(float); break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: vd = p->d; switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%g", vd); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%g"), vd) == -1) return -1; break; } t = ms->offset + sizeof(double); break; case FILE_REGEX: { char *cp; int rval; cp = strndup((const char *)ms->search.s, ms->search.rm_len); if (cp == NULL) { file_oomem(ms, ms->search.rm_len); return -1; } rval = file_printf(ms, F(ms, m, "%s"), cp); free(cp); if (rval == -1) return -1; if ((m->str_flags & REGEX_OFFSET_START)) t = ms->search.offset; else t = ms->search.offset + ms->search.rm_len; break; } case FILE_SEARCH: if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1) return -1; if ((m->str_flags & REGEX_OFFSET_START)) t = ms->search.offset; else t = ms->search.offset + m->vallen; break; case FILE_DEFAULT: case FILE_CLEAR: if (file_printf(ms, "%s", m->desc) == -1) return -1; t = ms->offset; break; case FILE_INDIRECT: case FILE_USE: case FILE_NAME: t = ms->offset; break; default: file_magerror(ms, "invalid m->type (%d) in mprint()", m->type); return -1; } return (int32_t)t; } private int32_t moffset(struct magic_set *ms, struct magic *m) { switch (m->type) { case FILE_BYTE: return CAST(int32_t, (ms->offset + sizeof(char))); case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: return CAST(int32_t, (ms->offset + sizeof(short))); case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: return CAST(int32_t, (ms->offset + sizeof(int32_t))); case FILE_QUAD: case FILE_BEQUAD: case FILE_LEQUAD: return CAST(int32_t, (ms->offset + sizeof(int64_t))); case FILE_STRING: case FILE_PSTRING: case FILE_BESTRING16: case FILE_LESTRING16: if (m->reln == '=' || m->reln == '!') return ms->offset + m->vallen; else { union VALUETYPE *p = &ms->ms_value; uint32_t t; if (*m->value.s == '\0') p->s[strcspn(p->s, "\n")] = '\0'; t = CAST(uint32_t, (ms->offset + strlen(p->s))); if (m->type == FILE_PSTRING) t += (uint32_t)file_pstring_length_size(m); return t; } case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: return CAST(int32_t, (ms->offset + sizeof(uint32_t))); case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: return CAST(int32_t, (ms->offset + sizeof(uint32_t))); case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: return CAST(int32_t, (ms->offset + sizeof(uint64_t))); case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: return CAST(int32_t, (ms->offset + sizeof(uint64_t))); case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: return CAST(int32_t, (ms->offset + sizeof(float))); case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: return CAST(int32_t, (ms->offset + sizeof(double))); case FILE_REGEX: if ((m->str_flags & REGEX_OFFSET_START) != 0) return CAST(int32_t, ms->search.offset); else return CAST(int32_t, (ms->search.offset + ms->search.rm_len)); case FILE_SEARCH: if ((m->str_flags & REGEX_OFFSET_START) != 0) return CAST(int32_t, ms->search.offset); else return CAST(int32_t, (ms->search.offset + m->vallen)); case FILE_CLEAR: case FILE_DEFAULT: case FILE_INDIRECT: return ms->offset; default: return 0; } } private int cvt_flip(int type, int flip) { if (flip == 0) return type; switch (type) { case FILE_BESHORT: return FILE_LESHORT; case FILE_BELONG: return FILE_LELONG; case FILE_BEDATE: return FILE_LEDATE; case FILE_BELDATE: return FILE_LELDATE; case FILE_BEQUAD: return FILE_LEQUAD; case FILE_BEQDATE: return FILE_LEQDATE; case FILE_BEQLDATE: return FILE_LEQLDATE; case FILE_BEQWDATE: return FILE_LEQWDATE; case FILE_LESHORT: return FILE_BESHORT; case FILE_LELONG: return FILE_BELONG; case FILE_LEDATE: return FILE_BEDATE; case FILE_LELDATE: return FILE_BELDATE; case FILE_LEQUAD: return FILE_BEQUAD; case FILE_LEQDATE: return FILE_BEQDATE; case FILE_LEQLDATE: return FILE_BEQLDATE; case FILE_LEQWDATE: return FILE_BEQWDATE; case FILE_BEFLOAT: return FILE_LEFLOAT; case FILE_LEFLOAT: return FILE_BEFLOAT; case FILE_BEDOUBLE: return FILE_LEDOUBLE; case FILE_LEDOUBLE: return FILE_BEDOUBLE; default: return type; } } #define DO_CVT(fld, cast) \ if (m->num_mask) \ switch (m->mask_op & FILE_OPS_MASK) { \ case FILE_OPAND: \ p->fld &= cast m->num_mask; \ break; \ case FILE_OPOR: \ p->fld |= cast m->num_mask; \ break; \ case FILE_OPXOR: \ p->fld ^= cast m->num_mask; \ break; \ case FILE_OPADD: \ p->fld += cast m->num_mask; \ break; \ case FILE_OPMINUS: \ p->fld -= cast m->num_mask; \ break; \ case FILE_OPMULTIPLY: \ p->fld *= cast m->num_mask; \ break; \ case FILE_OPDIVIDE: \ p->fld /= cast m->num_mask; \ break; \ case FILE_OPMODULO: \ p->fld %= cast m->num_mask; \ break; \ } \ if (m->mask_op & FILE_OPINVERSE) \ p->fld = ~p->fld \ private void cvt_8(union VALUETYPE *p, const struct magic *m) { DO_CVT(b, (uint8_t)); } private void cvt_16(union VALUETYPE *p, const struct magic *m) { DO_CVT(h, (uint16_t)); } private void cvt_32(union VALUETYPE *p, const struct magic *m) { DO_CVT(l, (uint32_t)); } private void cvt_64(union VALUETYPE *p, const struct magic *m) { DO_CVT(q, (uint64_t)); } #define DO_CVT2(fld, cast) \ if (m->num_mask) \ switch (m->mask_op & FILE_OPS_MASK) { \ case FILE_OPADD: \ p->fld += cast m->num_mask; \ break; \ case FILE_OPMINUS: \ p->fld -= cast m->num_mask; \ break; \ case FILE_OPMULTIPLY: \ p->fld *= cast m->num_mask; \ break; \ case FILE_OPDIVIDE: \ p->fld /= cast m->num_mask; \ break; \ } \ private void cvt_float(union VALUETYPE *p, const struct magic *m) { DO_CVT2(f, (float)); } private void cvt_double(union VALUETYPE *p, const struct magic *m) { DO_CVT2(d, (double)); } /* * Convert the byte order of the data we are looking at * While we're here, let's apply the mask operation * (unless you have a better idea) */ private int mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } private void mdebug(uint32_t offset, const char *str, size_t len) { (void) fprintf(stderr, "mget/%zu @%d: ", len, offset); file_showstr(stderr, str, len); (void) fputc('\n', stderr); (void) fputc('\n', stderr); } private int mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines, linecnt, bytecnt; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } if (m->str_flags & REGEX_LINE_COUNT) { linecnt = m->str_range; bytecnt = linecnt * 80; } else { linecnt = 0; bytecnt = m->str_range; } if (bytecnt == 0) bytecnt = 8192; if (bytecnt > nbytes) bytecnt = nbytes; buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + bytecnt; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\r' && b[1] == '\n') b++; } if (lines) last = RCAST(const char *, s) + bytecnt; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\0' : *(src + 1) != '\0') *dst = ' '; } } *edst = '\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\0', sizeof(*p) - nbytes); return 0; } private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t lhs; int rv, oneed_separator, in_type; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, m) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, " "nbytes=%zu)\n", m->type, m->flag, offset, o, nbytes); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (in_type = cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[0] << 8) | p->hs[1]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[1] << 8) | p->hs[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[0] << 24) | (p->hl[1] << 16) | (p->hl[2] << 8) | p->hl[3]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[3] << 24) | (p->hl[2] << 16) | (p->hl[1] << 8) | p->hl[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[1] << 24) | (p->hl[0] << 16) | (p->hl[3] << 8) | p->hl[2]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; default: break; } switch (in_type) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (OFFSET_OOB(nbytes, offset, 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (OFFSET_OOB(nbytes, offset, 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (OFFSET_OOB(nbytes, offset, m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (offset == 0) return 0; if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, recursion_level, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, F(ms, m, "%u"), offset) == -1) { free(rbuf); return -1; } if (file_printf(ms, "%s", rbuf) == -1) { free(rbuf); return -1; } } free(rbuf); return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ case FILE_CLEAR: default: break; } if (!mconvert(ms, m, flip)) return 0; return 1; } private uint64_t file_strncmp(const char *s1, const char *s2, size_t len, uint32_t flags) { /* * Convert the source args to unsigned here so that (1) the * compare will be unsigned as it is in strncmp() and (2) so * the ctype functions will work correctly without extra * casting. */ const unsigned char *a = (const unsigned char *)s1; const unsigned char *b = (const unsigned char *)s2; uint64_t v; /* * What we want here is v = strncmp(s1, s2, len), * but ignoring any nulls. */ v = 0; if (0L == flags) { /* normal string: do it fast */ while (len-- > 0) if ((v = *b++ - *a++) != '\0') break; } else { /* combine the others */ while (len-- > 0) { if ((flags & STRING_IGNORE_LOWERCASE) && islower(*a)) { if ((v = tolower(*b++) - *a++) != '\0') break; } else if ((flags & STRING_IGNORE_UPPERCASE) && isupper(*a)) { if ((v = toupper(*b++) - *a++) != '\0') break; } else if ((flags & STRING_COMPACT_WHITESPACE) && isspace(*a)) { a++; if (isspace(*b++)) { if (!isspace(*a)) while (isspace(*b)) b++; } else { v = 1; break; } } else if ((flags & STRING_COMPACT_OPTIONAL_WHITESPACE) && isspace(*a)) { a++; while (isspace(*b)) b++; } else { if ((v = *b++ - *a++) != '\0') break; } } } return v; } private uint64_t file_strncmp16(const char *a, const char *b, size_t len, uint32_t flags) { /* * XXX - The 16-bit string compare probably needs to be done * differently, especially if the flags are to be supported. * At the moment, I am unsure. */ flags = 0; return file_strncmp(a, b, len, flags); } private int magiccheck(struct magic_set *ms, struct magic *m) { uint64_t l = m->value.q; uint64_t v; float fl, fv; double dl, dv; int matched; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = p->b; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = p->h; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: v = p->l; break; case FILE_QUAD: case FILE_LEQUAD: case FILE_BEQUAD: case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: v = p->q; break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: fl = m->value.f; fv = p->f; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = fv != fl; break; case '=': matched = fv == fl; break; case '>': matched = fv > fl; break; case '<': matched = fv < fl; break; default: file_magerror(ms, "cannot happen with float: invalid relation `%c'", m->reln); return -1; } return matched; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: dl = m->value.d; dv = p->d; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = dv != dl; break; case '=': matched = dv == dl; break; case '>': matched = dv > dl; break; case '<': matched = dv < dl; break; default: file_magerror(ms, "cannot happen with double: invalid relation `%c'", m->reln); return -1; } return matched; case FILE_DEFAULT: case FILE_CLEAR: l = 0; v = 0; break; case FILE_STRING: case FILE_PSTRING: l = 0; v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_BESTRING16: case FILE_LESTRING16: l = 0; v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */ size_t slen; size_t idx; if (ms->search.s == NULL) return 0; slen = MIN(m->vallen, sizeof(m->value.s)); l = 0; v = 0; for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) { if (slen + idx > ms->search.s_len) break; v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags); if (v == 0) { /* found match */ ms->search.offset += idx; break; } } break; } case FILE_REGEX: { int rc; file_regex_t rx; if (ms->search.s == NULL) return 0; l = 0; rc = file_regcomp(&rx, m->value.s, REG_EXTENDED|REG_NEWLINE| ((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0)); if (rc) { file_regerror(&rx, rc, ms); v = (uint64_t)-1; } else { regmatch_t pmatch[1]; size_t slen = ms->search.s_len; #ifndef REG_STARTEND #define REG_STARTEND 0 char c; if (slen != 0) slen--; c = ms->search.s[slen]; ((char *)(intptr_t)ms->search.s)[slen] = '\0'; #else pmatch[0].rm_so = 0; pmatch[0].rm_eo = slen; #endif rc = file_regexec(&rx, (const char *)ms->search.s, 1, pmatch, REG_STARTEND); #if REG_STARTEND == 0 ((char *)(intptr_t)ms->search.s)[l] = c; #endif switch (rc) { case 0: ms->search.s += (int)pmatch[0].rm_so; ms->search.offset += (size_t)pmatch[0].rm_so; ms->search.rm_len = (size_t)(pmatch[0].rm_eo - pmatch[0].rm_so); v = 0; break; case REG_NOMATCH: v = 1; break; default: file_regerror(&rx, rc, ms); v = (uint64_t)-1; break; } } file_regfree(&rx); if (v == (uint64_t)-1) return -1; break; } case FILE_INDIRECT: case FILE_USE: case FILE_NAME: return 1; default: file_magerror(ms, "invalid type %d in magiccheck()", m->type); return -1; } v = file_signextend(ms, m, v); switch (m->reln) { case 'x': if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u == *any* = 1\n", (unsigned long long)v); matched = 1; break; case '!': matched = v != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u != %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); break; case '=': matched = v == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u == %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); break; case '>': if (m->flag & UNSIGNED) { matched = v > l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u > %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v > (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "d > %" INT64_T_FORMAT "d = %d\n", (long long)v, (long long)l, matched); } break; case '<': if (m->flag & UNSIGNED) { matched = v < l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "u < %" INT64_T_FORMAT "u = %d\n", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v < (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "%" INT64_T_FORMAT "d < %" INT64_T_FORMAT "d = %d\n", (long long)v, (long long)l, matched); } break; case '&': matched = (v & l) == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %" INT64_T_FORMAT "x) == %" INT64_T_FORMAT "x) = %d\n", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; case '^': matched = (v & l) != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, "((%" INT64_T_FORMAT "x & %" INT64_T_FORMAT "x) != %" INT64_T_FORMAT "x) = %d\n", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; default: file_magerror(ms, "cannot happen: invalid relation `%c'", m->reln); return -1; } return matched; } private int handle_annotation(struct magic_set *ms, struct magic *m) { if (ms->flags & MAGIC_APPLE) { if (file_printf(ms, "%.8s", m->apple) == -1) return -1; return 1; } if ((ms->flags & MAGIC_MIME_TYPE) && m->mimetype[0]) { if (file_printf(ms, "%s", m->mimetype) == -1) return -1; return 1; } return 0; } private int print_sep(struct magic_set *ms, int firstline) { if (ms->flags & MAGIC_MIME) return 0; if (firstline) return 0; /* * we found another match * put a newline and '-' to do some simple formatting */ return file_printf(ms, "\n- "); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2135_0
crossvul-cpp_data_good_161_0
/* * This file is part of Espruino, a JavaScript interpreter for Microcontrollers * * Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * ---------------------------------------------------------------------------- * Variables * ---------------------------------------------------------------------------- */ #include "jsvar.h" #include "jslex.h" #include "jsparse.h" #include "jswrap_json.h" #include "jsinteractive.h" #include "jswrapper.h" #include "jswrap_math.h" // for jswrap_math_mod #include "jswrap_object.h" // for jswrap_object_toString #include "jswrap_arraybuffer.h" // for jsvNewTypedArray #include "jswrap_dataview.h" // for jsvNewDataViewWithData #ifdef DEBUG /** When freeing, clear the references (nextChild/etc) in the JsVar. * This means we can assert at the end of jsvFreePtr to make sure * everything really is free. */ #define CLEAR_MEMORY_ON_FREE #endif /** Basically, JsVars are stored in one big array, so save the need for * lots of memory allocation. On Linux, the arrays are in blocks, so that * more blocks can be allocated. We can't use realloc on one big block as * this may change the address of vars that are already locked! * */ #ifdef RESIZABLE_JSVARS JsVar **jsVarBlocks = 0; unsigned int jsVarsSize = 0; #define JSVAR_BLOCK_SIZE 4096 #define JSVAR_BLOCK_SHIFT 12 #else JsVar jsVars[JSVAR_CACHE_SIZE]; unsigned int jsVarsSize = JSVAR_CACHE_SIZE; #endif typedef enum { MEM_NOT_BUSY, MEMBUSY_SYSTEM, MEMBUSY_GC } MemBusyType; volatile bool touchedFreeList = false; volatile JsVarRef jsVarFirstEmpty; ///< reference of first unused variable (variables are in a linked list) volatile MemBusyType isMemoryBusy; ///< Are we doing garbage collection or similar, so can't access memory? // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- bool jsvIsRoot(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ROOT; } bool jsvIsPin(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_PIN; } bool jsvIsSimpleInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_INTEGER; } // is just a very basic integer value bool jsvIsInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_INTEGER || (v->flags&JSV_VARTYPEMASK)==JSV_PIN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); } bool jsvIsFloat(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLOAT; } bool jsvIsBoolean(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_BOOLEAN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); } bool jsvIsString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_STRING_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_STRING_END; } ///< String, or a NAME too bool jsvIsBasicString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=JSV_STRING_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_STRING_MAX; } ///< Just a string (NOT a name) bool jsvIsStringExt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=JSV_STRING_EXT_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_STRING_EXT_MAX; } ///< The extra bits dumped onto the end of a string to store more data bool jsvIsFlatString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLAT_STRING; } bool jsvIsNativeString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NATIVE_STRING; } bool jsvIsNumeric(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NUMERIC_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NUMERIC_END; } bool jsvIsFunction(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION || (v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); } bool jsvIsFunctionReturn(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); } ///< Is this a function with an implicit 'return' at the start? bool jsvIsFunctionParameter(const JsVar *v) { return v && (v->flags&JSV_NATIVE) && jsvIsString(v); } bool jsvIsObject(const JsVar *v) { return v && (((v->flags&JSV_VARTYPEMASK)==JSV_OBJECT) || ((v->flags&JSV_VARTYPEMASK)==JSV_ROOT)); } bool jsvIsArray(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ARRAY; } bool jsvIsArrayBuffer(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ARRAYBUFFER; } bool jsvIsArrayBufferName(const JsVar *v) { return v && (v->flags&(JSV_VARTYPEMASK))==JSV_ARRAYBUFFERNAME; } bool jsvIsNative(const JsVar *v) { return v && (v->flags&JSV_NATIVE)!=0; } bool jsvIsNativeFunction(const JsVar *v) { return v && (v->flags&(JSV_NATIVE|JSV_VARTYPEMASK))==(JSV_NATIVE|JSV_FUNCTION); } bool jsvIsUndefined(const JsVar *v) { return v==0; } bool jsvIsNull(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NULL; } bool jsvIsBasic(const JsVar *v) { return jsvIsNumeric(v) || jsvIsString(v);} ///< Is this *not* an array/object/etc bool jsvIsName(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NAME_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NAME_END; } ///< NAMEs are what's used to name a variable (it is not the data itself) /// Names with values have firstChild set to a value - AND NOT A REFERENCE bool jsvIsNameWithValue(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NAME_WITH_VALUE_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NAME_WITH_VALUE_END; } bool jsvIsNameInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || ((v->flags&JSV_VARTYPEMASK)>=JSV_NAME_STRING_INT_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_NAME_STRING_INT_MAX)); } bool jsvIsNameIntInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT; } bool jsvIsNameIntBool(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL; } /// What happens when we access a variable that doesn't exist. We get a NAME where the next + previous siblings point to the object that may one day contain them bool jsvIsNewChild(const JsVar *v) { return jsvIsName(v) && jsvGetNextSibling(v) && jsvGetNextSibling(v)==jsvGetPrevSibling(v); } /// Are var.varData.ref.* (excl pad) used for data (so we expect them not to be empty) bool jsvIsRefUsedForData(const JsVar *v) { return jsvIsStringExt(v) || (jsvIsString(v)&&!jsvIsName(v)) || jsvIsFloat(v) || jsvIsNativeFunction(v) || jsvIsArrayBuffer(v) || jsvIsArrayBufferName(v); } /// Can the given variable be converted into an integer without loss of precision bool jsvIsIntegerish(const JsVar *v) { return jsvIsInt(v) || jsvIsPin(v) || jsvIsBoolean(v) || jsvIsNull(v); } bool jsvIsIterable(const JsVar *v) { return jsvIsArray(v) || jsvIsObject(v) || jsvIsFunction(v) || jsvIsString(v) || jsvIsArrayBuffer(v); } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- /** Return a pointer - UNSAFE for null refs. * This is effectively a Lock without locking! */ static ALWAYS_INLINE JsVar *jsvGetAddressOf(JsVarRef ref) { assert(ref); #ifdef RESIZABLE_JSVARS JsVarRef t = ref-1; return &jsVarBlocks[t>>JSVAR_BLOCK_SHIFT][t&(JSVAR_BLOCK_SIZE-1)]; #else return &jsVars[ref-1]; #endif } JsVar *_jsvGetAddressOf(JsVarRef ref) { return jsvGetAddressOf(ref); } #ifdef JSVARREF_PACKED_BITS #define JSVARREF_PACKED_BIT_MASK ((1U<<JSVARREF_PACKED_BITS)-1) JsVarRef jsvGetFirstChild(const JsVar *v) { return (JsVarRef)(v->varData.ref.firstChild | (((v->varData.ref.pack)&JSVARREF_PACKED_BIT_MASK))<<8); } JsVarRefSigned jsvGetFirstChildSigned(const JsVar *v) { JsVarRefSigned r = (JsVarRefSigned)jsvGetFirstChild(v); if (r & (1<<(JSVARREF_PACKED_BITS+7))) r -= 1<<(JSVARREF_PACKED_BITS+8); return r; } JsVarRef jsvGetNextSibling(const JsVar *v) { return (JsVarRef)(v->varData.ref.nextSibling | (((v->varData.ref.pack >> (JSVARREF_PACKED_BITS*2))&JSVARREF_PACKED_BIT_MASK))<<8); } JsVarRef jsvGetPrevSibling(const JsVar *v) { return (JsVarRef)(v->varData.ref.prevSibling | (((v->varData.ref.pack >> (JSVARREF_PACKED_BITS*3))&JSVARREF_PACKED_BIT_MASK))<<8); } void jsvSetFirstChild(JsVar *v, JsVarRef r) { v->varData.ref.firstChild = (unsigned char)(r & 0xFF); v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~JSVARREF_PACKED_BIT_MASK) | ((r >> 8) & JSVARREF_PACKED_BIT_MASK)); } void jsvSetNextSibling(JsVar *v, JsVarRef r) { v->varData.ref.nextSibling = (unsigned char)(r & 0xFF); v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~(JSVARREF_PACKED_BIT_MASK<<(JSVARREF_PACKED_BITS*2))) | (((r >> 8) & JSVARREF_PACKED_BIT_MASK) << (JSVARREF_PACKED_BITS*2))); } void jsvSetPrevSibling(JsVar *v, JsVarRef r) { v->varData.ref.prevSibling = (unsigned char)(r & 0xFF); v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~(JSVARREF_PACKED_BIT_MASK<<(JSVARREF_PACKED_BITS*3))) | (((r >> 8) & JSVARREF_PACKED_BIT_MASK) << (JSVARREF_PACKED_BITS*3))); } /* lastchild stores the upper 2 bits in JsVarFlags because then STRING_EXT can use one more character! */ JsVarRef jsvGetLastChild(const JsVar *v) { return (JsVarRef)(v->varData.ref.lastChild | (((v->flags >> JSV_LASTCHILD_BIT_SHIFT)&JSVARREF_PACKED_BIT_MASK))<<8); } void jsvSetLastChild(JsVar *v, JsVarRef r) { v->varData.ref.lastChild = (unsigned char)(r & 0xFF); v->flags = (v->flags & ~JSV_LASTCHILD_BIT_MASK) | ((r >> 8) << JSV_LASTCHILD_BIT_SHIFT); } #endif // For debugging/testing ONLY - maximum # of vars we are allowed to use void jsvSetMaxVarsUsed(unsigned int size) { #ifdef RESIZABLE_JSVARS assert(size < JSVAR_BLOCK_SIZE); // remember - this is only for DEBUGGING - as such it doesn't use multiple blocks #else assert(size < JSVAR_CACHE_SIZE); #endif jsVarsSize = size; } // maps the empty variables in... void jsvCreateEmptyVarList() { assert(!isMemoryBusy); isMemoryBusy = MEMBUSY_SYSTEM; jsVarFirstEmpty = 0; JsVar firstVar; // temporary var to simplify code in the loop below jsvSetNextSibling(&firstVar, 0); JsVar *lastEmpty = &firstVar; JsVarRef i; for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) { jsvSetNextSibling(lastEmpty, i); lastEmpty = var; } else if (jsvIsFlatString(var)) { // skip over used blocks for flat strings i = (JsVarRef)(i+jsvGetFlatStringBlocks(var)); } } jsvSetNextSibling(lastEmpty, 0); jsVarFirstEmpty = jsvGetNextSibling(&firstVar); isMemoryBusy = MEM_NOT_BUSY; } /* Removes the empty variable counter, cleaving clear runs of 0s where no data resides. This helps if compressing the variables for storage. */ void jsvClearEmptyVarList() { assert(!isMemoryBusy); isMemoryBusy = MEMBUSY_SYSTEM; jsVarFirstEmpty = 0; JsVarRef i; for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) { // completely zero it (JSV_UNUSED==0, so it still stays the same) memset((void*)var,0,sizeof(JsVar)); } else if (jsvIsFlatString(var)) { // skip over used blocks for flat strings i = (JsVarRef)(i+jsvGetFlatStringBlocks(var)); } } isMemoryBusy = MEM_NOT_BUSY; } void jsvSoftInit() { jsvCreateEmptyVarList(); } void jsvSoftKill() { jsvClearEmptyVarList(); } /** This links all JsVars together, so we can have our nice * linked list of free JsVars. It returns the ref of the first * item - that we should set jsVarFirstEmpty to (if it is 0) */ static JsVarRef jsvInitJsVars(JsVarRef start, unsigned int count) { JsVarRef i; for (i=start;i<start+count;i++) { JsVar *v = jsvGetAddressOf(i); v->flags = JSV_UNUSED; // v->locks = 0; // locks is 0 anyway because it is stored in flags jsvSetNextSibling(v, (JsVarRef)(i+1)); // link to next } jsvSetNextSibling(jsvGetAddressOf((JsVarRef)(start+count-1)), (JsVarRef)0); // set the final one to 0 return start; } void jsvInit() { #ifdef RESIZABLE_JSVARS jsVarsSize = JSVAR_BLOCK_SIZE; jsVarBlocks = malloc(sizeof(JsVar*)); // just 1 jsVarBlocks[0] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE); #endif jsVarFirstEmpty = jsvInitJsVars(1/*first*/, jsVarsSize); jsvSoftInit(); } void jsvKill() { #ifdef RESIZABLE_JSVARS unsigned int i; for (i=0;i<jsVarsSize>>JSVAR_BLOCK_SHIFT;i++) free(jsVarBlocks[i]); free(jsVarBlocks); jsVarBlocks = 0; jsVarsSize = 0; #endif } /** Find or create the ROOT variable item - used mainly * if recovering from a saved state. */ JsVar *jsvFindOrCreateRoot() { JsVarRef i; for (i=1;i<=jsVarsSize;i++) if (jsvIsRoot(jsvGetAddressOf(i))) return jsvLock(i); return jsvRef(jsvNewWithFlags(JSV_ROOT)); } /// Get number of memory records (JsVars) used unsigned int jsvGetMemoryUsage() { unsigned int usage = 0; unsigned int i; for (i=1;i<=jsVarsSize;i++) { JsVar *v = jsvGetAddressOf((JsVarRef)i); if ((v->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { usage++; if (jsvIsFlatString(v)) { unsigned int b = (unsigned int)jsvGetFlatStringBlocks(v); i+=b; usage+=b; } } } return usage; } /// Get total amount of memory records unsigned int jsvGetMemoryTotal() { return jsVarsSize; } /// Try and allocate more memory - only works if RESIZABLE_JSVARS is defined void jsvSetMemoryTotal(unsigned int jsNewVarCount) { #ifdef RESIZABLE_JSVARS assert(!isMemoryBusy); if (jsNewVarCount <= jsVarsSize) return; // never allow us to have less! isMemoryBusy = MEMBUSY_SYSTEM; // When resizing, we just allocate a bunch more unsigned int oldSize = jsVarsSize; unsigned int oldBlockCount = jsVarsSize >> JSVAR_BLOCK_SHIFT; unsigned int newBlockCount = (jsNewVarCount+JSVAR_BLOCK_SIZE-1) >> JSVAR_BLOCK_SHIFT; jsVarsSize = newBlockCount << JSVAR_BLOCK_SHIFT; // resize block table jsVarBlocks = realloc(jsVarBlocks, sizeof(JsVar*)*newBlockCount); // allocate more blocks unsigned int i; for (i=oldBlockCount;i<newBlockCount;i++) jsVarBlocks[i] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE); /** and now reset all the newly allocated vars. We know jsVarFirstEmpty * is 0 (because jsiFreeMoreMemory returned 0) so we can just assign it. */ assert(!jsVarFirstEmpty); jsVarFirstEmpty = jsvInitJsVars(oldSize+1, jsVarsSize-oldSize); // jsiConsolePrintf("Resized memory from %d blocks to %d\n", oldBlockCount, newBlockCount); touchedFreeList = true; isMemoryBusy = MEM_NOT_BUSY; #else NOT_USED(jsNewVarCount); assert(0); #endif } bool jsvMoreFreeVariablesThan(unsigned int vars) { if (!vars) return false; JsVarRef r = jsVarFirstEmpty; while (r) { if (!vars--) return true; r = jsvGetNextSibling(jsvGetAddressOf(r)); } return false; } /// Get whether memory is full or not bool jsvIsMemoryFull() { return !jsVarFirstEmpty; } // Show what is still allocated, for debugging memory problems void jsvShowAllocated() { JsVarRef i; for (i=1;i<=jsVarsSize;i++) { if ((jsvGetAddressOf(i)->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { jsiConsolePrintf("USED VAR #%d:",i); jsvTrace(jsvGetAddressOf(i), 2); } } } bool jsvHasCharacterData(const JsVar *v) { return jsvIsString(v) || jsvIsStringExt(v); } bool jsvHasStringExt(const JsVar *v) { return jsvIsString(v) || jsvIsStringExt(v); } bool jsvHasChildren(const JsVar *v) { return jsvIsFunction(v) || jsvIsObject(v) || jsvIsArray(v) || jsvIsRoot(v); } /// Is this variable a type that uses firstChild to point to a single Variable (ie. it doesn't have multiple children) bool jsvHasSingleChild(const JsVar *v) { return jsvIsArrayBuffer(v) || (jsvIsName(v) && !jsvIsNameWithValue(v)); } /** Return the is the number of characters this one JsVar can contain, NOT string length (eg, a chain of JsVars) * This will return an invalid length when applied to Flat Strings */ size_t jsvGetMaxCharactersInVar(const JsVar *v) { // see jsvCopy - we need to know about this in there too if (jsvIsStringExt(v)) return JSVAR_DATA_STRING_MAX_LEN; assert(jsvHasCharacterData(v)); if (jsvIsName(v)) return JSVAR_DATA_STRING_NAME_LEN; return JSVAR_DATA_STRING_LEN; } /// This is the number of characters a JsVar can contain, NOT string length size_t jsvGetCharactersInVar(const JsVar *v) { unsigned int f = v->flags&JSV_VARTYPEMASK; if (f == JSV_FLAT_STRING) return (size_t)v->varData.integer; if (f == JSV_NATIVE_STRING) return (size_t)v->varData.nativeStr.len; assert(f >= JSV_NAME_STRING_INT_0); assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) && (JSV_NAME_STRING_0 < JSV_STRING_0) && (JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering if (f<=JSV_NAME_STRING_MAX) { if (f<=JSV_NAME_STRING_INT_MAX) return f-JSV_NAME_STRING_INT_0; else return f-JSV_NAME_STRING_0; } else { if (f<=JSV_STRING_MAX) return f-JSV_STRING_0; assert(f <= JSV_STRING_EXT_MAX); return f - JSV_STRING_EXT_0; } } /// This is the number of characters a JsVar can contain, NOT string length void jsvSetCharactersInVar(JsVar *v, size_t chars) { unsigned int f = v->flags&JSV_VARTYPEMASK; assert(!(jsvIsFlatString(v) || jsvIsNativeString(v))); JsVarFlags m = (JsVarFlags)(v->flags&~JSV_VARTYPEMASK); assert(f >= JSV_NAME_STRING_INT_0); assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) && (JSV_NAME_STRING_0 < JSV_STRING_0) && (JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering if (f<=JSV_NAME_STRING_MAX) { assert(chars <= JSVAR_DATA_STRING_NAME_LEN); if (f<=JSV_NAME_STRING_INT_MAX) v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_INT_0+chars)); else v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_0+chars)); } else { if (f<=JSV_STRING_MAX) { assert(chars <= JSVAR_DATA_STRING_LEN); v->flags = (JsVarFlags)(m | (JSV_STRING_0+chars)); } else { assert(chars <= JSVAR_DATA_STRING_MAX_LEN); assert(f <= JSV_STRING_EXT_MAX); v->flags = (JsVarFlags)(m | (JSV_STRING_EXT_0+chars)); } } } void jsvResetVariable(JsVar *v, JsVarFlags flags) { assert((v->flags&JSV_VARTYPEMASK) == JSV_UNUSED); // make sure we clear all data... /* Force a proper zeroing of all data. We don't use * memset because that'd create a function call. This * should just generate a bunch of STR instructions */ unsigned int i; assert((sizeof(JsVar)&3) == 0); // must be a multiple of 4 in size for (i=0;i<sizeof(JsVar)/sizeof(uint32_t);i++) ((uint32_t*)v)[i] = 0; // set flags assert(!(flags & JSV_LOCK_MASK)); v->flags = flags | JSV_LOCK_ONE; } JsVar *jsvNewWithFlags(JsVarFlags flags) { if (isMemoryBusy) { jsErrorFlags |= JSERR_MEMORY_BUSY; return 0; } JsVar *v = 0; jshInterruptOff(); // to allow this to be used from an IRQ if (jsVarFirstEmpty!=0) { v = jsvGetAddressOf(jsVarFirstEmpty); // jsvResetVariable will lock jsVarFirstEmpty = jsvGetNextSibling(v); // move our reference to the next in the fr touchedFreeList = true; } jshInterruptOn(); if (v) { assert(v->flags == JSV_UNUSED); // Cope with IRQs/multi-threading when getting a new free variable /* JsVarRef empty; JsVarRef next; JsVar *v; do { empty = jsVarFirstEmpty; v = jsvGetAddressOf(empty); // jsvResetVariable will lock next = jsvGetNextSibling(v); // move our reference to the next in the free list touchedFreeList = true; } while (!__sync_bool_compare_and_swap(&jsVarFirstEmpty, empty, next)); assert(v->flags == JSV_UNUSED);*/ jsvResetVariable(v, flags); // setup variable, and add one lock // return pointer return v; } jsErrorFlags |= JSERR_LOW_MEMORY; /* If we're calling from an IRQ, do NOT try and do fancy * stuff to free memory */ if (jshIsInInterrupt()) { return 0; } /* we don't have memory - second last hope - run garbage collector */ if (jsvGarbageCollect()) { return jsvNewWithFlags(flags); // if it freed something, continue } /* we don't have memory - last hope - ask jsInteractive to try and free some it may have kicking around */ if (jsiFreeMoreMemory()) { return jsvNewWithFlags(flags); } /* We couldn't claim any more memory by Garbage collecting... */ #ifdef RESIZABLE_JSVARS jsvSetMemoryTotal(jsVarsSize*2); return jsvNewWithFlags(flags); #else // On a micro, we're screwed. jsErrorFlags |= JSERR_MEMORY; jspSetInterrupted(true); return 0; #endif } static NO_INLINE void jsvFreePtrInternal(JsVar *var) { assert(jsvGetLocks(var)==0); var->flags = JSV_UNUSED; // add this to our free list jshInterruptOff(); // to allow this to be used from an IRQ jsvSetNextSibling(var, jsVarFirstEmpty); jsVarFirstEmpty = jsvGetRef(var); touchedFreeList = true; jshInterruptOn(); } ALWAYS_INLINE void jsvFreePtr(JsVar *var) { /* To be here, we're not supposed to be part of anything else. If * we were, we'd have been freed by jsvGarbageCollect */ assert((!jsvGetNextSibling(var) && !jsvGetPrevSibling(var)) || // check that next/prevSibling are not set jsvIsRefUsedForData(var) || // UNLESS we're part of a string and nextSibling/prevSibling are used for string data (jsvIsName(var) && (jsvGetNextSibling(var)==jsvGetPrevSibling(var)))); // UNLESS we're signalling that we're jsvIsNewChild // Names that Link to other things if (jsvIsNameWithValue(var)) { #ifdef CLEAR_MEMORY_ON_FREE jsvSetFirstChild(var, 0); // it just contained random data - zero it #endif // CLEAR_MEMORY_ON_FREE } else if (jsvHasSingleChild(var)) { if (jsvGetFirstChild(var)) { JsVar *child = jsvLock(jsvGetFirstChild(var)); jsvUnRef(child); #ifdef CLEAR_MEMORY_ON_FREE jsvSetFirstChild(var, 0); // unlink the child #endif // CLEAR_MEMORY_ON_FREE jsvUnLock(child); // unlock should trigger a free } } /* No else, because a String Name may have a single child, but * also StringExts */ /* Now, free children - see jsvar.h comments for how! */ if (jsvHasStringExt(var)) { // Free the string without recursing JsVarRef stringDataRef = jsvGetLastChild(var); #ifdef CLEAR_MEMORY_ON_FREE jsvSetLastChild(var, 0); #endif // CLEAR_MEMORY_ON_FREE while (stringDataRef) { JsVar *child = jsvGetAddressOf(stringDataRef); assert(jsvIsStringExt(child)); stringDataRef = jsvGetLastChild(child); jsvFreePtrInternal(child); } // We might be a flat string if (jsvIsFlatString(var)) { // in which case we need to free all the blocks. size_t count = jsvGetFlatStringBlocks(var); JsVarRef i = (JsVarRef)(jsvGetRef(var)+count); // do it in reverse, so the free list ends up in kind of the right order while (count--) { JsVar *p = jsvGetAddressOf(i--); p->flags = JSV_UNUSED; // set locks to 0 so the assert in jsvFreePtrInternal doesn't get fed up jsvFreePtrInternal(p); } } else if (jsvIsBasicString(var)) { #ifdef CLEAR_MEMORY_ON_FREE jsvSetFirstChild(var, 0); // firstchild could have had string data in #endif // CLEAR_MEMORY_ON_FREE } } /* NO ELSE HERE - because jsvIsNewChild stuff can be for Names, which can be ints or strings */ if (jsvHasChildren(var)) { JsVarRef childref = jsvGetFirstChild(var); #ifdef CLEAR_MEMORY_ON_FREE jsvSetFirstChild(var, 0); jsvSetLastChild(var, 0); #endif // CLEAR_MEMORY_ON_FREE while (childref) { JsVar *child = jsvLock(childref); assert(jsvIsName(child)); childref = jsvGetNextSibling(child); jsvSetPrevSibling(child, 0); jsvSetNextSibling(child, 0); jsvUnRef(child); jsvUnLock(child); } } else { #ifdef CLEAR_MEMORY_ON_FREE #if JSVARREF_SIZE==1 assert(jsvIsFloat(var) || !jsvGetFirstChild(var)); assert(jsvIsFloat(var) || !jsvGetLastChild(var)); #else assert(!jsvGetFirstChild(var)); // strings use firstchild now as well assert(!jsvGetLastChild(var)); #endif #endif // CLEAR_MEMORY_ON_FREE if (jsvIsName(var)) { assert(jsvGetNextSibling(var)==jsvGetPrevSibling(var)); // the case for jsvIsNewChild if (jsvGetNextSibling(var)) { jsvUnRefRef(jsvGetNextSibling(var)); jsvUnRefRef(jsvGetPrevSibling(var)); } } } // free! jsvFreePtrInternal(var); } /// Get a reference from a var - SAFE for null vars ALWAYS_INLINE JsVarRef jsvGetRef(JsVar *var) { if (!var) return 0; #ifdef RESIZABLE_JSVARS unsigned int i, c = jsVarsSize>>JSVAR_BLOCK_SHIFT; for (i=0;i<c;i++) { if (var>=jsVarBlocks[i] && var<&jsVarBlocks[i][JSVAR_BLOCK_SIZE]) { JsVarRef r = (JsVarRef)(1 + (i<<JSVAR_BLOCK_SHIFT) + (var - jsVarBlocks[i])); return r; } } return 0; #else return (JsVarRef)(1 + (var - jsVars)); #endif } /// Lock this reference and return a pointer - UNSAFE for null refs ALWAYS_INLINE JsVar *jsvLock(JsVarRef ref) { JsVar *var = jsvGetAddressOf(ref); //var->locks++; assert(jsvGetLocks(var) < JSV_LOCK_MAX); var->flags += JSV_LOCK_ONE; #ifdef DEBUG if (jsvGetLocks(var)==0) { jsError("Too many locks to Variable!"); //jsPrint("Var #");jsPrintInt(ref);jsPrint("\n"); } #endif return var; } /// Lock this pointer and return a pointer - UNSAFE for null pointer ALWAYS_INLINE JsVar *jsvLockAgain(JsVar *var) { assert(var); assert(jsvGetLocks(var) < JSV_LOCK_MAX); var->flags += JSV_LOCK_ONE; return var; } /// Lock this pointer and return a pointer - UNSAFE for null pointer ALWAYS_INLINE JsVar *jsvLockAgainSafe(JsVar *var) { return var ? jsvLockAgain(var) : 0; } // CALL ONLY FROM jsvUnlock // jsvGetLocks(var) must == 0 static NO_INLINE void jsvUnLockFreeIfNeeded(JsVar *var) { assert(jsvGetLocks(var) == 0); /* if we know we're free, then we can just free this variable right now. * Loops of variables are handled by the Garbage Collector. * Note: we checked locks already in jsvUnLock as it is fastest to check */ if (jsvGetRefs(var) == 0 && jsvHasRef(var) && (var->flags&JSV_VARTYPEMASK)!=JSV_UNUSED) { // we might be in an IRQ now, with GC in the main thread. If so, don't free! jsvFreePtr(var); } } /// Unlock this variable - this is SAFE for null variables ALWAYS_INLINE void jsvUnLock(JsVar *var) { if (!var) return; assert(jsvGetLocks(var)>0); var->flags -= JSV_LOCK_ONE; // Now see if we can properly free the data // Note: we check locks first as they are already in a register if ((var->flags & JSV_LOCK_MASK) == 0) jsvUnLockFreeIfNeeded(var); } /// Unlock 2 variables in one go void jsvUnLock2(JsVar *var1, JsVar *var2) { jsvUnLock(var1); jsvUnLock(var2); } /// Unlock 3 variables in one go void jsvUnLock3(JsVar *var1, JsVar *var2, JsVar *var3) { jsvUnLock(var1); jsvUnLock(var2); jsvUnLock(var3); } /// Unlock 4 variables in one go void jsvUnLock4(JsVar *var1, JsVar *var2, JsVar *var3, JsVar *var4) { jsvUnLock(var1); jsvUnLock(var2); jsvUnLock(var3); jsvUnLock(var4); } /// Unlock an array of variables NO_INLINE void jsvUnLockMany(unsigned int count, JsVar **vars) { while (count) jsvUnLock(vars[--count]); } /// Reference - set this variable as used by something JsVar *jsvRef(JsVar *var) { assert(var && jsvHasRef(var)); jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)+1)); assert(jsvGetRefs(var)); return var; } /// Unreference - set this variable as not used by anything void jsvUnRef(JsVar *var) { assert(var && jsvGetRefs(var)>0 && jsvHasRef(var)); jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)-1)); } /// Helper fn, Reference - set this variable as used by something JsVarRef jsvRefRef(JsVarRef ref) { JsVar *v; assert(ref); v = jsvLock(ref); assert(!jsvIsStringExt(v)); jsvRef(v); jsvUnLock(v); return ref; } /// Helper fn, Unreference - set this variable as not used by anything JsVarRef jsvUnRefRef(JsVarRef ref) { JsVar *v; assert(ref); v = jsvLock(ref); assert(!jsvIsStringExt(v)); jsvUnRef(v); jsvUnLock(v); return 0; } JsVar *jsvNewFlatStringOfLength(unsigned int byteLength) { if (isMemoryBusy) { jsErrorFlags |= JSERR_MEMORY_BUSY; return 0; } // Work out how many blocks we need. One for the header, plus some for the characters size_t requiredBlocks = 1 + ((byteLength+sizeof(JsVar)-1) / sizeof(JsVar)); JsVar *flatString = 0; /* Now try and find a contiguous set of 'requiredBlocks' blocks by searching the free list. This can be done as long as nobody's messed with the free list in the mean time (which we check for with touchedFreeList). If someone has messed with it, we restart.*/ bool memoryTouched = true; while (memoryTouched) { memoryTouched = false; touchedFreeList = false; JsVarRef beforeStartBlock = 0; JsVarRef curr = jsVarFirstEmpty; JsVarRef startBlock = curr; unsigned int blockCount = 1; while (curr && !touchedFreeList) { JsVar *currVar = jsvGetAddressOf(curr); JsVarRef next = jsvGetNextSibling(currVar); #ifdef RESIZABLE_JSVARS if (next && jsvGetAddressOf(next)==currVar+1) { #else if (next == curr+1) { #endif blockCount++; if (blockCount>=requiredBlocks) { JsVar *nextVar = jsvGetAddressOf(next); JsVarRef nextFree = jsvGetNextSibling(nextVar); jshInterruptOff(); if (!touchedFreeList) { // we're there! Quickly re-link free list if (beforeStartBlock) { jsvSetNextSibling(jsvGetAddressOf(beforeStartBlock),nextFree); } else { jsVarFirstEmpty = nextFree; } flatString = jsvGetAddressOf(startBlock); // Set up the header block (including one lock) jsvResetVariable(flatString, JSV_FLAT_STRING); flatString->varData.integer = (JsVarInt)byteLength; } jshInterruptOn(); // if success, break out! if (flatString) break; } } else { // this block is not immediately after the last - restart run blockCount = 1; beforeStartBlock = curr; startBlock = next; } // move to next! curr = next; } // memory list has been touched - restart! if (touchedFreeList) { memoryTouched = true; } } /* Nope... we couldn't find a free string. It could be because * the free list is fragmented, so GCing might well fix it - which * we'll try. */ if (!flatString) { if (jsvGarbageCollect()) return jsvNewFlatStringOfLength(byteLength); return 0; } /* We now have the string! All that's left is to clear it, * which we can do outside of an IRQ */ // clear data memset((char*)&flatString[1], 0, sizeof(JsVar)*(requiredBlocks-1)); /* We did mess with the free list - set it here in case we are trying to create a flat string in an IRQ while trying to make one outside the IRQ too */ touchedFreeList = true; // and we're done return flatString; } JsVar *jsvNewFromString(const char *str) { // Create a var JsVar *first = jsvNewWithFlags(JSV_STRING_0); if (!first) return 0; // out of memory // Now we copy the string, but keep creating new jsVars if we go // over the end JsVar *var = jsvLockAgain(first); while (*str) { // copy data in size_t i, l = jsvGetMaxCharactersInVar(var); for (i=0;i<l && *str;i++) var->varData.str[i] = *(str++); // we already set the variable data to 0, so no need for adding one // we've stopped if the string was empty jsvSetCharactersInVar(var, i); // if there is still some left, it's because we filled up our var... // make a new one, link it in, and unlock the old one. if (*str) { JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0); if (!next) { // Truncating string as not enough memory jsvUnLock(var); return first; } // we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner) jsvSetLastChild(var, jsvGetRef(next)); jsvUnLock(var); var = next; } } jsvUnLock(var); // return return first; } JsVar *jsvNewStringOfLength(unsigned int byteLength, const char *initialData) { // if string large enough, try and make a flat string instead if (byteLength > JSV_FLAT_STRING_BREAK_EVEN) { JsVar *v = jsvNewFlatStringOfLength(byteLength); if (v) { if (initialData) jsvSetString(v, initialData, byteLength); return v; } } // Create a var JsVar *first = jsvNewWithFlags(JSV_STRING_0); if (!first) return 0; // out of memory, will have already set flag // Now keep creating enough new jsVars JsVar *var = jsvLockAgain(first); while (true) { // copy data in unsigned int l = (unsigned int)jsvGetMaxCharactersInVar(var); if (l>=byteLength) { if (initialData) memcpy(var->varData.str, initialData, byteLength); // we've got enough jsvSetCharactersInVar(var, byteLength); break; } else { if (initialData) { memcpy(var->varData.str, initialData, l); initialData+=l; } // We need more jsvSetCharactersInVar(var, l); byteLength -= l; // Make a new one, link it in, and unlock the old one. JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0); if (!next) break; // out of memory, will have already set flag // we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner) jsvSetLastChild(var, jsvGetRef(next)); jsvUnLock(var); var = next; } } jsvUnLock(var); // return return first; } JsVar *jsvNewFromInteger(JsVarInt value) { JsVar *var = jsvNewWithFlags(JSV_INTEGER); if (!var) return 0; // no memory var->varData.integer = value; return var; } JsVar *jsvNewFromBool(bool value) { JsVar *var = jsvNewWithFlags(JSV_BOOLEAN); if (!var) return 0; // no memory var->varData.integer = value ? 1 : 0; return var; } JsVar *jsvNewFromFloat(JsVarFloat value) { JsVar *var = jsvNewWithFlags(JSV_FLOAT); if (!var) return 0; // no memory var->varData.floating = value; return var; } JsVar *jsvNewFromLongInteger(long long value) { if (value>=-2147483648LL && value<=2147483647LL) return jsvNewFromInteger((JsVarInt)value); else return jsvNewFromFloat((JsVarFloat)value); } JsVar *jsvMakeIntoVariableName(JsVar *var, JsVar *valueOrZero) { if (!var) return 0; assert(jsvGetRefs(var)==0); // make sure it's unused assert(jsvIsSimpleInt(var) || jsvIsString(var)); JsVarFlags varType = (var->flags & JSV_VARTYPEMASK); if (varType==JSV_INTEGER) { int t = JSV_NAME_INT; if ((jsvIsInt(valueOrZero) || jsvIsBoolean(valueOrZero)) && !jsvIsPin(valueOrZero)) { JsVarInt v = valueOrZero->varData.integer; if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { t = jsvIsInt(valueOrZero) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL; jsvSetFirstChild(var, (JsVarRef)v); valueOrZero = 0; } } var->flags = (JsVarFlags)(var->flags & ~JSV_VARTYPEMASK) | t; } else if (varType>=_JSV_STRING_START && varType<=_JSV_STRING_END) { if (jsvGetCharactersInVar(var) > JSVAR_DATA_STRING_NAME_LEN) { /* Argh. String is too large to fit in a JSV_NAME! We must chomp make * new STRINGEXTs to put the data in */ JsvStringIterator it; jsvStringIteratorNew(&it, var, JSVAR_DATA_STRING_NAME_LEN); JsVar *startExt = jsvNewWithFlags(JSV_STRING_EXT_0); JsVar *ext = jsvLockAgainSafe(startExt); size_t nChars = 0; while (ext && jsvStringIteratorHasChar(&it)) { if (nChars >= JSVAR_DATA_STRING_MAX_LEN) { jsvSetCharactersInVar(ext, nChars); JsVar *ext2 = jsvNewWithFlags(JSV_STRING_EXT_0); if (ext2) { jsvSetLastChild(ext, jsvGetRef(ext2)); } jsvUnLock(ext); ext = ext2; nChars = 0; } ext->varData.str[nChars++] = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); if (ext) { jsvSetCharactersInVar(ext, nChars); jsvUnLock(ext); } jsvSetCharactersInVar(var, JSVAR_DATA_STRING_NAME_LEN); // Free any old stringexts JsVarRef oldRef = jsvGetLastChild(var); while (oldRef) { JsVar *v = jsvGetAddressOf(oldRef); oldRef = jsvGetLastChild(v); jsvFreePtrInternal(v); } // set up new stringexts jsvSetLastChild(var, jsvGetRef(startExt)); jsvSetNextSibling(var, 0); jsvSetPrevSibling(var, 0); jsvSetFirstChild(var, 0); jsvUnLock(startExt); } size_t t = JSV_NAME_STRING_0; if (jsvIsInt(valueOrZero) && !jsvIsPin(valueOrZero)) { JsVarInt v = valueOrZero->varData.integer; if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { t = JSV_NAME_STRING_INT_0; jsvSetFirstChild(var, (JsVarRef)v); valueOrZero = 0; } } else jsvSetFirstChild(var, 0); var->flags = (var->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (t+jsvGetCharactersInVar(var)); } else assert(0); if (valueOrZero) jsvSetFirstChild(var, jsvGetRef(jsvRef(valueOrZero))); return var; } void jsvMakeFunctionParameter(JsVar *v) { assert(jsvIsString(v)); if (!jsvIsName(v)) jsvMakeIntoVariableName(v,0); v->flags = (JsVarFlags)(v->flags | JSV_NATIVE); } JsVar *jsvNewFromPin(int pin) { JsVar *v = jsvNewFromInteger((JsVarInt)pin); if (v) { v->flags = (JsVarFlags)((v->flags & ~JSV_VARTYPEMASK) | JSV_PIN); } return v; } JsVar *jsvNewObject() { return jsvNewWithFlags(JSV_OBJECT); } JsVar *jsvNewEmptyArray() { return jsvNewWithFlags(JSV_ARRAY); } /// Create an array containing the given elements JsVar *jsvNewArray(JsVar **elements, int elementCount) { JsVar *arr = jsvNewEmptyArray(); if (!arr) return 0; int i; for (i=0;i<elementCount;i++) jsvArrayPush(arr, elements[i]); return arr; } JsVar *jsvNewNativeFunction(void (*ptr)(void), unsigned short argTypes) { JsVar *func = jsvNewWithFlags(JSV_FUNCTION | JSV_NATIVE); if (!func) return 0; func->varData.native.ptr = ptr; func->varData.native.argTypes = argTypes; return func; } JsVar *jsvNewNativeString(char *ptr, size_t len) { if (len>JSV_NATIVE_STR_MAX_LENGTH) len=JSV_NATIVE_STR_MAX_LENGTH; // crop string to what we can store in nativeStr.len JsVar *str = jsvNewWithFlags(JSV_NATIVE_STRING); if (!str) return 0; str->varData.nativeStr.ptr = ptr; str->varData.nativeStr.len = (uint16_t)len; return str; } void *jsvGetNativeFunctionPtr(const JsVar *function) { /* see descriptions in jsvar.h. If we have a child called JSPARSE_FUNCTION_CODE_NAME * then we execute code straight from that */ JsVar *flatString = jsvFindChildFromString((JsVar*)function, JSPARSE_FUNCTION_CODE_NAME, 0); if (flatString) { flatString = jsvSkipNameAndUnLock(flatString); void *v = (void*)((size_t)function->varData.native.ptr + (char*)jsvGetFlatStringPointer(flatString)); jsvUnLock(flatString); return v; } else return (void *)function->varData.native.ptr; } /// Create a new ArrayBuffer backed by the given string. If length is not specified, it will be worked out JsVar *jsvNewArrayBufferFromString(JsVar *str, unsigned int lengthOrZero) { JsVar *arr = jsvNewWithFlags(JSV_ARRAYBUFFER); if (!arr) return 0; jsvSetFirstChild(arr, jsvGetRef(jsvRef(str))); arr->varData.arraybuffer.type = ARRAYBUFFERVIEW_ARRAYBUFFER; assert(arr->varData.arraybuffer.byteOffset == 0); if (lengthOrZero==0) lengthOrZero = (unsigned int)jsvGetStringLength(str); arr->varData.arraybuffer.length = (unsigned short)lengthOrZero; return arr; } bool jsvIsBasicVarEqual(JsVar *a, JsVar *b) { // quick checks if (a==b) return true; if (!a || !b) return false; // one of them is undefined // OPT: would this be useful as compare instead? assert(jsvIsBasic(a) && jsvIsBasic(b)); if (jsvIsNumeric(a) && jsvIsNumeric(b)) { if (jsvIsIntegerish(a)) { if (jsvIsIntegerish(b)) { return a->varData.integer == b->varData.integer; } else { assert(jsvIsFloat(b)); return a->varData.integer == b->varData.floating; } } else { assert(jsvIsFloat(a)); if (jsvIsIntegerish(b)) { return a->varData.floating == b->varData.integer; } else { assert(jsvIsFloat(b)); return a->varData.floating == b->varData.floating; } } } else if (jsvIsString(a) && jsvIsString(b)) { JsvStringIterator ita, itb; jsvStringIteratorNew(&ita, a, 0); jsvStringIteratorNew(&itb, b, 0); while (true) { char a = jsvStringIteratorGetChar(&ita); char b = jsvStringIteratorGetChar(&itb); if (a != b) { jsvStringIteratorFree(&ita); jsvStringIteratorFree(&itb); return false; } if (!a) { // equal, but end of string jsvStringIteratorFree(&ita); jsvStringIteratorFree(&itb); return true; } jsvStringIteratorNext(&ita); jsvStringIteratorNext(&itb); } // we never get here return false; // make compiler happy } else { //TODO: are there any other combinations we should check here?? String v int? return false; } } bool jsvIsEqual(JsVar *a, JsVar *b) { if (jsvIsBasic(a) && jsvIsBasic(b)) return jsvIsBasicVarEqual(a,b); return jsvGetRef(a)==jsvGetRef(b); } /// Get a const string representing this variable - if we can. Otherwise return 0 const char *jsvGetConstString(const JsVar *v) { if (jsvIsUndefined(v)) { return "undefined"; } else if (jsvIsNull(v)) { return "null"; } else if (jsvIsBoolean(v)) { return jsvGetBool(v) ? "true" : "false"; } return 0; } /// Return the 'type' of the JS variable (eg. JS's typeof operator) const char *jsvGetTypeOf(const JsVar *v) { if (jsvIsUndefined(v)) return "undefined"; if (jsvIsNull(v) || jsvIsObject(v) || jsvIsArray(v) || jsvIsArrayBuffer(v)) return "object"; if (jsvIsFunction(v)) return "function"; if (jsvIsString(v)) return "string"; if (jsvIsBoolean(v)) return "boolean"; if (jsvIsNumeric(v)) return "number"; return "?"; } /// Return the JsVar, or if it's an object and has a valueOf function, call that JsVar *jsvGetValueOf(JsVar *v) { if (!jsvIsObject(v)) return jsvLockAgainSafe(v); JsVar *valueOf = jspGetNamedField(v, "valueOf", false); if (!jsvIsFunction(valueOf)) { jsvUnLock(valueOf); return jsvLockAgain(v); } v = jspeFunctionCall(valueOf, 0, v, false, 0, 0); jsvUnLock(valueOf); return v; } /** Save this var as a string to the given buffer, and return how long it was (return val doesn't include terminating 0) If the buffer length is exceeded, the returned value will == len */ size_t jsvGetString(const JsVar *v, char *str, size_t len) { assert(len>0); const char *s = jsvGetConstString(v); if (s) { /* don't use strncpy here because we don't * want to pad the entire buffer with zeros */ len--; int l = 0; while (s[l] && l<len) { str[l] = s[l]; l++; } str[l] = 0; return l; } else if (jsvIsInt(v)) { itostr(v->varData.integer, str, 10); return strlen(str); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, str, len); return strlen(str); } else if (jsvHasCharacterData(v)) { assert(!jsvIsStringExt(v)); size_t l = len; JsvStringIterator it; jsvStringIteratorNewConst(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (l--<=1) { *str = 0; jsvStringIteratorFree(&it); return len; } *(str++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); *str = 0; return len-l; } else { // Try and get as a JsVar string, and try again JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here if (stringVar) { size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var jsvUnLock(stringVar); return l; } else { str[0] = 0; jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); return 0; } } } /// Get len bytes of string data from this string. Does not error if string len is not equal to len size_t jsvGetStringChars(const JsVar *v, size_t startChar, char *str, size_t len) { assert(jsvHasCharacterData(v)); size_t l = len; JsvStringIterator it; jsvStringIteratorNewConst(&it, v, startChar); while (jsvStringIteratorHasChar(&it)) { if (l--<=0) { jsvStringIteratorFree(&it); return len; } *(str++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); *str = 0; return len-l; } /// Set the Data in this string. This must JUST overwrite - not extend or shrink void jsvSetString(JsVar *v, const char *str, size_t len) { assert(jsvHasCharacterData(v)); // the iterator checks, so it is safe not to assert if the length is different //assert(len == jsvGetStringLength(v)); JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); size_t i; for (i=0;i<len;i++) { jsvStringIteratorSetChar(&it, str[i]); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); } /** If var is a string, lock and return it, else * create a new string. unlockVar means this will auto-unlock 'var' */ JsVar *jsvAsString(JsVar *v, bool unlockVar) { JsVar *str = 0; // If it is string-ish, but not quite a string, copy it if (jsvHasCharacterData(v) && jsvIsName(v)) { str = jsvNewFromStringVar(v,0,JSVAPPENDSTRINGVAR_MAXLENGTH); } else if (jsvIsString(v)) { // If it is a string - just return a reference str = jsvLockAgain(v); } else if (jsvIsObject(v)) { // If it is an object and we can call toString on it JsVar *toStringFn = jspGetNamedField(v, "toString", false); if (toStringFn && toStringFn->varData.native.ptr != (void (*)(void))jswrap_object_toString) { // Function found and it's not the default one - execute it JsVar *result = jspExecuteFunction(toStringFn,v,0,0); jsvUnLock(toStringFn); str = jsvAsString(result, true); } else { jsvUnLock(toStringFn); str = jsvNewFromString("[object Object]"); } } else { const char *constChar = jsvGetConstString(v); assert(JS_NUMBER_BUFFER_SIZE>=10); char buf[JS_NUMBER_BUFFER_SIZE]; if (constChar) { // if we could get this as a simple const char, do that.. str = jsvNewFromString(constChar); } else if (jsvIsPin(v)) { jshGetPinString(buf, (Pin)v->varData.integer); str = jsvNewFromString(buf); } else if (jsvIsInt(v)) { itostr(v->varData.integer, buf, 10); str = jsvNewFromString(buf); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, buf, sizeof(buf)); str = jsvNewFromString(buf); } else if (jsvIsArray(v) || jsvIsArrayBuffer(v)) { JsVar *filler = jsvNewFromString(","); str = jsvArrayJoin(v, filler); jsvUnLock(filler); } else if (jsvIsFunction(v)) { str = jsvNewFromEmptyString(); if (str) jsfGetJSON(v, str, JSON_NONE); } else { jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); str = 0; } } if (unlockVar) jsvUnLock(v); return str; } JsVar *jsvAsFlatString(JsVar *var) { if (jsvIsFlatString(var)) return jsvLockAgain(var); JsVar *str = jsvAsString(var, false); size_t len = jsvGetStringLength(str); JsVar *flat = jsvNewFlatStringOfLength((unsigned int)len); if (flat) { JsvStringIterator src; JsvStringIterator dst; jsvStringIteratorNew(&src, str, 0); jsvStringIteratorNew(&dst, flat, 0); while (len--) { jsvStringIteratorSetChar(&dst, jsvStringIteratorGetChar(&src)); if (len>0) { jsvStringIteratorNext(&src); jsvStringIteratorNext(&dst); } } jsvStringIteratorFree(&src); jsvStringIteratorFree(&dst); } jsvUnLock(str); return flat; } /** Given a JsVar meant to be an index to an array, convert it to * the actual variable type we'll use to access the array. For example * a["0"] is actually translated to a[0] */ JsVar *jsvAsArrayIndex(JsVar *index) { if (jsvIsSimpleInt(index)) { return jsvLockAgain(index); // we're ok! } else if (jsvIsString(index)) { /* Index filtering (bug #19) - if we have an array index A that is: is_string(A) && int_to_string(string_to_int(A)) == A then convert it to an integer. Shouldn't be too nasty for performance as we only do this when accessing an array with a string */ if (jsvIsStringNumericStrict(index)) { JsVar *i = jsvNewFromInteger(jsvGetInteger(index)); JsVar *is = jsvAsString(i, false); if (jsvCompareString(index,is,0,0,false)==0) { // two items are identical - use the integer jsvUnLock(is); return i; } else { // not identical, use as a string jsvUnLock2(i,is); } } } else if (jsvIsFloat(index)) { // if it's a float that is actually integral, return an integer... JsVarFloat v = jsvGetFloat(index); JsVarInt vi = jsvGetInteger(index); if (v == vi) return jsvNewFromInteger(vi); } // else if it's not a simple numeric type, convert it to a string return jsvAsString(index, false); } /** Same as jsvAsArrayIndex, but ensures that 'index' is unlocked */ JsVar *jsvAsArrayIndexAndUnLock(JsVar *a) { JsVar *b = jsvAsArrayIndex(a); jsvUnLock(a); return b; } /// Returns true if the string is empty - faster than jsvGetStringLength(v)==0 bool jsvIsEmptyString(JsVar *v) { if (!jsvHasCharacterData(v)) return true; return jsvGetCharactersInVar(v)==0; } size_t jsvGetStringLength(const JsVar *v) { size_t strLength = 0; const JsVar *var = v; JsVar *newVar = 0; if (!jsvHasCharacterData(v)) return 0; while (var) { JsVarRef ref = jsvGetLastChild(var); strLength += jsvGetCharactersInVar(var); // Go to next jsvUnLock(newVar); // note use of if (ref), not var var = newVar = ref ? jsvLock(ref) : 0; } jsvUnLock(newVar); // note use of if (ref), not var return strLength; } size_t jsvGetFlatStringBlocks(const JsVar *v) { assert(jsvIsFlatString(v)); return ((size_t)v->varData.integer+sizeof(JsVar)-1) / sizeof(JsVar); } char *jsvGetFlatStringPointer(JsVar *v) { assert(jsvIsFlatString(v)); if (!jsvIsFlatString(v)) return 0; return (char*)(v+1); // pointer to the next JsVar } JsVar *jsvGetFlatStringFromPointer(char *v) { JsVar *secondVar = (JsVar*)v; JsVar *flatStr = secondVar-1; assert(jsvIsFlatString(flatStr)); return flatStr; } /// If the variable points to a *flat* area of memory, return a pointer (and set length). Otherwise return 0. char *jsvGetDataPointer(JsVar *v, size_t *len) { assert(len); if (jsvIsArrayBuffer(v)) { /* Arraybuffers generally use some kind of string to store their data. * Find it, then call ourselves again to figure out if we can get a * raw pointer to it. */ JsVar *d = jsvGetArrayBufferBackingString(v); char *r = jsvGetDataPointer(d, len); jsvUnLock(d); if (r) { r += v->varData.arraybuffer.byteOffset; *len = v->varData.arraybuffer.length; } return r; } if (jsvIsNativeString(v)) { *len = v->varData.nativeStr.len; return (char*)v->varData.nativeStr.ptr; } if (jsvIsFlatString(v)) { *len = jsvGetStringLength(v); return jsvGetFlatStringPointer(v); } return 0; } // IN A STRING get the number of lines in the string (min=1) size_t jsvGetLinesInString(JsVar *v) { size_t lines = 1; JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (jsvStringIteratorGetChar(&it)=='\n') lines++; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return lines; } // IN A STRING Get the number of characters on a line - lines start at 1 size_t jsvGetCharsOnLine(JsVar *v, size_t line) { size_t currentLine = 1; size_t chars = 0; JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (jsvStringIteratorGetChar(&it)=='\n') { currentLine++; if (currentLine > line) break; } else if (currentLine==line) chars++; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return chars; } // IN A STRING, get the 1-based line and column of the given character. Both values must be non-null void jsvGetLineAndCol(JsVar *v, size_t charIdx, size_t *line, size_t *col) { size_t x = 1; size_t y = 1; size_t n = 0; assert(line && col); JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { char ch = jsvStringIteratorGetChar(&it); if (n==charIdx) { jsvStringIteratorFree(&it); *line = y; *col = x; return; } x++; if (ch=='\n') { x=1; y++; } n++; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); // uh-oh - not found *line = y; *col = x; } // IN A STRING, get a character index from a line and column size_t jsvGetIndexFromLineAndCol(JsVar *v, size_t line, size_t col) { size_t x = 1; size_t y = 1; size_t n = 0; JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { char ch = jsvStringIteratorGetChar(&it); if ((y==line && x>=col) || y>line) { jsvStringIteratorFree(&it); return (y>line) ? (n-1) : n; } x++; if (ch=='\n') { x=1; y++; } n++; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return n; } void jsvAppendString(JsVar *var, const char *str) { assert(jsvIsString(var)); JsvStringIterator dst; jsvStringIteratorNew(&dst, var, 0); jsvStringIteratorGotoEnd(&dst); // now start appending /* This isn't as fast as something single-purpose, but it's not that bad, * and is less likely to break :) */ while (*str) jsvStringIteratorAppend(&dst, *(str++)); jsvStringIteratorFree(&dst); } // Append the given string to this one - but does not use null-terminated strings void jsvAppendStringBuf(JsVar *var, const char *str, size_t length) { assert(jsvIsString(var)); JsvStringIterator dst; jsvStringIteratorNew(&dst, var, 0); jsvStringIteratorGotoEnd(&dst); // now start appending /* This isn't as fast as something single-purpose, but it's not that bad, * and is less likely to break :) */ while (length) { jsvStringIteratorAppend(&dst, *(str++)); length--; } jsvStringIteratorFree(&dst); } /// Special version of append designed for use with vcbprintf_callback (See jsvAppendPrintf) void jsvStringIteratorPrintfCallback(const char *str, void *user_data) { while (*str) jsvStringIteratorAppend((JsvStringIterator *)user_data, *(str++)); } void jsvAppendPrintf(JsVar *var, const char *fmt, ...) { JsvStringIterator it; jsvStringIteratorNew(&it, var, 0); jsvStringIteratorGotoEnd(&it); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); } JsVar *jsvVarPrintf( const char *fmt, ...) { JsVar *str = jsvNewFromEmptyString(); if (!str) return 0; JsvStringIterator it; jsvStringIteratorNew(&it, str, 0); jsvStringIteratorGotoEnd(&it); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); return str; } /** Append str to var. Both must be strings. stridx = start char or str, maxLength = max number of characters (can be JSVAPPENDSTRINGVAR_MAXLENGTH) */ void jsvAppendStringVar(JsVar *var, const JsVar *str, size_t stridx, size_t maxLength) { assert(jsvIsString(var)); JsvStringIterator dst; jsvStringIteratorNew(&dst, var, 0); jsvStringIteratorGotoEnd(&dst); // now start appending /* This isn't as fast as something single-purpose, but it's not that bad, * and is less likely to break :) */ JsvStringIterator it; jsvStringIteratorNewConst(&it, str, stridx); while (jsvStringIteratorHasChar(&it) && (maxLength-->0)) { char ch = jsvStringIteratorGetChar(&it); jsvStringIteratorAppend(&dst, ch); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); jsvStringIteratorFree(&dst); } /** Create a new variable from a substring. argument must be a string. stridx = start char or str, maxLength = max number of characters (can be JSVAPPENDSTRINGVAR_MAXLENGTH) */ JsVar *jsvNewFromStringVar(const JsVar *str, size_t stridx, size_t maxLength) { JsVar *var = jsvNewFromEmptyString(); if (var) jsvAppendStringVar(var, str, stridx, maxLength); return var; } /** Append all of str to var. Both must be strings. */ void jsvAppendStringVarComplete(JsVar *var, const JsVar *str) { jsvAppendStringVar(var, str, 0, JSVAPPENDSTRINGVAR_MAXLENGTH); } char jsvGetCharInString(JsVar *v, size_t idx) { if (!jsvIsString(v)) return 0; JsvStringIterator it; jsvStringIteratorNew(&it, v, idx); char ch = jsvStringIteratorGetChar(&it); jsvStringIteratorFree(&it); return ch; } /// Get the index of a character in a string, or -1 int jsvGetStringIndexOf(JsVar *str, char ch) { JsvStringIterator it; jsvStringIteratorNew(&it, str, 0); while (jsvStringIteratorHasChar(&it)) { if (jsvStringIteratorGetChar(&it) == ch) { int idx = (int)jsvStringIteratorGetIndex(&it); jsvStringIteratorFree(&it); return idx; }; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return -1; } /** Does this string contain only Numeric characters (with optional '-'/'+' at the front)? NOT '.'/'e' and similar (allowDecimalPoint is for '.' only) */ bool jsvIsStringNumericInt(const JsVar *var, bool allowDecimalPoint) { assert(jsvIsString(var)); JsvStringIterator it; jsvStringIteratorNewConst(&it, var, 0); // we know it's non const // skip whitespace while (jsvStringIteratorHasChar(&it) && isWhitespace(jsvStringIteratorGetChar(&it))) jsvStringIteratorNext(&it); // skip a minus. if there was one if (jsvStringIteratorGetChar(&it)=='-' || jsvStringIteratorGetChar(&it)=='+') jsvStringIteratorNext(&it); int radix = 0; if (jsvStringIteratorGetChar(&it)=='0') { jsvStringIteratorNext(&it); char buf[3]; buf[0] = '0'; buf[1] = jsvStringIteratorGetChar(&it); buf[2] = 0; const char *p = buf; radix = getRadix(&p,0,0); if (p>&buf[1]) jsvStringIteratorNext(&it); } if (radix==0) radix=10; // now check... int chars=0; while (jsvStringIteratorHasChar(&it)) { chars++; char ch = jsvStringIteratorGetChar(&it); if (ch=='.' && allowDecimalPoint) { allowDecimalPoint = false; // there can be only one } else { int n = chtod(ch); if (n<0 || n>=radix) { jsvStringIteratorFree(&it); return false; } } jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return chars>0; } /** Does this string contain only Numeric characters? This is for arrays * and makes the assertion that int_to_string(string_to_int(var))==var */ bool jsvIsStringNumericStrict(const JsVar *var) { assert(jsvIsString(var)); JsvStringIterator it; jsvStringIteratorNewConst(&it, var, 0); // we know it's non const bool hadNonZero = false; bool hasLeadingZero = false; int chars = 0; while (jsvStringIteratorHasChar(&it)) { chars++; char ch = jsvStringIteratorGetChar(&it); if (!isNumeric(ch)) { // test for leading zero ensures int_to_string(string_to_int(var))==var jsvStringIteratorFree(&it); return false; } if (!hadNonZero && ch=='0') hasLeadingZero=true; if (ch!='0') hadNonZero=true; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return chars>0 && (!hasLeadingZero || chars==1); } JsVarInt jsvGetInteger(const JsVar *v) { if (!v) return 0; // undefined /* strtol understands about hex and octal */ if (jsvIsNull(v)) return 0; if (jsvIsUndefined(v)) return 0; if (jsvIsIntegerish(v) || jsvIsArrayBufferName(v)) return v->varData.integer; if (jsvIsArray(v) || jsvIsArrayBuffer(v)) { JsVarInt l = jsvGetLength((JsVar *)v); if (l==0) return 0; // 0 length, return 0 if (l==1) { if (jsvIsArrayBuffer(v)) return jsvGetIntegerAndUnLock(jsvArrayBufferGet((JsVar*)v,0)); return jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jsvGetArrayItem(v,0))); } } if (jsvIsFloat(v)) { if (isfinite(v->varData.floating)) return (JsVarInt)(long long)v->varData.floating; return 0; } if (jsvIsString(v) && jsvIsStringNumericInt(v, true/* allow decimal point*/)) { char buf[32]; if (jsvGetString(v, buf, sizeof(buf))==sizeof(buf)) jsExceptionHere(JSET_ERROR, "String too big to convert to integer\n"); else return (JsVarInt)stringToInt(buf); } return 0; } long long jsvGetLongInteger(const JsVar *v) { if (jsvIsInt(v)) return jsvGetInteger(v); return (long long)jsvGetFloat(v); } long long jsvGetLongIntegerAndUnLock(JsVar *v) { long long i = jsvGetLongInteger(v); jsvUnLock(v); return i; } void jsvSetInteger(JsVar *v, JsVarInt value) { assert(jsvIsInt(v)); v->varData.integer = value; } /** * Get the boolean value of a variable. * From a JavaScript variable, we determine its boolean value. The rules * are: * * * If integer, true if value is not 0. * * If float, true if value is not 0.0. * * If function, array or object, always true. * * If string, true if length of string is greater than 0. */ bool jsvGetBool(const JsVar *v) { if (jsvIsString(v)) return jsvGetStringLength((JsVar*)v)!=0; if (jsvIsFunction(v) || jsvIsArray(v) || jsvIsObject(v) || jsvIsArrayBuffer(v)) return true; if (jsvIsFloat(v)) { JsVarFloat f = jsvGetFloat(v); return !isnan(f) && f!=0.0; } return jsvGetInteger(v)!=0; } JsVarFloat jsvGetFloat(const JsVar *v) { if (!v) return NAN; // undefined if (jsvIsFloat(v)) return v->varData.floating; if (jsvIsIntegerish(v)) return (JsVarFloat)v->varData.integer; if (jsvIsArray(v) || jsvIsArrayBuffer(v)) { JsVarInt l = jsvGetLength(v); if (l==0) return 0; // zero element array==0 (not undefined) if (l==1) { if (jsvIsArrayBuffer(v)) return jsvGetFloatAndUnLock(jsvArrayBufferGet((JsVar*)v,0)); return jsvGetFloatAndUnLock(jsvSkipNameAndUnLock(jsvGetArrayItem(v,0))); } } if (jsvIsString(v)) { char buf[64]; if (jsvGetString(v, buf, sizeof(buf))==sizeof(buf)) { jsExceptionHere(JSET_ERROR, "String too big to convert to float\n"); } else { if (buf[0]==0) return 0; // empty string -> 0 if (!strcmp(buf,"Infinity")) return INFINITY; if (!strcmp(buf,"-Infinity")) return -INFINITY; return stringToFloat(buf); } } return NAN; } /// Convert the given variable to a number JsVar *jsvAsNumber(JsVar *var) { // stuff that we can just keep if (jsvIsInt(var) || jsvIsFloat(var)) return jsvLockAgain(var); // stuff that can be converted to an int if (jsvIsBoolean(var) || jsvIsPin(var) || jsvIsNull(var) || jsvIsBoolean(var) || jsvIsArrayBufferName(var)) return jsvNewFromInteger(jsvGetInteger(var)); if (jsvIsString(var) && (jsvIsEmptyString(var) || jsvIsStringNumericInt(var, false/* no decimal pt - handle that with GetFloat */))) { // handle strings like this, in case they're too big for an int char buf[64]; if (jsvGetString(var, buf, sizeof(buf))==sizeof(buf)) { jsExceptionHere(JSET_ERROR, "String too big to convert to integer\n"); return jsvNewFromFloat(NAN); } else return jsvNewFromLongInteger(stringToInt(buf)); } // Else just try and get a float return jsvNewFromFloat(jsvGetFloat(var)); } JsVarInt jsvGetIntegerAndUnLock(JsVar *v) { return _jsvGetIntegerAndUnLock(v); } JsVarFloat jsvGetFloatAndUnLock(JsVar *v) { return _jsvGetFloatAndUnLock(v); } bool jsvGetBoolAndUnLock(JsVar *v) { return _jsvGetBoolAndUnLock(v); } /** Get the item at the given location in the array buffer and return the result */ size_t jsvGetArrayBufferLength(const JsVar *arrayBuffer) { assert(jsvIsArrayBuffer(arrayBuffer)); return arrayBuffer->varData.arraybuffer.length; } /** Get the String the contains the data for this arrayBuffer */ JsVar *jsvGetArrayBufferBackingString(JsVar *arrayBuffer) { jsvLockAgain(arrayBuffer); while (jsvIsArrayBuffer(arrayBuffer)) { JsVar *s = jsvLock(jsvGetFirstChild(arrayBuffer)); jsvUnLock(arrayBuffer); arrayBuffer = s; } assert(jsvIsString(arrayBuffer)); return arrayBuffer; } /** Get the item at the given location in the array buffer and return the result */ JsVar *jsvArrayBufferGet(JsVar *arrayBuffer, size_t idx) { JsvArrayBufferIterator it; jsvArrayBufferIteratorNew(&it, arrayBuffer, idx); JsVar *v = jsvArrayBufferIteratorGetValue(&it); jsvArrayBufferIteratorFree(&it); return v; } /** Set the item at the given location in the array buffer */ void jsvArrayBufferSet(JsVar *arrayBuffer, size_t idx, JsVar *value) { JsvArrayBufferIterator it; jsvArrayBufferIteratorNew(&it, arrayBuffer, idx); jsvArrayBufferIteratorSetValue(&it, value); jsvArrayBufferIteratorFree(&it); } /** Given an integer name that points to an arraybuffer or an arraybufferview, evaluate it and return the result */ JsVar *jsvArrayBufferGetFromName(JsVar *name) { assert(jsvIsArrayBufferName(name)); size_t idx = (size_t)jsvGetInteger(name); JsVar *arrayBuffer = jsvLock(jsvGetFirstChild(name)); JsVar *value = jsvArrayBufferGet(arrayBuffer, idx); jsvUnLock(arrayBuffer); return value; } JsVar *jsvGetFunctionArgumentLength(JsVar *functionScope) { JsVar *args = jsvNewEmptyArray(); if (!args) return 0; // out of memory JsvObjectIterator it; jsvObjectIteratorNew(&it, functionScope); while (jsvObjectIteratorHasValue(&it)) { JsVar *idx = jsvObjectIteratorGetKey(&it); if (jsvIsFunctionParameter(idx)) { JsVar *val = jsvSkipOneName(idx); jsvArrayPushAndUnLock(args, val); } jsvUnLock(idx); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); return args; } /** Is this variable actually defined? eg, can we pass it into `jsvSkipName` * without getting a ReferenceError? This also returns false if the variable * if ok, but has the value `undefined`. */ bool jsvIsVariableDefined(JsVar *a) { return !jsvIsName(a) || jsvIsNameWithValue(a) || (jsvGetFirstChild(a)!=0); } /** If a is a name skip it and go to what it points to - and so on. * ALWAYS locks - so must unlock what it returns. It MAY * return 0. Throws a ReferenceError if variable is not defined, * but you can check if it will with jsvIsReferenceError */ JsVar *jsvSkipName(JsVar *a) { if (!a) return 0; if (jsvIsArrayBufferName(a)) return jsvArrayBufferGetFromName(a); if (jsvIsNameInt(a)) return jsvNewFromInteger((JsVarInt)jsvGetFirstChildSigned(a)); if (jsvIsNameIntBool(a)) return jsvNewFromBool(jsvGetFirstChild(a)!=0); JsVar *pa = jsvLockAgain(a); while (jsvIsName(pa)) { JsVarRef n = jsvGetFirstChild(pa); jsvUnLock(pa); if (!n) { if (pa==a && jsvGetRefs(a)==0 && !jsvIsNewChild(a)) { jsExceptionHere(JSET_REFERENCEERROR, "%q is not defined", a); } return 0; } pa = jsvLock(n); assert(pa!=a); } return pa; } /** If a is a name skip it and go to what it points to. * ALWAYS locks - so must unlock what it returns. It MAY * return 0. Throws a ReferenceError if variable is not defined, * but you can check if it will with jsvIsReferenceError */ JsVar *jsvSkipOneName(JsVar *a) { if (!a) return 0; if (jsvIsArrayBufferName(a)) return jsvArrayBufferGetFromName(a); if (jsvIsNameInt(a)) return jsvNewFromInteger((JsVarInt)jsvGetFirstChildSigned(a)); if (jsvIsNameIntBool(a)) return jsvNewFromBool(jsvGetFirstChild(a)!=0); JsVar *pa = jsvLockAgain(a); if (jsvIsName(pa)) { JsVarRef n = jsvGetFirstChild(pa); jsvUnLock(pa); if (!n) { if (pa==a && jsvGetRefs(a)==0 && !jsvIsNewChild(a)) { jsExceptionHere(JSET_REFERENCEERROR, "%q is not defined", a); } return 0; } pa = jsvLock(n); assert(pa!=a); } return pa; } /** If a is a's child is a name skip it and go to what it points to. * ALWAYS locks - so must unlock what it returns. */ JsVar *jsvSkipToLastName(JsVar *a) { assert(jsvIsName(a)); a = jsvLockAgain(a); while (true) { if (!jsvGetFirstChild(a)) return a; JsVar *child = jsvLock(jsvGetFirstChild(a)); if (jsvIsName(child)) { jsvUnLock(a); a = child; } else { jsvUnLock(child); return a; } } return 0; // not called } /** Same as jsvSkipName, but ensures that 'a' is unlocked */ JsVar *jsvSkipNameAndUnLock(JsVar *a) { JsVar *b = jsvSkipName(a); jsvUnLock(a); return b; } /** Same as jsvSkipOneName, but ensures that 'a' is unlocked */ JsVar *jsvSkipOneNameAndUnLock(JsVar *a) { JsVar *b = jsvSkipOneName(a); jsvUnLock(a); return b; } bool jsvIsStringEqualOrStartsWithOffset(JsVar *var, const char *str, bool isStartsWith, size_t startIdx, bool ignoreCase) { if (!jsvHasCharacterData(var)) { return 0; // not a string so not equal! } JsvStringIterator it; jsvStringIteratorNew(&it, var, startIdx); if (ignoreCase) { while (jsvStringIteratorHasChar(&it) && *str && jsvStringCharToLower(jsvStringIteratorGetChar(&it)) == jsvStringCharToLower(*str)) { str++; jsvStringIteratorNext(&it); } } else { while (jsvStringIteratorHasChar(&it) && *str && jsvStringIteratorGetChar(&it) == *str) { str++; jsvStringIteratorNext(&it); } } bool eq = (isStartsWith && !*str) || jsvStringIteratorGetChar(&it)==*str; // should both be 0 if equal jsvStringIteratorFree(&it); return eq; } /* jsvIsStringEqualOrStartsWith(A, B, false) is a proper A==B jsvIsStringEqualOrStartsWith(A, B, true) is A.startsWith(B) */ bool jsvIsStringEqualOrStartsWith(JsVar *var, const char *str, bool isStartsWith) { return jsvIsStringEqualOrStartsWithOffset(var, str, isStartsWith, 0, false); } // Also see jsvIsBasicVarEqual bool jsvIsStringEqual(JsVar *var, const char *str) { return jsvIsStringEqualOrStartsWith(var, str, false); } // Also see jsvIsBasicVarEqual bool jsvIsStringIEqualAndUnLock(JsVar *var, const char *str) { bool b = jsvIsStringEqualOrStartsWithOffset(var, str, false, 0, true); jsvUnLock(var); return b; } /** Compare 2 strings, starting from the given character positions. equalAtEndOfString means that * if one of the strings ends (even if the other hasn't), we treat them as equal. * For a basic strcmp, do: jsvCompareString(a,b,0,0,false) * */ int jsvCompareString(JsVar *va, JsVar *vb, size_t starta, size_t startb, bool equalAtEndOfString) { JsvStringIterator ita, itb; jsvStringIteratorNew(&ita, va, starta); jsvStringIteratorNew(&itb, vb, startb); // step to first positions while (true) { int ca = jsvStringIteratorGetCharOrMinusOne(&ita); int cb = jsvStringIteratorGetCharOrMinusOne(&itb); if (ca != cb) { jsvStringIteratorFree(&ita); jsvStringIteratorFree(&itb); if ((ca<0 || cb<0) && equalAtEndOfString) return 0; return ca - cb; } if (ca < 0) { // both equal, but end of string jsvStringIteratorFree(&ita); jsvStringIteratorFree(&itb); return 0; } jsvStringIteratorNext(&ita); jsvStringIteratorNext(&itb); } // never get here, but the compiler warns... return true; } /** Return a new string containing just the characters that are * shared between two strings. */ JsVar *jsvGetCommonCharacters(JsVar *va, JsVar *vb) { JsVar *v = jsvNewFromEmptyString(); if (!v) return 0; JsvStringIterator ita, itb; jsvStringIteratorNew(&ita, va, 0); jsvStringIteratorNew(&itb, vb, 0); int ca = jsvStringIteratorGetCharOrMinusOne(&ita); int cb = jsvStringIteratorGetCharOrMinusOne(&itb); while (ca>0 && cb>0 && ca == cb) { jsvAppendCharacter(v, (char)ca); jsvStringIteratorNext(&ita); jsvStringIteratorNext(&itb); ca = jsvStringIteratorGetCharOrMinusOne(&ita); cb = jsvStringIteratorGetCharOrMinusOne(&itb); } jsvStringIteratorFree(&ita); jsvStringIteratorFree(&itb); return v; } /** Compare 2 integers, >0 if va>vb, <0 if va<vb. If compared with a non-integer, that gets put later */ int jsvCompareInteger(JsVar *va, JsVar *vb) { if (jsvIsInt(va) && jsvIsInt(vb)) return (int)(jsvGetInteger(va) - jsvGetInteger(vb)); else if (jsvIsInt(va)) return -1; else if (jsvIsInt(vb)) return 1; else return 0; } /** Copy only a name, not what it points to. ALTHOUGH the link to what it points to is maintained unless linkChildren=false If keepAsName==false, this will be converted into a normal variable */ JsVar *jsvCopyNameOnly(JsVar *src, bool linkChildren, bool keepAsName) { assert(jsvIsName(src)); JsVarFlags flags = src->flags; JsVar *dst = 0; if (!keepAsName) { JsVarFlags t = src->flags & JSV_VARTYPEMASK; if (t>=_JSV_NAME_INT_START && t<=_JSV_NAME_INT_END) { flags = (flags & ~JSV_VARTYPEMASK) | JSV_INTEGER; } else { assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) && (JSV_NAME_STRING_0 < JSV_STRING_0) && (JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering assert(t>=JSV_NAME_STRING_INT_0 && t<=JSV_NAME_STRING_MAX); if (jsvGetLastChild(src)) { /* it's not a simple name string - it has STRING_EXT bits on the end. * Because the max length of NAME and STRING is different we must just * copy */ dst = jsvNewFromStringVar(src, 0, JSVAPPENDSTRINGVAR_MAXLENGTH); if (!dst) return 0; } else { flags = (flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_STRING_0 + jsvGetCharactersInVar(src)); } } } if (!dst) { dst = jsvNewWithFlags(flags & JSV_VARIABLEINFOMASK); if (!dst) return 0; // out of memory memcpy(&dst->varData, &src->varData, JSVAR_DATA_STRING_NAME_LEN); assert(jsvGetLastChild(dst) == 0); assert(jsvGetFirstChild(dst) == 0); assert(jsvGetPrevSibling(dst) == 0); assert(jsvGetNextSibling(dst) == 0); // Copy extra string data if there was any if (jsvHasStringExt(src)) { // If it had extra string data it should have been handled above assert(keepAsName || !jsvGetLastChild(src)); // copy extra bits of string if there were any if (jsvGetLastChild(src)) { JsVar *child = jsvLock(jsvGetLastChild(src)); JsVar *childCopy = jsvCopy(child, true); if (childCopy) { // could be out of memory jsvSetLastChild(dst, jsvGetRef(childCopy)); // no ref for stringext jsvUnLock(childCopy); } jsvUnLock(child); } } else { assert(jsvIsBasic(src)); // in case we missed something! } } // Copy LINK of what it points to if (linkChildren && jsvGetFirstChild(src)) { if (jsvIsNameWithValue(src)) jsvSetFirstChild(dst, jsvGetFirstChild(src)); else jsvSetFirstChild(dst, jsvRefRef(jsvGetFirstChild(src))); } return dst; } JsVar *jsvCopy(JsVar *src, bool copyChildren) { if (jsvIsFlatString(src)) { // Copy a Flat String into a non-flat string - it's just safer return jsvNewFromStringVar(src, 0, JSVAPPENDSTRINGVAR_MAXLENGTH); } JsVar *dst = jsvNewWithFlags(src->flags & JSV_VARIABLEINFOMASK); if (!dst) return 0; // out of memory if (!jsvIsStringExt(src)) { memcpy(&dst->varData, &src->varData, (jsvIsBasicString(src)||jsvIsNativeString(src)) ? JSVAR_DATA_STRING_LEN : JSVAR_DATA_STRING_NAME_LEN); if (!(jsvIsBasicString(src)||jsvIsNativeString(src))) { assert(jsvGetPrevSibling(dst) == 0); assert(jsvGetNextSibling(dst) == 0); assert(jsvGetFirstChild(dst) == 0); } assert(jsvGetLastChild(dst) == 0); } else { // stringexts use the extra pointers after varData to store characters // see jsvGetMaxCharactersInVar memcpy(&dst->varData, &src->varData, JSVAR_DATA_STRING_MAX_LEN); assert(jsvGetLastChild(dst) == 0); } // Copy what names point to if (copyChildren && jsvIsName(src)) { if (jsvGetFirstChild(src)) { if (jsvIsNameWithValue(src)) { // name_int/etc don't need references jsvSetFirstChild(dst, jsvGetFirstChild(src)); } else { JsVar *child = jsvLock(jsvGetFirstChild(src)); JsVar *childCopy = jsvRef(jsvCopy(child, true)); jsvUnLock(child); if (childCopy) { // could have been out of memory jsvSetFirstChild(dst, jsvGetRef(childCopy)); jsvUnLock(childCopy); } } } } if (jsvHasStringExt(src)) { // copy extra bits of string if there were any if (jsvGetLastChild(src)) { JsVar *child = jsvLock(jsvGetLastChild(src)); JsVar *childCopy = jsvCopy(child, true); if (childCopy) {// could be out of memory jsvSetLastChild(dst, jsvGetRef(childCopy)); // no ref for stringext jsvUnLock(childCopy); } jsvUnLock(child); } } else if (jsvHasChildren(src)) { if (copyChildren) { // Copy children.. JsVarRef vr; vr = jsvGetFirstChild(src); while (vr) { JsVar *name = jsvLock(vr); JsVar *child = jsvCopyNameOnly(name, true/*link children*/, true/*keep as name*/); // NO DEEP COPY! if (child) { // could have been out of memory jsvAddName(dst, child); jsvUnLock(child); } vr = jsvGetNextSibling(name); jsvUnLock(name); } } } else { assert(jsvIsBasic(src)); // in case we missed something! } return dst; } void jsvAddName(JsVar *parent, JsVar *namedChild) { namedChild = jsvRef(namedChild); // ref here VERY important as adding to structure! assert(jsvIsName(namedChild)); // update array length if (jsvIsArray(parent) && jsvIsInt(namedChild)) { JsVarInt index = namedChild->varData.integer; if (index >= jsvGetArrayLength(parent)) { jsvSetArrayLength(parent, index + 1, false); } } if (jsvGetLastChild(parent)) { // we have children already JsVar *insertAfter = jsvLock(jsvGetLastChild(parent)); if (jsvIsArray(parent)) { // we must insert in order - so step back until we get the right place while (insertAfter && jsvCompareInteger(namedChild, insertAfter)<0) { JsVarRef prev = jsvGetPrevSibling(insertAfter); jsvUnLock(insertAfter); insertAfter = prev ? jsvLock(prev) : 0; } } if (insertAfter) { if (jsvGetNextSibling(insertAfter)) { // great, we're in the middle... JsVar *insertBefore = jsvLock(jsvGetNextSibling(insertAfter)); jsvSetPrevSibling(insertBefore, jsvGetRef(namedChild)); jsvSetNextSibling(namedChild, jsvGetRef(insertBefore)); jsvUnLock(insertBefore); } else { // We're at the end - just set up the parent jsvSetLastChild(parent, jsvGetRef(namedChild)); } jsvSetNextSibling(insertAfter, jsvGetRef(namedChild)); jsvSetPrevSibling(namedChild, jsvGetRef(insertAfter)); jsvUnLock(insertAfter); } else { // Insert right at the beginning of the array // Link 2 children together JsVar *firstChild = jsvLock(jsvGetFirstChild(parent)); jsvSetPrevSibling(firstChild, jsvGetRef(namedChild)); jsvUnLock(firstChild); jsvSetNextSibling(namedChild, jsvGetFirstChild(parent)); // finally set the new child as the first one jsvSetFirstChild(parent, jsvGetRef(namedChild)); } } else { // we have no children - just add it JsVarRef r = jsvGetRef(namedChild); jsvSetFirstChild(parent, r); jsvSetLastChild(parent, r); } } JsVar *jsvAddNamedChild(JsVar *parent, JsVar *child, const char *name) { JsVar *namedChild = jsvMakeIntoVariableName(jsvNewFromString(name), child); if (!namedChild) return 0; // Out of memory jsvAddName(parent, namedChild); return namedChild; } JsVar *jsvSetNamedChild(JsVar *parent, JsVar *child, const char *name) { JsVar *namedChild = jsvFindChildFromString(parent, name, true); if (namedChild) // could be out of memory return jsvSetValueOfName(namedChild, child); return 0; } JsVar *jsvSetValueOfName(JsVar *name, JsVar *src) { assert(name && jsvIsName(name)); assert(name!=src); // no infinite loops! // all is fine, so replace the existing child... /* Existing child may be null in the case of Z = 0 where * we create 'Z' and pass it down to '=' to have the value * filled in (or it may be undefined). */ if (jsvIsNameWithValue(name)) { if (jsvIsString(name)) name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_NAME_STRING_0 + jsvGetCharactersInVar(name)); else name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | JSV_NAME_INT; jsvSetFirstChild(name, 0); } else if (jsvGetFirstChild(name)) jsvUnRefRef(jsvGetFirstChild(name)); // free existing if (src) { if (jsvIsInt(name)) { if ((jsvIsInt(src) || jsvIsBoolean(src)) && !jsvIsPin(src)) { JsVarInt v = src->varData.integer; if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (jsvIsInt(src) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL); jsvSetFirstChild(name, (JsVarRef)v); return name; } } } else if (jsvIsString(name)) { if (jsvIsInt(src) && !jsvIsPin(src)) { JsVarInt v = src->varData.integer; if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_NAME_STRING_INT_0 + jsvGetCharactersInVar(name)); jsvSetFirstChild(name, (JsVarRef)v); return name; } } } // we can link to a name if we want (so can remove the assert!) jsvSetFirstChild(name, jsvGetRef(jsvRef(src))); } else jsvSetFirstChild(name, 0); return name; } JsVar *jsvFindChildFromString(JsVar *parent, const char *name, bool addIfNotFound) { /* Pull out first 4 bytes, and ensure that everything * is 0 padded so that we can do a nice speedy check. */ char fastCheck[4]; fastCheck[0] = name[0]; if (name[0]) { fastCheck[1] = name[1]; if (name[1]) { fastCheck[2] = name[2]; if (name[2]) { fastCheck[3] = name[3]; } else { fastCheck[3] = 0; } } else { fastCheck[2] = 0; fastCheck[3] = 0; } } else { fastCheck[1] = 0; fastCheck[2] = 0; fastCheck[3] = 0; } assert(jsvHasChildren(parent)); JsVarRef childref = jsvGetFirstChild(parent); while (childref) { // Don't Lock here, just use GetAddressOf - to try and speed up the finding // TODO: We can do this now, but when/if we move to cacheing vars, it'll break JsVar *child = jsvGetAddressOf(childref); if (*(int*)fastCheck==*(int*)child->varData.str && // speedy check of first 4 bytes jsvIsStringEqual(child, name)) { // found it! unlock parent but leave child locked return jsvLockAgain(child); } childref = jsvGetNextSibling(child); } JsVar *child = 0; if (addIfNotFound) { child = jsvMakeIntoVariableName(jsvNewFromString(name), 0); if (child) // could be out of memory jsvAddName(parent, child); } return child; } /// See jsvIsNewChild - for fields that don't exist yet JsVar *jsvCreateNewChild(JsVar *parent, JsVar *index, JsVar *child) { JsVar *newChild = jsvAsName(index); if (!newChild) return 0; assert(!jsvGetFirstChild(newChild)); if (child) jsvSetValueOfName(newChild, child); assert(!jsvGetNextSibling(newChild) && !jsvGetPrevSibling(newChild)); // by setting the siblings as the same, we signal that if set, // we should be made a member of the given object JsVarRef r = jsvGetRef(jsvRef(jsvRef(parent))); jsvSetNextSibling(newChild, r); jsvSetPrevSibling(newChild, r); return newChild; } /** Try and turn the supplied variable into a name. If not, make a new one. This locks again. */ JsVar *jsvAsName(JsVar *var) { if (!var) return 0; if (jsvGetRefs(var) == 0) { // Not reffed - great! let's just use it if (!jsvIsName(var)) var = jsvMakeIntoVariableName(var, 0); return jsvLockAgain(var); } else { // it was reffed, we must add a new one return jsvMakeIntoVariableName(jsvCopy(var, false), 0); } } /** Non-recursive finding */ JsVar *jsvFindChildFromVar(JsVar *parent, JsVar *childName, bool addIfNotFound) { JsVar *child; JsVarRef childref = jsvGetFirstChild(parent); while (childref) { child = jsvLock(childref); if (jsvIsBasicVarEqual(child, childName)) { // found it! unlock parent but leave child locked return child; } childref = jsvGetNextSibling(child); jsvUnLock(child); } child = 0; if (addIfNotFound && childName) { child = jsvAsName(childName); jsvAddName(parent, child); } return child; } void jsvRemoveChild(JsVar *parent, JsVar *child) { assert(jsvHasChildren(parent)); assert(jsvIsName(child)); JsVarRef childref = jsvGetRef(child); bool wasChild = false; // unlink from parent if (jsvGetFirstChild(parent) == childref) { jsvSetFirstChild(parent, jsvGetNextSibling(child)); wasChild = true; } if (jsvGetLastChild(parent) == childref) { jsvSetLastChild(parent, jsvGetPrevSibling(child)); wasChild = true; // If this was an array and we were the last // element, update the length if (jsvIsArray(parent)) { JsVarInt l = 0; // get index of last child if (jsvGetLastChild(parent)) l = jsvGetIntegerAndUnLock(jsvLock(jsvGetLastChild(parent)))+1; // set it jsvSetArrayLength(parent, l, false); } } // unlink from child list if (jsvGetPrevSibling(child)) { JsVar *v = jsvLock(jsvGetPrevSibling(child)); assert(jsvGetNextSibling(v) == jsvGetRef(child)); jsvSetNextSibling(v, jsvGetNextSibling(child)); jsvUnLock(v); wasChild = true; } if (jsvGetNextSibling(child)) { JsVar *v = jsvLock(jsvGetNextSibling(child)); assert(jsvGetPrevSibling(v) == jsvGetRef(child)); jsvSetPrevSibling(v, jsvGetPrevSibling(child)); jsvUnLock(v); wasChild = true; } jsvSetPrevSibling(child, 0); jsvSetNextSibling(child, 0); if (wasChild) jsvUnRef(child); } void jsvRemoveAllChildren(JsVar *parent) { assert(jsvHasChildren(parent)); while (jsvGetFirstChild(parent)) { JsVar *v = jsvLock(jsvGetFirstChild(parent)); jsvRemoveChild(parent, v); jsvUnLock(v); } } /// Check if the given name is a child of the parent bool jsvIsChild(JsVar *parent, JsVar *child) { assert(jsvIsArray(parent) || jsvIsObject(parent)); assert(jsvIsName(child)); JsVarRef childref = jsvGetRef(child); JsVarRef indexref; indexref = jsvGetFirstChild(parent); while (indexref) { if (indexref == childref) return true; // get next JsVar *indexVar = jsvLock(indexref); indexref = jsvGetNextSibling(indexVar); jsvUnLock(indexVar); } return false; // not found undefined } /// Get the named child of an object. If createChild!=0 then create the child JsVar *jsvObjectGetChild(JsVar *obj, const char *name, JsVarFlags createChild) { if (!obj) return 0; assert(jsvHasChildren(obj)); JsVar *childName = jsvFindChildFromString(obj, name, createChild!=0); JsVar *child = jsvSkipName(childName); if (!child && createChild && childName!=0/*out of memory?*/) { child = jsvNewWithFlags(createChild); jsvSetValueOfName(childName, child); jsvUnLock(childName); return child; } jsvUnLock(childName); return child; } /// Set the named child of an object, and return the child (so you can choose to unlock it if you want) JsVar *jsvObjectSetChild(JsVar *obj, const char *name, JsVar *child) { assert(jsvHasChildren(obj)); if (!jsvHasChildren(obj)) return 0; // child can actually be a name (for instance if it is a named function) JsVar *childName = jsvFindChildFromString(obj, name, true); if (!childName) return 0; // out of memory jsvSetValueOfName(childName, child); jsvUnLock(childName); return child; } /// Set the named child of an object, and return the child (so you can choose to unlock it if you want) JsVar *jsvObjectSetChildVar(JsVar *obj, JsVar *name, JsVar *child) { assert(jsvHasChildren(obj)); if (!jsvHasChildren(obj)) return 0; // child can actually be a name (for instance if it is a named function) JsVar *childName = jsvFindChildFromVar(obj, name, true); if (!childName) return 0; // out of memory jsvSetValueOfName(childName, child); jsvUnLock(childName); return child; } void jsvObjectSetChildAndUnLock(JsVar *obj, const char *name, JsVar *child) { jsvUnLock(jsvObjectSetChild(obj, name, child)); } void jsvObjectRemoveChild(JsVar *obj, const char *name) { JsVar *child = jsvFindChildFromString(obj, name, false); if (child) { jsvRemoveChild(obj, child); jsvUnLock(child); } } /** Set the named child of an object, and return the child (so you can choose to unlock it if you want). * If the child is 0, the 'name' is also removed from the object */ JsVar *jsvObjectSetOrRemoveChild(JsVar *obj, const char *name, JsVar *child) { if (child) jsvObjectSetChild(obj, name, child); else jsvObjectRemoveChild(obj, name); return child; } /** Append all keys from the source object to the target object. Will ignore hidden/internal fields */ void jsvObjectAppendAll(JsVar *target, JsVar *source) { assert(jsvIsObject(target)); assert(jsvIsObject(source)); JsvObjectIterator it; jsvObjectIteratorNew(&it, source); while (jsvObjectIteratorHasValue(&it)) { JsVar *k = jsvObjectIteratorGetKey(&it); JsVar *v = jsvSkipName(k); if (!jsvIsInternalObjectKey(k)) jsvObjectSetChildVar(target, k, v); jsvUnLock2(k,v); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); } int jsvGetChildren(const JsVar *v) { //OPT: could length be stored as the value of the array? int children = 0; JsVarRef childref = jsvGetFirstChild(v); while (childref) { JsVar *child = jsvLock(childref); children++; childref = jsvGetNextSibling(child); jsvUnLock(child); } return children; } /// Get the first child's name from an object,array or function JsVar *jsvGetFirstName(JsVar *v) { assert(jsvHasChildren(v)); if (!jsvGetFirstChild(v)) return 0; return jsvLock(jsvGetFirstChild(v)); } JsVarInt jsvGetArrayLength(const JsVar *arr) { if (!arr) return 0; assert(jsvIsArray(arr)); return arr->varData.integer; } JsVarInt jsvSetArrayLength(JsVar *arr, JsVarInt length, bool truncate) { assert(jsvIsArray(arr)); if (truncate && length < arr->varData.integer) { // @TODO implement truncation here } arr->varData.integer = length; return length; } JsVarInt jsvGetLength(const JsVar *src) { if (jsvIsArray(src)) { return jsvGetArrayLength(src); } else if (jsvIsArrayBuffer(src)) { return (JsVarInt)jsvGetArrayBufferLength(src); } else if (jsvIsString(src)) { return (JsVarInt)jsvGetStringLength(src); } else if (jsvIsObject(src) || jsvIsFunction(src)) { return jsvGetChildren(src); } else { return 1; } } /** Count the amount of JsVars used. Mostly useful for debugging */ static size_t _jsvCountJsVarsUsedRecursive(JsVar *v, bool resetRecursionFlag) { if (!v) return 0; // Use IS_RECURSING flag to stop recursion if (resetRecursionFlag) { if (!(v->flags & JSV_IS_RECURSING)) return 0; v->flags &= ~JSV_IS_RECURSING; } else { if (v->flags & JSV_IS_RECURSING) return 0; v->flags |= JSV_IS_RECURSING; } size_t count = 1; if (jsvHasSingleChild(v) || jsvHasChildren(v)) { JsVarRef childref = jsvGetFirstChild(v); while (childref) { JsVar *child = jsvLock(childref); count += _jsvCountJsVarsUsedRecursive(child, resetRecursionFlag); if (jsvHasChildren(v)) childref = jsvGetNextSibling(child); else childref = 0; jsvUnLock(child); } } else if (jsvIsFlatString(v)) count += jsvGetFlatStringBlocks(v); if (jsvHasCharacterData(v)) { JsVarRef childref = jsvGetLastChild(v); while (childref) { JsVar *child = jsvLock(childref); count++; childref = jsvGetLastChild(child); jsvUnLock(child); } } if (jsvIsName(v) && !jsvIsNameWithValue(v) && jsvGetFirstChild(v)) { JsVar *child = jsvLock(jsvGetFirstChild(v)); count += _jsvCountJsVarsUsedRecursive(child, resetRecursionFlag); jsvUnLock(child); } return count; } /** Count the amount of JsVars used. Mostly useful for debugging */ size_t jsvCountJsVarsUsed(JsVar *v) { // we do this so we don't count the same item twice, but don't use too much memory size_t c = _jsvCountJsVarsUsedRecursive(v, false); _jsvCountJsVarsUsedRecursive(v, true); return c; } JsVar *jsvGetArrayIndex(const JsVar *arr, JsVarInt index) { JsVarRef childref = jsvGetLastChild(arr); JsVarInt lastArrayIndex = 0; // Look at last non-string element! while (childref) { JsVar *child = jsvLock(childref); if (jsvIsInt(child)) { lastArrayIndex = child->varData.integer; // it was the last element... sorted! if (lastArrayIndex == index) { return child; } jsvUnLock(child); break; } // if not an int, keep going childref = jsvGetPrevSibling(child); jsvUnLock(child); } // it's not in this array - don't search the whole lot... if (index > lastArrayIndex) return 0; // otherwise is it more than halfway through? if (index > lastArrayIndex/2) { // it's in the final half of the array (probably) - search backwards while (childref) { JsVar *child = jsvLock(childref); assert(jsvIsInt(child)); if (child->varData.integer == index) { return child; } childref = jsvGetPrevSibling(child); jsvUnLock(child); } } else { // it's in the first half of the array (probably) - search forwards childref = jsvGetFirstChild(arr); while (childref) { JsVar *child = jsvLock(childref); assert(jsvIsInt(child)); if (child->varData.integer == index) { return child; } childref = jsvGetNextSibling(child); jsvUnLock(child); } } return 0; // undefined } JsVar *jsvGetArrayItem(const JsVar *arr, JsVarInt index) { return jsvSkipNameAndUnLock(jsvGetArrayIndex(arr,index)); } void jsvSetArrayItem(JsVar *arr, JsVarInt index, JsVar *item) { JsVar *indexVar = jsvGetArrayIndex(arr, index); if (indexVar) { jsvSetValueOfName(indexVar, item); } else { indexVar = jsvMakeIntoVariableName(jsvNewFromInteger(index), item); jsvAddName(arr, indexVar); } jsvUnLock(indexVar); } // Get all elements from arr and put them in itemPtr (unless it'd overflow). // Makes sure all of itemPtr either contains a JsVar or 0 void jsvGetArrayItems(JsVar *arr, unsigned int itemCount, JsVar **itemPtr) { JsvObjectIterator it; jsvObjectIteratorNew(&it, arr); unsigned int i = 0; while (jsvObjectIteratorHasValue(&it)) { if (i<itemCount) itemPtr[i++] = jsvObjectIteratorGetValue(&it); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); while (i<itemCount) itemPtr[i++] = 0; // just ensure we don't end up with bad data } /// Get the index of the value in the array (matchExact==use pointer not equality check, matchIntegerIndices = don't check non-integers) JsVar *jsvGetIndexOfFull(JsVar *arr, JsVar *value, bool matchExact, bool matchIntegerIndices, int startIdx) { JsVarRef indexref; assert(jsvIsArray(arr) || jsvIsObject(arr)); indexref = jsvGetFirstChild(arr); while (indexref) { JsVar *childIndex = jsvLock(indexref); if (!matchIntegerIndices || (jsvIsInt(childIndex) && jsvGetInteger(childIndex)>=startIdx)) { assert(jsvIsName(childIndex)); JsVar *childValue = jsvSkipName(childIndex); if (childValue==value || (!matchExact && jsvMathsOpTypeEqual(childValue, value))) { jsvUnLock(childValue); return childIndex; } jsvUnLock(childValue); } indexref = jsvGetNextSibling(childIndex); jsvUnLock(childIndex); } return 0; // undefined } /// Get the index of the value in the array or object (matchExact==use pointer, not equality check) JsVar *jsvGetIndexOf(JsVar *arr, JsVar *value, bool matchExact) { return jsvGetIndexOfFull(arr, value, matchExact, false, 0); } /// Adds new elements to the end of an array, and returns the new length. initialValue is the item index when no items are currently in the array. JsVarInt jsvArrayAddToEnd(JsVar *arr, JsVar *value, JsVarInt initialValue) { assert(jsvIsArray(arr)); JsVarInt index = initialValue; if (jsvGetLastChild(arr)) { JsVar *last = jsvLock(jsvGetLastChild(arr)); index = jsvGetInteger(last)+1; jsvUnLock(last); } JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(index), value); if (!idx) return 0; // out of memory - error flag will have been set already jsvAddName(arr, idx); jsvUnLock(idx); return index+1; } /// Adds new elements to the end of an array, and returns the new length JsVarInt jsvArrayPush(JsVar *arr, JsVar *value) { assert(jsvIsArray(arr)); JsVarInt index = jsvGetArrayLength(arr); JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(index), value); if (!idx) return 0; // out of memory - error flag will have been set already jsvAddName(arr, idx); jsvUnLock(idx); return jsvGetArrayLength(arr); } /// Adds a new element to the end of an array, unlocks it, and returns the new length JsVarInt jsvArrayPushAndUnLock(JsVar *arr, JsVar *value) { JsVarInt l = jsvArrayPush(arr, value); jsvUnLock(value); return l; } /// Append all values from the source array to the target array void jsvArrayPushAll(JsVar *target, JsVar *source, bool checkDuplicates) { assert(jsvIsArray(target)); assert(jsvIsArray(source)); JsvObjectIterator it; jsvObjectIteratorNew(&it, source); while (jsvObjectIteratorHasValue(&it)) { JsVar *v = jsvObjectIteratorGetValue(&it); bool add = true; if (checkDuplicates) { JsVar *idx = jsvGetIndexOf(target, v, false); if (idx) { add = false; jsvUnLock(idx); } } if (add) jsvArrayPush(target, v); jsvUnLock(v); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); } /// Removes the last element of an array, and returns that element (or 0 if empty). includes the NAME JsVar *jsvArrayPop(JsVar *arr) { assert(jsvIsArray(arr)); JsVar *child = 0; JsVarInt length = jsvGetArrayLength(arr); if (length > 0) { length--; if (jsvGetLastChild(arr)) { // find last child with an integer key JsVarRef ref = jsvGetLastChild(arr); child = jsvLock(ref); while (child && !jsvIsInt(child)) { ref = jsvGetPrevSibling(child); jsvUnLock(child); if (ref) { child = jsvLock(ref); } else { child = 0; } } // check if the last integer key really is the last element if (child) { if (jsvGetInteger(child) == length) { // child is the last element - remove it jsvRemoveChild(arr, child); } else { // child is not the last element jsvUnLock(child); child = 0; } } } // and finally shrink the array jsvSetArrayLength(arr, length, false); } return child; } /// Removes the first element of an array, and returns that element (or 0 if empty). DOES NOT RENUMBER. JsVar *jsvArrayPopFirst(JsVar *arr) { assert(jsvIsArray(arr)); if (jsvGetFirstChild(arr)) { JsVar *child = jsvLock(jsvGetFirstChild(arr)); if (jsvGetFirstChild(arr) == jsvGetLastChild(arr)) jsvSetLastChild(arr, 0); // if 1 item in array jsvSetFirstChild(arr, jsvGetNextSibling(child)); // unlink from end of array jsvUnRef(child); // as no longer in array if (jsvGetNextSibling(child)) { JsVar *v = jsvLock(jsvGetNextSibling(child)); jsvSetPrevSibling(v, 0); jsvUnLock(v); } jsvSetNextSibling(child, 0); return child; // and return it } else { // no children! return 0; } } /// Adds a new variable element to the end of an array (IF it was not already there). Return true if successful void jsvArrayAddUnique(JsVar *arr, JsVar *v) { JsVar *idx = jsvGetIndexOf(arr, v, false); // did it already exist? if (!idx) { jsvArrayPush(arr, v); // if 0, it failed } else { jsvUnLock(idx); } } /// Join all elements of an array together into a string JsVar *jsvArrayJoin(JsVar *arr, JsVar *filler) { JsVar *str = jsvNewFromEmptyString(); if (!str) return 0; // out of memory JsvIterator it; jsvIteratorNew(&it, arr, JSIF_EVERY_ARRAY_ELEMENT); bool first = true; while (!jspIsInterrupted() && jsvIteratorHasElement(&it)) { JsVar *key = jsvIteratorGetKey(&it); if (jsvIsInt(key)) { // add the filler if (filler && !first) jsvAppendStringVarComplete(str, filler); first = false; // add the value JsVar *value = jsvIteratorGetValue(&it); if (value && !jsvIsNull(value)) { JsVar *valueStr = jsvAsString(value, false); if (valueStr) { // could be out of memory jsvAppendStringVarComplete(str, valueStr); jsvUnLock(valueStr); } } jsvUnLock(value); } jsvUnLock(key); jsvIteratorNext(&it); } jsvIteratorFree(&it); return str; } /// Insert a new element before beforeIndex, DOES NOT UPDATE INDICES void jsvArrayInsertBefore(JsVar *arr, JsVar *beforeIndex, JsVar *element) { if (beforeIndex) { JsVar *idxVar = jsvMakeIntoVariableName(jsvNewFromInteger(0), element); if (!idxVar) return; // out of memory JsVarRef idxRef = jsvGetRef(jsvRef(idxVar)); JsVarRef prev = jsvGetPrevSibling(beforeIndex); if (prev) { JsVar *prevVar = jsvRef(jsvLock(prev)); jsvSetInteger(idxVar, jsvGetInteger(prevVar)+1); // update index number jsvSetNextSibling(prevVar, idxRef); jsvUnLock(prevVar); jsvSetPrevSibling(idxVar, prev); } else { jsvSetPrevSibling(idxVar, 0); jsvSetFirstChild(arr, idxRef); } jsvSetPrevSibling(beforeIndex, idxRef); jsvSetNextSibling(idxVar, jsvGetRef(jsvRef(beforeIndex))); jsvUnLock(idxVar); } else jsvArrayPush(arr, element); } /** Same as jsvMathsOpPtr, but if a or b are a name, skip them * and go to what they point to. Also handle the case where * they may be objects with valueOf functions. */ JsVar *jsvMathsOpSkipNames(JsVar *a, JsVar *b, int op) { JsVar *pa = jsvSkipName(a); JsVar *pb = jsvSkipName(b); JsVar *oa = jsvGetValueOf(pa); JsVar *ob = jsvGetValueOf(pb); jsvUnLock2(pa, pb); JsVar *res = jsvMathsOp(oa,ob,op); jsvUnLock2(oa, ob); return res; } JsVar *jsvMathsOpError(int op, const char *datatype) { char opName[32]; jslTokenAsString(op, opName, sizeof(opName)); jsError("Operation %s not supported on the %s datatype", opName, datatype); return 0; } bool jsvMathsOpTypeEqual(JsVar *a, JsVar *b) { // check type first, then call again to check data bool eql = (a==0) == (b==0); if (a && b) { // Check whether both are numbers, otherwise check the variable // type flags themselves eql = ((jsvIsInt(a)||jsvIsFloat(a)) && (jsvIsInt(b)||jsvIsFloat(b))) || ((a->flags & JSV_VARTYPEMASK) == (b->flags & JSV_VARTYPEMASK)); } if (eql) { JsVar *contents = jsvMathsOp(a,b, LEX_EQUAL); if (!jsvGetBool(contents)) eql = false; jsvUnLock(contents); } else { /* Make sure we don't get in the situation where we have two equal * strings with a check that fails because they were stored differently */ assert(!(jsvIsString(a) && jsvIsString(b) && jsvIsBasicVarEqual(a,b))); } return eql; } JsVar *jsvMathsOp(JsVar *a, JsVar *b, int op) { // Type equality check if (op == LEX_TYPEEQUAL || op == LEX_NTYPEEQUAL) { bool eql = jsvMathsOpTypeEqual(a,b); if (op == LEX_TYPEEQUAL) return jsvNewFromBool(eql); else return jsvNewFromBool(!eql); } bool needsInt = op=='&' || op=='|' || op=='^' || op==LEX_LSHIFT || op==LEX_RSHIFT || op==LEX_RSHIFTUNSIGNED; bool needsNumeric = needsInt || op=='*' || op=='/' || op=='%' || op=='-'; bool isCompare = op==LEX_EQUAL || op==LEX_NEQUAL || op=='<' || op==LEX_LEQUAL || op=='>'|| op==LEX_GEQUAL; if (isCompare) { if (jsvIsNumeric(a) && jsvIsString(b)) { needsNumeric = true; needsInt = jsvIsIntegerish(a) && jsvIsStringNumericInt(b, false); } else if (jsvIsNumeric(b) && jsvIsString(a)) { needsNumeric = true; needsInt = jsvIsIntegerish(b) && jsvIsStringNumericInt(a, false); } } // do maths... if (jsvIsUndefined(a) && jsvIsUndefined(b)) { if (op == LEX_EQUAL) return jsvNewFromBool(true); else if (op == LEX_NEQUAL) return jsvNewFromBool(false); else return 0; // undefined } else if (needsNumeric || ((jsvIsNumeric(a) || jsvIsUndefined(a) || jsvIsNull(a)) && (jsvIsNumeric(b) || jsvIsUndefined(b) || jsvIsNull(b)))) { if (needsInt || (jsvIsIntegerish(a) && jsvIsIntegerish(b))) { // note that int+undefined should be handled as a double // use ints JsVarInt da = jsvGetInteger(a); JsVarInt db = jsvGetInteger(b); switch (op) { case '+': return jsvNewFromLongInteger((long long)da + (long long)db); case '-': return jsvNewFromLongInteger((long long)da - (long long)db); case '*': return jsvNewFromLongInteger((long long)da * (long long)db); case '/': return jsvNewFromFloat((JsVarFloat)da/(JsVarFloat)db); case '&': return jsvNewFromInteger(da&db); case '|': return jsvNewFromInteger(da|db); case '^': return jsvNewFromInteger(da^db); case '%': return db ? jsvNewFromInteger(da%db) : jsvNewFromFloat(NAN); case LEX_LSHIFT: return jsvNewFromInteger(da << db); case LEX_RSHIFT: return jsvNewFromInteger(da >> db); case LEX_RSHIFTUNSIGNED: return jsvNewFromInteger((JsVarInt)(((JsVarIntUnsigned)da) >> db)); case LEX_EQUAL: return jsvNewFromBool(da==db && jsvIsNull(a)==jsvIsNull(b)); case LEX_NEQUAL: return jsvNewFromBool(da!=db || jsvIsNull(a)!=jsvIsNull(b)); case '<': return jsvNewFromBool(da<db); case LEX_LEQUAL: return jsvNewFromBool(da<=db); case '>': return jsvNewFromBool(da>db); case LEX_GEQUAL: return jsvNewFromBool(da>=db); default: return jsvMathsOpError(op, "Integer"); } } else { // use doubles JsVarFloat da = jsvGetFloat(a); JsVarFloat db = jsvGetFloat(b); switch (op) { case '+': return jsvNewFromFloat(da+db); case '-': return jsvNewFromFloat(da-db); case '*': return jsvNewFromFloat(da*db); case '/': return jsvNewFromFloat(da/db); case '%': return jsvNewFromFloat(jswrap_math_mod(da, db)); case LEX_EQUAL: case LEX_NEQUAL: { bool equal = da==db; if ((jsvIsNull(a) && jsvIsUndefined(b)) || (jsvIsNull(b) && jsvIsUndefined(a))) equal = true; // JS quirk :) return jsvNewFromBool((op==LEX_EQUAL) ? equal : ((bool)!equal)); } case '<': return jsvNewFromBool(da<db); case LEX_LEQUAL: return jsvNewFromBool(da<=db); case '>': return jsvNewFromBool(da>db); case LEX_GEQUAL: return jsvNewFromBool(da>=db); default: return jsvMathsOpError(op, "Double"); } } } else if ((jsvIsArray(a) || jsvIsObject(a) || jsvIsFunction(a) || jsvIsArray(b) || jsvIsObject(b) || jsvIsFunction(b)) && jsvIsArray(a)==jsvIsArray(b) && // Fix #283 - convert to string and test if only one is an array (op == LEX_EQUAL || op==LEX_NEQUAL)) { bool equal = a==b; if (jsvIsNativeFunction(a) || jsvIsNativeFunction(b)) { // even if one is not native, the contents will be different equal = a && b && a->varData.native.ptr == b->varData.native.ptr && a->varData.native.argTypes == b->varData.native.argTypes && jsvGetFirstChild(a) == jsvGetFirstChild(b); } /* Just check pointers */ switch (op) { case LEX_EQUAL: return jsvNewFromBool(equal); case LEX_NEQUAL: return jsvNewFromBool(!equal); default: return jsvMathsOpError(op, jsvIsArray(a)?"Array":"Object"); } } else { JsVar *da = jsvAsString(a, false); JsVar *db = jsvAsString(b, false); if (!da || !db) { // out of memory jsvUnLock2(da, db); return 0; } if (op=='+') { JsVar *v = jsvCopy(da, false); // TODO: can we be fancy and not copy da if we know it isn't reffed? what about locks? if (v) // could be out of memory jsvAppendStringVarComplete(v, db); jsvUnLock2(da, db); return v; } int cmp = jsvCompareString(da,db,0,0,false); jsvUnLock2(da, db); // use strings switch (op) { case LEX_EQUAL: return jsvNewFromBool(cmp==0); case LEX_NEQUAL: return jsvNewFromBool(cmp!=0); case '<': return jsvNewFromBool(cmp<0); case LEX_LEQUAL: return jsvNewFromBool(cmp<=0); case '>': return jsvNewFromBool(cmp>0); case LEX_GEQUAL: return jsvNewFromBool(cmp>=0); default: return jsvMathsOpError(op, "String"); } } } JsVar *jsvNegateAndUnLock(JsVar *v) { JsVar *zero = jsvNewFromInteger(0); JsVar *res = jsvMathsOpSkipNames(zero, v, '-'); jsvUnLock2(zero, v); return res; } /** If the given element is found, return the path to it as a string of * the form 'foo.bar', else return 0. If we would have returned a.b and * ignoreParent is a, don't! */ JsVar *jsvGetPathTo(JsVar *root, JsVar *element, int maxDepth, JsVar *ignoreParent) { if (maxDepth<=0) return 0; JsvIterator it; jsvIteratorNew(&it, root, JSIF_DEFINED_ARRAY_ElEMENTS); while (jsvIteratorHasElement(&it)) { JsVar *el = jsvIteratorGetValue(&it); if (el == element && root != ignoreParent) { // if we found it - send the key name back! JsVar *name = jsvAsString(jsvIteratorGetKey(&it), true); jsvIteratorFree(&it); return name; } else if (jsvIsObject(el) || jsvIsArray(el) || jsvIsFunction(el)) { // recursively search JsVar *n = jsvGetPathTo(el, element, maxDepth-1, ignoreParent); if (n) { // we found it! Append our name onto it as well JsVar *keyName = jsvIteratorGetKey(&it); JsVar *name = jsvVarPrintf(jsvIsObject(el) ? "%v.%v" : "%v[%q]",keyName,n); jsvUnLock2(keyName, n); jsvIteratorFree(&it); return name; } } jsvIteratorNext(&it); } jsvIteratorFree(&it); return 0; } void jsvTraceLockInfo(JsVar *v) { jsiConsolePrintf("#%d[r%d,l%d] ",jsvGetRef(v),jsvGetRefs(v),jsvGetLocks(v)); } /** Get the lowest level at which searchRef appears */ int _jsvTraceGetLowestLevel(JsVar *var, JsVar *searchVar) { if (var == searchVar) return 0; int found = -1; // Use IS_RECURSING flag to stop recursion if (var->flags & JSV_IS_RECURSING) return -1; var->flags |= JSV_IS_RECURSING; if (jsvHasSingleChild(var) && jsvGetFirstChild(var)) { JsVar *child = jsvLock(jsvGetFirstChild(var)); int f = _jsvTraceGetLowestLevel(child, searchVar); jsvUnLock(child); if (f>=0 && (found<0 || f<found)) found=f+1; } if (jsvHasChildren(var)) { JsVarRef childRef = jsvGetFirstChild(var); while (childRef) { JsVar *child = jsvLock(childRef); int f = _jsvTraceGetLowestLevel(child, searchVar); if (f>=0 && (found<0 || f<found)) found=f+1; childRef = jsvGetNextSibling(child); jsvUnLock(child); } } var->flags &= ~JSV_IS_RECURSING; return found; // searchRef not found } void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) { #ifdef SAVE_ON_FLASH jsiConsolePrint("Trace unimplemented in this version.\n"); #else int i; for (i=0;i<indent;i++) jsiConsolePrint(" "); if (!var) { jsiConsolePrint("undefined"); return; } jsvTraceLockInfo(var); int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var); if (lowestLevel < level) { // If this data is available elsewhere in the tree (but nearer the root) // then don't print it. This makes the dump significantly more readable! // It also stops us getting in recursive loops ... jsiConsolePrint("...\n"); return; } if (jsvIsName(var)) jsiConsolePrint("Name "); char endBracket = ' '; if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; } else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; } else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; } else if (jsvIsFunction(var)) { jsiConsolePrint("Function { "); if (jsvIsFunctionReturn(var)) jsiConsolePrint("return "); endBracket = '}'; } else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var)); else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var)); else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false"); else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var)); else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var); else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var)); else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)?jswGetBasicObjectName(var):"unknown ArrayBuffer"); // way to get nice name else if (jsvIsString(var)) { size_t blocks = 1; if (jsvGetLastChild(var)) { JsVar *v = jsvLock(jsvGetLastChild(var)); blocks += jsvCountJsVarsUsed(v); jsvUnLock(v); } if (jsvIsFlatString(var)) { blocks += jsvGetFlatStringBlocks(var); } jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var); } else { jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK)); } // print a value if it was stored in here as well... if (jsvIsNameInt(var)) { jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var)); return; } else if (jsvIsNameIntBool(var)) { jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false"); return; } if (jsvHasSingleChild(var)) { JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0; _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); } else if (jsvHasChildren(var)) { JsvIterator it; jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS); bool first = true; while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) { if (first) jsiConsolePrintf("\n"); first = false; JsVar *child = jsvIteratorGetKey(&it); _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); jsiConsolePrintf("\n"); jsvIteratorNext(&it); } jsvIteratorFree(&it); if (!first) for (i=0;i<indent;i++) jsiConsolePrint(" "); } jsiConsolePrintf("%c", endBracket); #endif } /** Write debug info for this Var out to the console */ void jsvTrace(JsVar *var, int indent) { _jsvTrace(var,indent,var,0); jsiConsolePrintf("\n"); } /** Recursively mark the variable */ static void jsvGarbageCollectMarkUsed(JsVar *var) { var->flags &= (JsVarFlags)~JSV_GARBAGE_COLLECT; if (jsvHasCharacterData(var)) { // non-recursively scan strings JsVarRef child = jsvGetLastChild(var); while (child) { JsVar *childVar; childVar = jsvGetAddressOf(child); childVar->flags &= (JsVarFlags)~JSV_GARBAGE_COLLECT; child = jsvGetLastChild(childVar); } } // intentionally no else if (jsvHasSingleChild(var)) { if (jsvGetFirstChild(var)) { JsVar *childVar = jsvGetAddressOf(jsvGetFirstChild(var)); if (childVar->flags & JSV_GARBAGE_COLLECT) jsvGarbageCollectMarkUsed(childVar); } } else if (jsvHasChildren(var)) { JsVarRef child = jsvGetFirstChild(var); while (child) { JsVar *childVar; childVar = jsvGetAddressOf(child); if (childVar->flags & JSV_GARBAGE_COLLECT) jsvGarbageCollectMarkUsed(childVar); child = jsvGetNextSibling(childVar); } } } /** Run a garbage collection sweep - return nonzero if things have been freed */ int jsvGarbageCollect() { if (isMemoryBusy) return false; isMemoryBusy = MEMBUSY_GC; JsVarRef i; // Add GC flags to anything that is currently used for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { // if it is not unused var->flags |= (JsVarFlags)JSV_GARBAGE_COLLECT; // if we have a flat string, skip that many blocks if (jsvIsFlatString(var)) i = (JsVarRef)(i+jsvGetFlatStringBlocks(var)); } } /* recursively remove anything that is referenced from a var that is locked. */ for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if ((var->flags & JSV_GARBAGE_COLLECT) && // not already GC'd jsvGetLocks(var)>0) // or it is locked jsvGarbageCollectMarkUsed(var); // if we have a flat string, skip that many blocks if (jsvIsFlatString(var)) i = (JsVarRef)(i+jsvGetFlatStringBlocks(var)); } /* now sweep for things that we can GC! * Also update the free list - this means that every new variable that * gets allocated gets allocated towards the start of memory, which * hopefully helps compact everything towards the start. */ unsigned int freedCount = 0; jsVarFirstEmpty = 0; JsVar *lastEmpty = 0; for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if (var->flags & JSV_GARBAGE_COLLECT) { if (jsvIsFlatString(var)) { // If we're a flat string, there are more blocks to free. unsigned int count = (unsigned int)jsvGetFlatStringBlocks(var); freedCount+=count; // Free the first block var->flags = JSV_UNUSED; // add this to our free list if (lastEmpty) jsvSetNextSibling(lastEmpty, i); else jsVarFirstEmpty = i; lastEmpty = var; // free subsequent blocks while (count-- > 0) { i++; var = jsvGetAddressOf((JsVarRef)(i)); var->flags = JSV_UNUSED; // add this to our free list if (lastEmpty) jsvSetNextSibling(lastEmpty, i); else jsVarFirstEmpty = i; lastEmpty = var; } } else { // otherwise just free 1 block if (jsvHasSingleChild(var)) { /* If this had a child that wasn't listed for GC then we need to * unref it. Everything else is fine because it'll disappear anyway. * We don't have to check if we should free this other variable * here because we know the GC picked up it was referenced from * somewhere else. */ JsVarRef ch = jsvGetFirstChild(var); if (ch) { JsVar *child = jsvGetAddressOf(ch); // not locked if (child->flags!=JSV_UNUSED && // not already GC'd! !(child->flags&JSV_GARBAGE_COLLECT)) // not marked for GC jsvUnRef(child); } } /* Sanity checks here. We're making sure that any variables that are * linked from this one have either already been garbage collected or * are marked for GC */ assert(!jsvHasChildren(var) || !jsvGetFirstChild(var) || jsvGetAddressOf(jsvGetFirstChild(var))->flags==JSV_UNUSED || (jsvGetAddressOf(jsvGetFirstChild(var))->flags&JSV_GARBAGE_COLLECT)); assert(!jsvHasChildren(var) || !jsvGetLastChild(var) || jsvGetAddressOf(jsvGetLastChild(var))->flags==JSV_UNUSED || (jsvGetAddressOf(jsvGetLastChild(var))->flags&JSV_GARBAGE_COLLECT)); assert(!jsvIsName(var) || !jsvGetPrevSibling(var) || jsvGetAddressOf(jsvGetPrevSibling(var))->flags==JSV_UNUSED || (jsvGetAddressOf(jsvGetPrevSibling(var))->flags&JSV_GARBAGE_COLLECT)); assert(!jsvIsName(var) || !jsvGetNextSibling(var) || jsvGetAddressOf(jsvGetNextSibling(var))->flags==JSV_UNUSED || (jsvGetAddressOf(jsvGetNextSibling(var))->flags&JSV_GARBAGE_COLLECT)); // free! var->flags = JSV_UNUSED; // add this to our free list if (lastEmpty) jsvSetNextSibling(lastEmpty, i); else jsVarFirstEmpty = i; lastEmpty = var; freedCount++; } } else if (jsvIsFlatString(var)) { // if we have a flat string, skip forward that many blocks i = (JsVarRef)(i+jsvGetFlatStringBlocks(var)); } else if (var->flags == JSV_UNUSED) { // this is already free - add it to the free list if (lastEmpty) jsvSetNextSibling(lastEmpty, i); else jsVarFirstEmpty = i; lastEmpty = var; } } if (lastEmpty) jsvSetNextSibling(lastEmpty, 0); isMemoryBusy = MEM_NOT_BUSY; return (int)freedCount; } #ifndef RELEASE // Dump any locked variables that aren't referenced from `global` - for debugging memory leaks void jsvDumpLockedVars() { jsvGarbageCollect(); if (isMemoryBusy) return; isMemoryBusy = MEMBUSY_SYSTEM; JsVarRef i; // clear garbage collect flags for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { // if it is not unused var->flags |= (JsVarFlags)JSV_GARBAGE_COLLECT; // if we have a flat string, skip that many blocks if (jsvIsFlatString(var)) i = (JsVarRef)(i+jsvGetFlatStringBlocks(var)); } } // Add global jsvGarbageCollectMarkUsed(execInfo.root); // Now dump any that aren't used! for (i=1;i<=jsVarsSize;i++) { JsVar *var = jsvGetAddressOf(i); if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { if (var->flags & JSV_GARBAGE_COLLECT) { jsvGarbageCollectMarkUsed(var); jsvTrace(var, 0); } } } isMemoryBusy = MEM_NOT_BUSY; } // Dump the free list - in order void jsvDumpFreeList() { JsVarRef ref = jsVarFirstEmpty; int n = 0; while (ref) { jsiConsolePrintf("%5d ", (int)ref); if (++n >= 16) { n = 0; jsiConsolePrintf("\n"); } JsVar *v = jsvGetAddressOf(ref); ref = jsvGetNextSibling(v); } jsiConsolePrintf("\n"); } #endif /** Remove whitespace to the right of a string - on MULTIPLE LINES */ JsVar *jsvStringTrimRight(JsVar *srcString) { JsvStringIterator src, dst; JsVar *dstString = jsvNewFromEmptyString(); jsvStringIteratorNew(&src, srcString, 0); jsvStringIteratorNew(&dst, dstString, 0); int spaces = 0; while (jsvStringIteratorHasChar(&src)) { char ch = jsvStringIteratorGetChar(&src); jsvStringIteratorNext(&src); if (ch==' ') spaces++; else if (ch=='\n') { spaces = 0; jsvStringIteratorAppend(&dst, ch); } else { for (;spaces>0;spaces--) jsvStringIteratorAppend(&dst, ' '); jsvStringIteratorAppend(&dst, ch); } } jsvStringIteratorFree(&src); jsvStringIteratorFree(&dst); return dstString; } /// If v is the key of a function, return true if it is internal and shouldn't be visible to the user bool jsvIsInternalFunctionKey(JsVar *v) { return (jsvIsString(v) && ( v->varData.str[0]==JS_HIDDEN_CHAR) ) || jsvIsFunctionParameter(v); } /// If v is the key of an object, return true if it is internal and shouldn't be visible to the user bool jsvIsInternalObjectKey(JsVar *v) { return (jsvIsString(v) && ( v->varData.str[0]==JS_HIDDEN_CHAR || jsvIsStringEqual(v, JSPARSE_INHERITS_VAR) || jsvIsStringEqual(v, JSPARSE_CONSTRUCTOR_VAR) )); } /// Get the correct checker function for the given variable. see jsvIsInternalFunctionKey/jsvIsInternalObjectKey JsvIsInternalChecker jsvGetInternalFunctionCheckerFor(JsVar *v) { if (jsvIsFunction(v)) return jsvIsInternalFunctionKey; if (jsvIsObject(v)) return jsvIsInternalObjectKey; return 0; } /** Using 'configs', this reads 'object' into the given pointers, returns true on success. * If object is not undefined and not an object, an error is raised. * If there are fields that are not in the list of configs, an error is raised */ bool jsvReadConfigObject(JsVar *object, jsvConfigObject *configs, int nConfigs) { if (jsvIsUndefined(object)) return true; if (!jsvIsObject(object)) { jsExceptionHere(JSET_ERROR, "Expecting an Object, or undefined"); return false; } // Ok, it's an object JsvObjectIterator it; jsvObjectIteratorNew(&it, object); bool ok = true; while (ok && jsvObjectIteratorHasValue(&it)) { JsVar *key = jsvObjectIteratorGetKey(&it); bool found = false; int i; for (i=0;i<nConfigs;i++) { if (jsvIsStringEqual(key, configs[i].name)) { found = true; if (configs[i].ptr) { JsVar *val = jsvObjectIteratorGetValue(&it); switch (configs[i].type) { case 0: break; case JSV_OBJECT: case JSV_STRING_0: case JSV_ARRAY: case JSV_FUNCTION: *((JsVar**)configs[i].ptr) = jsvLockAgain(val); break; case JSV_PIN: *((Pin*)configs[i].ptr) = jshGetPinFromVar(val); break; case JSV_BOOLEAN: *((bool*)configs[i].ptr) = jsvGetBool(val); break; case JSV_INTEGER: *((JsVarInt*)configs[i].ptr) = jsvGetInteger(val); break; case JSV_FLOAT: *((JsVarFloat*)configs[i].ptr) = jsvGetFloat(val); break; default: assert(0); break; } jsvUnLock(val); } } } if (!found) { jsExceptionHere(JSET_ERROR, "Unknown option %q", key); ok = false; } jsvUnLock(key); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); return ok; } /// Is the variable an instance of the given class. Eg. `jsvIsInstanceOf(e, "Error")` - does a simple, non-recursive check that doesn't take account of builtins like String bool jsvIsInstanceOf(JsVar *var, const char *constructorName) { bool isInst = false; if (!jsvHasChildren(var)) return false; JsVar *proto = jsvObjectGetChild(var, JSPARSE_INHERITS_VAR, 0); if (jsvIsObject(proto)) { JsVar *constr = jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0); if (constr) isInst = jspIsConstructor(constr, constructorName); jsvUnLock(constr); } jsvUnLock(proto); return isInst; } JsVar *jsvNewTypedArray(JsVarDataArrayBufferViewType type, JsVarInt length) { JsVar *lenVar = jsvNewFromInteger(length); if (!lenVar) return 0; JsVar *array = jswrap_typedarray_constructor(type, lenVar,0,0); jsvUnLock(lenVar); return array; } #ifndef SAVE_ON_FLASH JsVar *jsvNewDataViewWithData(JsVarInt length, unsigned char *data) { JsVar *buf = jswrap_arraybuffer_constructor(length); if (!buf) return 0; JsVar *view = jswrap_dataview_constructor(buf, 0, 0); if (!view) { jsvUnLock(buf); return 0; } if (data) { JsVar *arrayBufferData = jsvGetArrayBufferBackingString(buf); if (arrayBufferData) jsvSetString(arrayBufferData, (char *)data, (size_t)length); jsvUnLock(arrayBufferData); } jsvUnLock(buf); return view; } #endif JsVar *jsvNewArrayBufferWithPtr(unsigned int length, char **ptr) { assert(ptr); *ptr=0; JsVar *backingString = jsvNewFlatStringOfLength(length); if (!backingString) return 0; JsVar *arr = jsvNewArrayBufferFromString(backingString, length); if (!arr) { jsvUnLock(backingString); return 0; } *ptr = jsvGetFlatStringPointer(backingString); jsvUnLock(backingString); return arr; } JsVar *jsvNewArrayBufferWithData(JsVarInt length, unsigned char *data) { assert(data); JsVar *dst = 0; JsVar *arr = jsvNewArrayBufferWithPtr((unsigned int)length, (char**)&dst); if (!dst) { jsvUnLock(arr); return 0; } memcpy(dst, data, (size_t)length); return arr; } void *jsvMalloc(size_t size) { /** Allocate flat string, return pointer to its first element. * As we drop the pointer here, it's left locked. jsvGetFlatStringPointer * is also safe if 0 is passed in. */ JsVar *flatStr = jsvNewFlatStringOfLength((unsigned int)size); if (!flatStr) { jsErrorFlags |= JSERR_LOW_MEMORY; // Not allocated - try and free any command history/etc while (jsiFreeMoreMemory()); // Garbage collect jsvGarbageCollect(); // Try again flatStr = jsvNewFlatStringOfLength((unsigned int)size); } // intentionally no jsvUnLock - see above void *p = (void*)jsvGetFlatStringPointer(flatStr); if (p) { //jsiConsolePrintf("jsvMalloc var %d-%d at %d (%d bytes)\n", jsvGetRef(flatStr), jsvGetRef(flatStr)+jsvGetFlatStringBlocks(flatStr), p, size); memset(p,0,size); } return p; } void jsvFree(void *ptr) { JsVar *flatStr = jsvGetFlatStringFromPointer((char *)ptr); //jsiConsolePrintf("jsvFree var %d at %d (%d bytes)\n", jsvGetRef(flatStr), ptr, jsvGetLength(flatStr)); jsvUnLock(flatStr); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_161_0
crossvul-cpp_data_bad_2529_1
/* * wildmidi_lib.c -- Midi Wavetable Processing library * * Copyright (C) WildMIDI Developers 2001-2016 * * This file is part of WildMIDI. * * WildMIDI is free software: you can redistribute and/or modify the player * under the terms of the GNU General Public License and you can redistribute * and/or modify the library under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either version 3 of * the licenses, or(at your option) any later version. * * WildMIDI is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License and the * GNU Lesser General Public License along with WildMIDI. If not, see * <http://www.gnu.org/licenses/>. */ #define _WILDMIDI_LIB_C #include "config.h" #include <stdint.h> #include <errno.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wm_error.h" #include "file_io.h" #include "lock.h" #include "reverb.h" #include "gus_pat.h" #include "common.h" #include "wildmidi_lib.h" #include "filenames.h" #include "internal_midi.h" #include "f_hmi.h" #include "f_hmp.h" #include "f_midi.h" #include "f_mus.h" #include "f_xmidi.h" #include "patches.h" #include "sample.h" #include "mus2mid.h" #include "xmi2mid.h" /* * ========================= * Global Data and Data Structs * ========================= */ static int WM_Initialized = 0; uint16_t _WM_MixerOptions = 0; uint16_t _WM_SampleRate; int16_t _WM_MasterVolume; /* when converting files to midi */ typedef struct _cvt_options { int lock; uint16_t xmi_convert_type; uint16_t frequency; } _cvt_options; static _cvt_options WM_ConvertOptions = {0, 0, 0}; float _WM_reverb_room_width = 16.875f; float _WM_reverb_room_length = 22.5f; float _WM_reverb_listen_posx = 8.4375f; float _WM_reverb_listen_posy = 16.875f; int _WM_fix_release = 0; int _WM_auto_amp = 0; int _WM_auto_amp_with_amp = 0; struct _miditrack { uint32_t length; uint32_t ptr; uint32_t delta; uint8_t running_event; uint8_t EOT; }; struct _mdi_patches { struct _patch *patch; struct _mdi_patch *next; }; #define FPBITS 10 #define FPMASK ((1L<<FPBITS)-1L) /* Gauss Interpolation code adapted from code supplied by Eric. A. Welsh */ static double newt_coeffs[58][58]; /* for start/end of samples */ #define MAX_GAUSS_ORDER 34 /* 34 is as high as we can go before errors crop up */ static double *gauss_table = NULL; /* *gauss_table[1<<FPBITS] */ static int gauss_n = MAX_GAUSS_ORDER; static int gauss_lock; static void init_gauss(void) { /* init gauss table */ int n = gauss_n; int m, i, k, n_half = (n >> 1); int j; int sign; double ck; double x, x_inc, xz; double z[35]; double *gptr, *t; _WM_Lock(&gauss_lock); if (gauss_table) { _WM_Unlock(&gauss_lock); return; } newt_coeffs[0][0] = 1; for (i = 0; i <= n; i++) { newt_coeffs[i][0] = 1; newt_coeffs[i][i] = 1; if (i > 1) { newt_coeffs[i][0] = newt_coeffs[i - 1][0] / i; newt_coeffs[i][i] = newt_coeffs[i - 1][0] / i; } for (j = 1; j < i; j++) { newt_coeffs[i][j] = newt_coeffs[i - 1][j - 1] + newt_coeffs[i - 1][j]; if (i > 1) newt_coeffs[i][j] /= i; } z[i] = i / (4 * M_PI); } for (i = 0; i <= n; i++) for (j = 0, sign = (int) pow(-1, i); j <= i; j++, sign *= -1) newt_coeffs[i][j] *= sign; t = malloc((1<<FPBITS) * (n + 1) * sizeof(double)); x_inc = 1.0 / (1<<FPBITS); for (m = 0, x = 0.0; m < (1<<FPBITS); m++, x += x_inc) { xz = (x + n_half) / (4 * M_PI); gptr = &t[m * (n + 1)]; for (k = 0; k <= n; k++) { ck = 1.0; for (i = 0; i <= n; i++) { if (i == k) continue; ck *= (sin(xz - z[i])) / (sin(z[k] - z[i])); } *gptr++ = ck; } } gauss_table = t; _WM_Unlock(&gauss_lock); } static void free_gauss(void) { _WM_Lock(&gauss_lock); free(gauss_table); gauss_table = NULL; _WM_Unlock(&gauss_lock); } struct _hndl { void * handle; struct _hndl *next; struct _hndl *prev; }; static struct _hndl * first_handle = NULL; #define MAX_AUTO_AMP 2.0 /* * ========================= * Internal Functions * ========================= */ void _cvt_reset_options (void) { _WM_Lock(&WM_ConvertOptions.lock); WM_ConvertOptions.xmi_convert_type = 0; WM_ConvertOptions.frequency = 0; _WM_Unlock(&WM_ConvertOptions.lock); } uint16_t _cvt_get_option (uint16_t tag) { uint16_t r = 0; _WM_Lock(&WM_ConvertOptions.lock); switch (tag) { case WM_CO_XMI_TYPE: r = WM_ConvertOptions.xmi_convert_type; break; case WM_CO_FREQUENCY: r = WM_ConvertOptions.frequency; break; } _WM_Unlock(&WM_ConvertOptions.lock); return r; } static void WM_InitPatches(void) { int i; for (i = 0; i < 128; i++) { _WM_patch[i] = NULL; } } static void WM_FreePatches(void) { int i; struct _patch * tmp_patch; struct _sample * tmp_sample; _WM_Lock(&_WM_patch_lock); for (i = 0; i < 128; i++) { while (_WM_patch[i]) { while (_WM_patch[i]->first_sample) { tmp_sample = _WM_patch[i]->first_sample->next; free(_WM_patch[i]->first_sample->data); free(_WM_patch[i]->first_sample); _WM_patch[i]->first_sample = tmp_sample; } free(_WM_patch[i]->filename); tmp_patch = _WM_patch[i]->next; free(_WM_patch[i]); _WM_patch[i] = tmp_patch; } } _WM_Unlock(&_WM_patch_lock); } /* wm_strdup -- adds extra space for appending up to 4 chars */ static char *wm_strdup (const char *str) { size_t l = strlen(str) + 5; char *d = (char *) malloc(l * sizeof(char)); if (d) { strcpy(d, str); return (d); } return (NULL); } static inline int wm_isdigit(int c) { return (c >= '0' && c <= '9'); } static inline int wm_isupper(int c) { return (c >= 'A' && c <= 'Z'); } static inline int wm_tolower(int c) { return ((wm_isupper(c)) ? (c | ('a' - 'A')) : c); } #if 0 /* clang whines that these aren't used. */ static inline int wm_islower(int c) { return (c >= 'a' && c <= 'z'); } static inline int wm_toupper(int c) { return ((wm_islower(c)) ? (c & ~('a' - 'A')) : c); } #endif static int wm_strcasecmp(const char *s1, const char * s2) { const char * p1 = s1; const char * p2 = s2; char c1, c2; if (p1 == p2) return 0; do { c1 = wm_tolower (*p1++); c2 = wm_tolower (*p2++); if (c1 == '\0') break; } while (c1 == c2); return (int)(c1 - c2); } static int wm_strncasecmp(const char *s1, const char *s2, size_t n) { const char * p1 = s1; const char * p2 = s2; char c1, c2; if (p1 == p2 || n == 0) return 0; do { c1 = wm_tolower (*p1++); c2 = wm_tolower (*p2++); if (c1 == '\0' || c1 != c2) break; } while (--n > 0); return (int)(c1 - c2); } #define TOKEN_CNT_INC 8 static char** WM_LC_Tokenize_Line(char *line_data) { int line_length = (int) strlen(line_data); int token_data_length = 0; int line_ofs = 0; int token_start = 0; char **token_data = NULL; int token_count = 0; if (!line_length) return (NULL); do { /* ignore everything after # */ if (line_data[line_ofs] == '#') { break; } if ((line_data[line_ofs] == ' ') || (line_data[line_ofs] == '\t')) { /* whitespace means we aren't in a token */ if (token_start) { token_start = 0; line_data[line_ofs] = '\0'; } } else { if (!token_start) { /* the start of a token in the line */ token_start = 1; if (token_count >= token_data_length) { token_data_length += TOKEN_CNT_INC; token_data = realloc(token_data, token_data_length * sizeof(char *)); if (token_data == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM,"to parse config", errno); return (NULL); } } token_data[token_count] = &line_data[line_ofs]; token_count++; } } line_ofs++; } while (line_ofs != line_length); /* if we have found some tokens then add a null token to the end */ if (token_count) { if (token_count >= token_data_length) { token_data = realloc(token_data, ((token_count + 1) * sizeof(char *))); } token_data[token_count] = NULL; } return (token_data); } static int load_config(const char *config_file, const char *conf_dir) { uint32_t config_size = 0; char *config_buffer = NULL; const char *dir_end = NULL; char *config_dir = NULL; uint32_t config_ptr = 0; uint32_t line_start_ptr = 0; uint16_t patchid = 0; struct _patch * tmp_patch; char **line_tokens = NULL; int token_count = 0; config_buffer = (char *) _WM_BufferFile(config_file, &config_size); if (!config_buffer) { WM_FreePatches(); return (-1); } if (conf_dir) { if (!(config_dir = wm_strdup(conf_dir))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_buffer); return (-1); } } else { dir_end = FIND_LAST_DIRSEP(config_file); if (dir_end) { config_dir = malloc((dir_end - config_file + 2)); if (config_dir == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_buffer); return (-1); } strncpy(config_dir, config_file, (dir_end - config_file + 1)); config_dir[dir_end - config_file + 1] = '\0'; } } config_ptr = 0; line_start_ptr = 0; /* handle files without a newline at the end: this relies on * _WM_BufferFile() allocating the buffer with one extra byte */ config_buffer[config_size] = '\n'; while (config_ptr <= config_size) { if (config_buffer[config_ptr] == '\r' || config_buffer[config_ptr] == '\n') { config_buffer[config_ptr] = '\0'; if (config_ptr != line_start_ptr) { _WM_Global_ErrorI = 0; /* because WM_LC_Tokenize_Line() can legitimately return NULL */ line_tokens = WM_LC_Tokenize_Line(&config_buffer[line_start_ptr]); if (line_tokens) { if (wm_strcasecmp(line_tokens[0], "dir") == 0) { free(config_dir); if (!line_tokens[1]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(missing name in dir line)", 0); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } else if (!(config_dir = wm_strdup(line_tokens[1]))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } if (!IS_DIR_SEPARATOR(config_dir[strlen(config_dir) - 1])) { config_dir[strlen(config_dir) + 1] = '\0'; config_dir[strlen(config_dir)] = DIR_SEPARATOR_CHAR; } } else if (wm_strcasecmp(line_tokens[0], "source") == 0) { char *new_config = NULL; if (!line_tokens[1]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(missing name in source line)", 0); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } else if (!IS_ABSOLUTE_PATH(line_tokens[1]) && config_dir) { new_config = malloc(strlen(config_dir) + strlen(line_tokens[1]) + 1); if (new_config == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } strcpy(new_config, config_dir); strcpy(&new_config[strlen(config_dir)], line_tokens[1]); } else { if (!(new_config = wm_strdup(line_tokens[1]))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } } if (load_config(new_config, config_dir) == -1) { free(new_config); free(line_tokens); free(config_buffer); free(config_dir); return (-1); } free(new_config); } else if (wm_strcasecmp(line_tokens[0], "bank") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in bank line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } patchid = (atoi(line_tokens[1]) & 0xFF) << 8; } else if (wm_strcasecmp(line_tokens[0], "drumset") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in drumset line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } patchid = ((atoi(line_tokens[1]) & 0xFF) << 8) | 0x80; } else if (wm_strcasecmp(line_tokens[0], "reverb_room_width") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_room_width line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_room_width = (float) atof(line_tokens[1]); if (_WM_reverb_room_width < 1.0f) { _WM_DEBUG_MSG("%s: reverb_room_width < 1 meter, setting to minimum of 1 meter", config_file); _WM_reverb_room_width = 1.0f; } else if (_WM_reverb_room_width > 100.0f) { _WM_DEBUG_MSG("%s: reverb_room_width > 100 meters, setting to maximum of 100 meters", config_file); _WM_reverb_room_width = 100.0f; } } else if (wm_strcasecmp(line_tokens[0], "reverb_room_length") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_room_length line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_room_length = (float) atof(line_tokens[1]); if (_WM_reverb_room_length < 1.0f) { _WM_DEBUG_MSG("%s: reverb_room_length < 1 meter, setting to minimum of 1 meter", config_file); _WM_reverb_room_length = 1.0f; } else if (_WM_reverb_room_length > 100.0f) { _WM_DEBUG_MSG("%s: reverb_room_length > 100 meters, setting to maximum of 100 meters", config_file); _WM_reverb_room_length = 100.0f; } } else if (wm_strcasecmp(line_tokens[0], "reverb_listener_posx") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_listen_posx line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_listen_posx = (float) atof(line_tokens[1]); if ((_WM_reverb_listen_posx > _WM_reverb_room_width) || (_WM_reverb_listen_posx < 0.0f)) { _WM_DEBUG_MSG("%s: reverb_listen_posx set outside of room", config_file); _WM_reverb_listen_posx = _WM_reverb_room_width / 2.0f; } } else if (wm_strcasecmp(line_tokens[0], "reverb_listener_posy") == 0) { if (!line_tokens[1] || !wm_isdigit(line_tokens[1][0])) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(syntax error in reverb_listen_posy line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } _WM_reverb_listen_posy = (float) atof(line_tokens[1]); if ((_WM_reverb_listen_posy > _WM_reverb_room_width) || (_WM_reverb_listen_posy < 0.0f)) { _WM_DEBUG_MSG("%s: reverb_listen_posy set outside of room", config_file); _WM_reverb_listen_posy = _WM_reverb_room_length * 0.75f; } } else if (wm_strcasecmp(line_tokens[0], "guspat_editor_author_cant_read_so_fix_release_time_for_me") == 0) { _WM_fix_release = 1; } else if (wm_strcasecmp(line_tokens[0], "auto_amp") == 0) { _WM_auto_amp = 1; } else if (wm_strcasecmp(line_tokens[0], "auto_amp_with_amp") == 0) { _WM_auto_amp = 1; _WM_auto_amp_with_amp = 1; } else if (wm_isdigit(line_tokens[0][0])) { patchid = (patchid & 0xFF80) | (atoi(line_tokens[0]) & 0x7F); if (_WM_patch[(patchid & 0x7F)] == NULL) { _WM_patch[(patchid & 0x7F)] = malloc(sizeof(struct _patch)); if (_WM_patch[(patchid & 0x7F)] == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } tmp_patch = _WM_patch[(patchid & 0x7F)]; tmp_patch->patchid = patchid; tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; tmp_patch->next = NULL; tmp_patch->first_sample = NULL; tmp_patch->loaded = 0; tmp_patch->inuse_count = 0; } else { tmp_patch = _WM_patch[(patchid & 0x7F)]; if (tmp_patch->patchid == patchid) { free(tmp_patch->filename); tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; } else { if (tmp_patch->next) { while (tmp_patch->next) { if (tmp_patch->next->patchid == patchid) break; tmp_patch = tmp_patch->next; } if (tmp_patch->next == NULL) { if ((tmp_patch->next = malloc(sizeof(struct _patch))) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } tmp_patch = tmp_patch->next; tmp_patch->patchid = patchid; tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; tmp_patch->next = NULL; tmp_patch->first_sample = NULL; tmp_patch->loaded = 0; tmp_patch->inuse_count = 0; } else { tmp_patch = tmp_patch->next; free(tmp_patch->filename); tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; } } else { tmp_patch->next = malloc( sizeof(struct _patch)); if (tmp_patch->next == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, errno); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } tmp_patch = tmp_patch->next; tmp_patch->patchid = patchid; tmp_patch->filename = NULL; tmp_patch->amp = 1024; tmp_patch->note = 0; tmp_patch->next = NULL; tmp_patch->first_sample = NULL; tmp_patch->loaded = 0; tmp_patch->inuse_count = 0; } } } if (!line_tokens[1]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(missing name in patch line)", 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } else if (!IS_ABSOLUTE_PATH(line_tokens[1]) && config_dir) { tmp_patch->filename = malloc(strlen(config_dir) + strlen(line_tokens[1]) + 5); if (tmp_patch->filename == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } strcpy(tmp_patch->filename, config_dir); strcat(tmp_patch->filename, line_tokens[1]); } else { if (!(tmp_patch->filename = wm_strdup(line_tokens[1]))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, config_file, 0); WM_FreePatches(); free(config_dir); free(line_tokens); free(config_buffer); return (-1); } } if (wm_strncasecmp(&tmp_patch->filename[strlen(tmp_patch->filename) - 4], ".pat", 4) != 0) { strcat(tmp_patch->filename, ".pat"); } tmp_patch->env[0].set = 0x00; tmp_patch->env[1].set = 0x00; tmp_patch->env[2].set = 0x00; tmp_patch->env[3].set = 0x00; tmp_patch->env[4].set = 0x00; tmp_patch->env[5].set = 0x00; tmp_patch->keep = 0; tmp_patch->remove = 0; token_count = 0; while (line_tokens[token_count]) { if (wm_strncasecmp(line_tokens[token_count], "amp=", 4) == 0) { if (!wm_isdigit(line_tokens[token_count][4])) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "amp="); } else { tmp_patch->amp = (atoi(&line_tokens[token_count][4]) << 10) / 100; } } else if (wm_strncasecmp(line_tokens[token_count], "note=", 5) == 0) { if (!wm_isdigit(line_tokens[token_count][5])) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "note="); } else { tmp_patch->note = atoi(&line_tokens[token_count][5]); } } else if (wm_strncasecmp(line_tokens[token_count], "env_time", 8) == 0) { if ((!wm_isdigit(line_tokens[token_count][8])) || (!wm_isdigit(line_tokens[token_count][10])) || (line_tokens[token_count][9] != '=')) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_time"); } else { uint32_t env_no = atoi(&line_tokens[token_count][8]); if (env_no > 5) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_time"); } else { tmp_patch->env[env_no].time = (float) atof(&line_tokens[token_count][10]); if ((tmp_patch->env[env_no].time > 45000.0f) || (tmp_patch->env[env_no].time < 1.47f)) { _WM_DEBUG_MSG("%s: range error in patch line %s", config_file, "env_time"); tmp_patch->env[env_no].set &= 0xFE; } else { tmp_patch->env[env_no].set |= 0x01; } } } } else if (wm_strncasecmp(line_tokens[token_count], "env_level", 9) == 0) { if ((!wm_isdigit(line_tokens[token_count][9])) || (!wm_isdigit(line_tokens[token_count][11])) || (line_tokens[token_count][10] != '=')) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_level"); } else { uint32_t env_no = atoi(&line_tokens[token_count][9]); if (env_no > 5) { _WM_DEBUG_MSG("%s: syntax error in patch line for %s", config_file, "env_level"); } else { tmp_patch->env[env_no].level = (float) atof(&line_tokens[token_count][11]); if ((tmp_patch->env[env_no].level > 1.0f) || (tmp_patch->env[env_no].level < 0.0f)) { _WM_DEBUG_MSG("%s: range error in patch line for %s", config_file, "env_level"); tmp_patch->env[env_no].set &= 0xFD; } else { tmp_patch->env[env_no].set |= 0x02; } } } } else if (wm_strcasecmp(line_tokens[token_count], "keep=loop") == 0) { tmp_patch->keep |= SAMPLE_LOOP; } else if (wm_strcasecmp(line_tokens[token_count], "keep=env") == 0) { tmp_patch->keep |= SAMPLE_ENVELOPE; } else if (wm_strcasecmp(line_tokens[token_count], "remove=sustain") == 0) { tmp_patch->remove |= SAMPLE_SUSTAIN; } else if (wm_strcasecmp(line_tokens[token_count], "remove=clamped") == 0) { tmp_patch->remove |= SAMPLE_CLAMPED; } token_count++; } } } else if (_WM_Global_ErrorI) { /* malloc() failure in WM_LC_Tokenize_Line() */ WM_FreePatches(); free(line_tokens); free(config_buffer); return (-1); } /* free up tokens */ free(line_tokens); } line_start_ptr = config_ptr + 1; } config_ptr++; } free(config_buffer); free(config_dir); return (0); } static int WM_LoadConfig(const char *config_file) { return load_config(config_file, NULL); } static int add_handle(void * handle) { struct _hndl *tmp_handle = NULL; if (first_handle == NULL) { first_handle = malloc(sizeof(struct _hndl)); if (first_handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, " to get ram", errno); return (-1); } first_handle->handle = handle; first_handle->prev = NULL; first_handle->next = NULL; } else { tmp_handle = first_handle; if (tmp_handle->next) { while (tmp_handle->next) tmp_handle = tmp_handle->next; } tmp_handle->next = malloc(sizeof(struct _hndl)); if (tmp_handle->next == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, " to get ram", errno); return (-1); } tmp_handle->next->prev = tmp_handle; tmp_handle = tmp_handle->next; tmp_handle->next = NULL; tmp_handle->handle = handle; } return (0); } //#define DEBUG_RESAMPLE #ifdef DEBUG_RESAMPLE #define RESAMPLE_DEBUGI(dx,dy) fprintf(stderr,"\r%s, %i\n",dx,dy) #define RESAMPLE_DEBUGS(dx) fprintf(stderr,"\r%s\n",dx) #else #define RESAMPLE_DEBUGI(dx,dy) #define RESAMPLE_DEBUGS(dx) #endif static int WM_GetOutput_Linear(midi * handle, int8_t *buffer, uint32_t size) { uint32_t buffer_used = 0; uint32_t i; struct _mdi *mdi = (struct _mdi *) handle; uint32_t real_samples_to_mix = 0; uint32_t data_pos; int32_t premix, left_mix, right_mix; // int32_t vol_mul; struct _note *note_data = NULL; uint32_t count; struct _event *event = mdi->current_event; int32_t *tmp_buffer; int32_t *out_buffer; _WM_Lock(&mdi->lock); buffer_used = 0; memset(buffer, 0, size); if ( (size / 2) > mdi->mix_buffer_size) { if ( (size / 2) <= ( mdi->mix_buffer_size * 2 )) { mdi->mix_buffer_size += MEM_CHUNK; } else { mdi->mix_buffer_size = size / 2; } mdi->mix_buffer = realloc(mdi->mix_buffer, mdi->mix_buffer_size * sizeof(int32_t)); } tmp_buffer = mdi->mix_buffer; memset(tmp_buffer, 0, ((size / 2) * sizeof(int32_t))); out_buffer = tmp_buffer; do { if (__builtin_expect((!mdi->samples_to_mix), 0)) { while ((!mdi->samples_to_mix) && (event->do_event)) { event->do_event(mdi, &event->event_data); if ((mdi->extra_info.mixer_options & WM_MO_LOOP) && (event[0].do_event == *_WM_do_meta_endoftrack)) { _WM_ResetToStart(mdi); event = mdi->current_event; } else { mdi->samples_to_mix = event->samples_to_next; event++; mdi->current_event = event; } } if (__builtin_expect((!mdi->samples_to_mix), 0)) { if (mdi->extra_info.current_sample >= mdi->extra_info.approx_total_samples) { break; } else if ((mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample) > (size >> 2)) { mdi->samples_to_mix = size >> 2; } else { mdi->samples_to_mix = mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample; } } } if (__builtin_expect((mdi->samples_to_mix > (size >> 2)), 1)) { real_samples_to_mix = size >> 2; } else { real_samples_to_mix = mdi->samples_to_mix; if (real_samples_to_mix == 0) { continue; } } /* do mixing here */ count = real_samples_to_mix; do { note_data = mdi->note; left_mix = right_mix = 0; RESAMPLE_DEBUGI("SAMPLES_TO_MIX",count); if (__builtin_expect((note_data != NULL), 1)) { RESAMPLE_DEBUGS("Processing Notes"); while (note_data) { /* * =================== * resample the sample * =================== */ data_pos = note_data->sample_pos >> FPBITS; premix = ((note_data->sample->data[data_pos] + (((note_data->sample->data[data_pos + 1] - note_data->sample->data[data_pos]) * (int32_t)(note_data->sample_pos & FPMASK)) / 1024)) * (note_data->env_level >> 12)) / 1024; left_mix += (premix * (int32_t)note_data->left_mix_volume) / 1024; right_mix += (premix * (int32_t)note_data->right_mix_volume) / 1024; /* * ======================== * sample position checking * ======================== */ #ifdef DEBUG_RESAMPLE fprintf(stderr,"\r\n%d -> INC %i, ENV %i, LEVEL %i, TARGET %d, RATE %i, SAMPLE POS %i, SAMPLE LENGTH %i, PREMIX %i (%i:%i)", (uint32_t)note_data, note_data->env_inc, note_data->env, note_data->env_level, note_data->sample->env_target[note_data->env], note_data->sample->env_rate[note_data->env], note_data->sample_pos, note_data->sample->data_length, premix, left_mix, right_mix); if (note_data->modes & SAMPLE_LOOP) fprintf(stderr,", LOOP %i + %i", note_data->sample->loop_start, note_data->sample->loop_size); fprintf(stderr,"\r\n"); #endif note_data->sample_pos += note_data->sample_inc; if (__builtin_expect((note_data->modes & SAMPLE_LOOP), 1)) { if (__builtin_expect( (note_data->sample_pos > note_data->sample->loop_end), 0)) { note_data->sample_pos = note_data->sample->loop_start + ((note_data->sample_pos - note_data->sample->loop_start) % note_data->sample->loop_size); } } else if (__builtin_expect( (note_data->sample_pos >= note_data->sample->data_length), 0)) { goto _END_THIS_NOTE; } if (__builtin_expect((note_data->env_inc == 0), 0)) { note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: 0 env_inc"); continue; } note_data->env_level += note_data->env_inc; if (note_data->env_inc < 0) { if (__builtin_expect((note_data->env_level > note_data->sample->env_target[note_data->env]), 0)) { note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: env_lvl > env_target"); continue; } } else if (note_data->env_inc > 0) { if (__builtin_expect((note_data->env_level < note_data->sample->env_target[note_data->env]), 0)) { note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: env_lvl < env_target"); continue; } } // Yes could have a condition here but // it would crete another bottleneck note_data->env_level = note_data->sample->env_target[note_data->env]; switch (note_data->env) { case 0: if (!(note_data->modes & SAMPLE_ENVELOPE)) { note_data->env_inc = 0; note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: No Envelope"); continue; } break; case 2: if (note_data->modes & SAMPLE_SUSTAIN /*|| note_data->hold*/) { note_data->env_inc = 0; note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: SAMPLE_SUSTAIN"); continue; } else if (note_data->modes & SAMPLE_CLAMPED) { note_data->env = 5; if (note_data->env_level > note_data->sample->env_target[5]) { note_data->env_inc = -note_data->sample->env_rate[5]; } else { note_data->env_inc = note_data->sample->env_rate[5]; } continue; } break; case 5: if (__builtin_expect((note_data->env_level == 0), 1)) { goto _END_THIS_NOTE; } /* sample release */ if (note_data->modes & SAMPLE_LOOP) note_data->modes ^= SAMPLE_LOOP; note_data->env_inc = 0; note_data = note_data->next; RESAMPLE_DEBUGS("Next Note: Sample Release"); continue; case 6: _END_THIS_NOTE: if (__builtin_expect((note_data->replay != NULL), 1)) { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while (nte_array != note_data); } if (prev_note) { prev_note->next = note_data->replay; } else { mdi->note = note_data->replay; } note_data->replay->next = note_data->next; note_data = note_data->replay; note_data->active = 1; } } else { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while ((nte_array != note_data) && (nte_array)); } if (prev_note) { prev_note->next = note_data->next; } else { mdi->note = note_data->next; } note_data = note_data->next; } } RESAMPLE_DEBUGS("Next Note: Killed Off Note"); continue; } note_data->env++; if (note_data->is_off == 1) { _WM_do_note_off_extra(note_data); } else { if (note_data->env_level >= note_data->sample->env_target[note_data->env]) { note_data->env_inc = -note_data->sample->env_rate[note_data->env]; } else { note_data->env_inc = note_data->sample->env_rate[note_data->env]; } } note_data = note_data->next; #ifdef DEBUG_RESAMPLE if (note_data != NULL) RESAMPLE_DEBUGI("Next Note: Next ENV ", note_data->env); else RESAMPLE_DEBUGS("Next Note: Next ENV"); #endif continue; } } *tmp_buffer++ = left_mix; *tmp_buffer++ = right_mix; } while (--count); buffer_used += real_samples_to_mix * 4; size -= (real_samples_to_mix << 2); mdi->extra_info.current_sample += real_samples_to_mix; mdi->samples_to_mix -= real_samples_to_mix; } while (size); tmp_buffer = out_buffer; if (mdi->extra_info.mixer_options & WM_MO_REVERB) { _WM_do_reverb(mdi->reverb, tmp_buffer, (buffer_used / 2)); } //_WM_DynamicVolumeAdjust(mdi, tmp_buffer, (buffer_used/2)); for (i = 0; i < buffer_used; i += 4) { left_mix = *tmp_buffer++; right_mix = *tmp_buffer++; /* * =================== * Write to the buffer * =================== */ #ifdef WORDS_BIGENDIAN (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = left_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; #else (*buffer++) = left_mix & 0xff; (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); #endif } _WM_Unlock(&mdi->lock); return (buffer_used); } static int WM_GetOutput_Gauss(midi * handle, int8_t *buffer, uint32_t size) { uint32_t buffer_used = 0; uint32_t i; struct _mdi *mdi = (struct _mdi *) handle; uint32_t real_samples_to_mix = 0; uint32_t data_pos; int32_t premix, left_mix, right_mix; struct _note *note_data = NULL; uint32_t count; int16_t *sptr; double y, xd; double *gptr, *gend; int left, right, temp_n; int ii, jj; struct _event *event = mdi->current_event; int32_t *tmp_buffer; int32_t *out_buffer; _WM_Lock(&mdi->lock); buffer_used = 0; memset(buffer, 0, size); if ( (size / 2) > mdi->mix_buffer_size) { if ( (size / 2) <= ( mdi->mix_buffer_size * 2 )) { mdi->mix_buffer_size += MEM_CHUNK; } else { mdi->mix_buffer_size = size / 2; } mdi->mix_buffer = realloc(mdi->mix_buffer, mdi->mix_buffer_size * sizeof(int32_t)); } tmp_buffer = mdi->mix_buffer; memset(tmp_buffer, 0, ((size / 2) * sizeof(int32_t))); out_buffer = tmp_buffer; do { if (__builtin_expect((!mdi->samples_to_mix), 0)) { while ((!mdi->samples_to_mix) && (event->do_event)) { event->do_event(mdi, &event->event_data); if ((mdi->extra_info.mixer_options & WM_MO_LOOP) && (event[0].do_event == *_WM_do_meta_endoftrack)) { _WM_ResetToStart(mdi); event = mdi->current_event; } else { mdi->samples_to_mix = event->samples_to_next; event++; mdi->current_event = event; } } if (!mdi->samples_to_mix) { if (mdi->extra_info.current_sample >= mdi->extra_info.approx_total_samples) { break; } else if ((mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample) > (size >> 2)) { mdi->samples_to_mix = size >> 2; } else { mdi->samples_to_mix = mdi->extra_info.approx_total_samples - mdi->extra_info.current_sample; } } } if (__builtin_expect((mdi->samples_to_mix > (size >> 2)), 1)) { real_samples_to_mix = size >> 2; } else { real_samples_to_mix = mdi->samples_to_mix; if (real_samples_to_mix == 0) { continue; } } /* do mixing here */ count = real_samples_to_mix; do { note_data = mdi->note; left_mix = right_mix = 0; if (__builtin_expect((note_data != NULL), 1)) { while (note_data) { /* * =================== * resample the sample * =================== */ data_pos = note_data->sample_pos >> FPBITS; /* check to see if we're near one of the ends */ left = data_pos; right = (note_data->sample->data_length >> FPBITS) - left - 1; temp_n = (right << 1) - 1; if (temp_n <= 0) temp_n = 1; if (temp_n > (left << 1) + 1) temp_n = (left << 1) + 1; /* use Newton if we can't fill the window */ if (temp_n < gauss_n) { xd = note_data->sample_pos & FPMASK; xd /= (1L << FPBITS); xd += temp_n >> 1; y = 0; sptr = note_data->sample->data + (note_data->sample_pos >> FPBITS) - (temp_n >> 1); for (ii = temp_n; ii;) { for (jj = 0; jj <= ii; jj++) y += sptr[jj] * newt_coeffs[ii][jj]; y *= xd - --ii; } y += *sptr; } else { /* otherwise, use Gauss as usual */ y = 0; gptr = &gauss_table[(note_data->sample_pos & FPMASK) * (gauss_n + 1)]; gend = gptr + gauss_n; sptr = note_data->sample->data + (note_data->sample_pos >> FPBITS) - (gauss_n >> 1); do { y += *(sptr++) * *(gptr++); } while (gptr <= gend); } premix = (int32_t)((y * (note_data->env_level >> 12)) / 1024); left_mix += (premix * (int32_t)note_data->left_mix_volume) / 1024; right_mix += (premix * (int32_t)note_data->right_mix_volume) / 1024; /* * ======================== * sample position checking * ======================== */ note_data->sample_pos += note_data->sample_inc; if (__builtin_expect( (note_data->sample_pos > note_data->sample->loop_end), 0)) { if (note_data->modes & SAMPLE_LOOP) { note_data->sample_pos = note_data->sample->loop_start + ((note_data->sample_pos - note_data->sample->loop_start) % note_data->sample->loop_size); } else if (__builtin_expect( (note_data->sample_pos >= note_data->sample->data_length), 0)) { goto _END_THIS_NOTE; } } if (__builtin_expect((note_data->env_inc == 0), 0)) { /* fprintf(stderr,"\r\nINC = 0, ENV %i, LEVEL %i, TARGET %d, RATE %i\r\n", note_data->env, note_data->env_level, note_data->sample->env_target[note_data->env], note_data->sample->env_rate[note_data->env]); */ note_data = note_data->next; continue; } note_data->env_level += note_data->env_inc; /* fprintf(stderr,"\r\nENV %i, LEVEL %i, TARGET %d, RATE %i, INC %i\r\n", note_data->env, note_data->env_level, note_data->sample->env_target[note_data->env], note_data->sample->env_rate[note_data->env], note_data->env_inc); */ if (note_data->env_inc < 0) { if (note_data->env_level > note_data->sample->env_target[note_data->env]) { note_data = note_data->next; continue; } } else if (note_data->env_inc > 0) { if (note_data->env_level < note_data->sample->env_target[note_data->env]) { note_data = note_data->next; continue; } } // Yes could have a condition here but // it would crete another bottleneck note_data->env_level = note_data->sample->env_target[note_data->env]; switch (note_data->env) { case 0: if (!(note_data->modes & SAMPLE_ENVELOPE)) { note_data->env_inc = 0; note_data = note_data->next; continue; } break; case 2: if (note_data->modes & SAMPLE_SUSTAIN /*|| note_data->hold*/) { note_data->env_inc = 0; note_data = note_data->next; continue; } else if (note_data->modes & SAMPLE_CLAMPED) { note_data->env = 5; if (note_data->env_level > note_data->sample->env_target[5]) { note_data->env_inc = -note_data->sample->env_rate[5]; } else { note_data->env_inc = note_data->sample->env_rate[5]; } continue; } break; case 5: if (__builtin_expect((note_data->env_level == 0), 1)) { goto _END_THIS_NOTE; } /* sample release */ if (note_data->modes & SAMPLE_LOOP) note_data->modes ^= SAMPLE_LOOP; note_data->env_inc = 0; note_data = note_data->next; continue; case 6: _END_THIS_NOTE: if (__builtin_expect((note_data->replay != NULL), 1)) { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while (nte_array != note_data); } if (prev_note) { prev_note->next = note_data->replay; } else { mdi->note = note_data->replay; } note_data->replay->next = note_data->next; note_data = note_data->replay; note_data->active = 1; } } else { note_data->active = 0; { struct _note *prev_note = NULL; struct _note *nte_array = mdi->note; if (nte_array != note_data) { do { prev_note = nte_array; nte_array = nte_array->next; } while ((nte_array != note_data) && (nte_array)); } if (prev_note) { prev_note->next = note_data->next; } else { mdi->note = note_data->next; } note_data = note_data->next; } } continue; } note_data->env++; if (note_data->is_off == 1) { _WM_do_note_off_extra(note_data); } else { if (note_data->env_level >= note_data->sample->env_target[note_data->env]) { note_data->env_inc = -note_data->sample->env_rate[note_data->env]; } else { note_data->env_inc = note_data->sample->env_rate[note_data->env]; } } note_data = note_data->next; continue; } } *tmp_buffer++ = left_mix; *tmp_buffer++ = right_mix; } while (--count); buffer_used += real_samples_to_mix * 4; size -= (real_samples_to_mix << 2); mdi->extra_info.current_sample += real_samples_to_mix; mdi->samples_to_mix -= real_samples_to_mix; } while (size); tmp_buffer = out_buffer; if (mdi->extra_info.mixer_options & WM_MO_REVERB) { _WM_do_reverb(mdi->reverb, tmp_buffer, (buffer_used / 2)); } // _WM_DynamicVolumeAdjust(mdi, tmp_buffer, (buffer_used/2)); for (i = 0; i < buffer_used; i += 4) { left_mix = *tmp_buffer++; right_mix = *tmp_buffer++; /* * =================== * Write to the buffer * =================== */ #ifdef WORDS_BIGENDIAN (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = left_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; #else (*buffer++) = left_mix & 0xff; (*buffer++) = ((left_mix >> 8) & 0x7f) | ((left_mix >> 24) & 0x80); (*buffer++) = right_mix & 0xff; (*buffer++) = ((right_mix >> 8) & 0x7f) | ((right_mix >> 24) & 0x80); #endif } _WM_Unlock(&mdi->lock); return (buffer_used); } /* * ========================= * External Functions * ========================= */ WM_SYMBOL int WildMidi_ConvertToMidi (const char *file, uint8_t **out, uint32_t *size) { uint8_t *buf; int ret; if (!file) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0); return (-1); } if ((buf = (uint8_t *) _WM_BufferFile(file, size)) == NULL) { return (-1); } ret = WildMidi_ConvertBufferToMidi(buf, *size, out, size); free(buf); return ret; } WM_SYMBOL int WildMidi_ConvertBufferToMidi (uint8_t *in, uint32_t insize, uint8_t **out, uint32_t *outsize) { if (!in || !out || !outsize) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL params)", 0); return (-1); } if (!memcmp(in, "FORM", 4)) { if (_WM_xmi2midi(in, insize, out, outsize, _cvt_get_option(WM_CO_XMI_TYPE)) < 0) { return (-1); } } else if (!memcmp(in, "MUS", 3)) { if (_WM_mus2midi(in, insize, out, outsize, _cvt_get_option(WM_CO_FREQUENCY)) < 0) { return (-1); } } else if (!memcmp(in, "MThd", 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, 0, "Already a midi file", 0); return (-1); } else { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0); return (-1); } return (0); } WM_SYMBOL const char *WildMidi_GetString(uint16_t info) { static char WM_Version[] = "WildMidi Processing Library " PACKAGE_VERSION; switch (info) { case WM_GS_VERSION: return WM_Version; } return NULL; } WM_SYMBOL long WildMidi_GetVersion (void) { return (LIBWILDMIDI_VERSION); } WM_SYMBOL int WildMidi_Init(const char *config_file, uint16_t rate, uint16_t mixer_options) { if (WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_ALR_INIT, NULL, 0); return (-1); } if (config_file == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL config file pointer)", 0); return (-1); } WM_InitPatches(); if (WM_LoadConfig(config_file) == -1) { return (-1); } if (mixer_options & 0x0FF0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid option)", 0); WM_FreePatches(); return (-1); } _WM_MixerOptions = mixer_options; if (rate < 11025) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(rate out of bounds, range is 11025 - 65535)", 0); WM_FreePatches(); return (-1); } _WM_SampleRate = rate; gauss_lock = 0; _WM_patch_lock = 0; _WM_MasterVolume = 948; WM_Initialized = 1; return (0); } WM_SYMBOL int WildMidi_MasterVolume(uint8_t master_volume) { if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (master_volume > 127) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(master volume out of range, range is 0-127)", 0); return (-1); } _WM_MasterVolume = _WM_lin_volume[master_volume]; return (0); } WM_SYMBOL int WildMidi_Close(midi * handle) { struct _mdi *mdi = (struct _mdi *) handle; struct _hndl * tmp_handle; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (first_handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(no midi's open)", 0); return (-1); } _WM_Lock(&mdi->lock); if (first_handle->handle == handle) { tmp_handle = first_handle->next; free(first_handle); first_handle = tmp_handle; if (first_handle) first_handle->prev = NULL; } else { tmp_handle = first_handle; while (tmp_handle->handle != handle) { tmp_handle = tmp_handle->next; if (tmp_handle == NULL) { break; } } if (tmp_handle) { tmp_handle->prev->next = tmp_handle->next; if (tmp_handle->next) { tmp_handle->next->prev = tmp_handle->prev; } free(tmp_handle); } } _WM_freeMDI(mdi); return (0); } WM_SYMBOL midi *WildMidi_Open(const char *midifile) { uint8_t *mididata = NULL; uint32_t midisize = 0; uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midifile == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0); return (NULL); } if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) { return (NULL); } if (memcmp(mididata,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(mididata, midisize); } else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(mididata, midisize); } else if (memcmp(mididata, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(mididata, midisize); } else if (memcmp(mididata, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(mididata, midisize); } else { ret = (void *) _WM_ParseNewMidi(mididata, midisize); } free(mididata); if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midibuffer == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0); return (NULL); } if (size > WM_MAXFILESIZE) { /* don't bother loading suspiciously long files */ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0); return (NULL); } if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(midibuffer, size); } else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(midibuffer, size); } else if (memcmp(midibuffer, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(midibuffer, size); } else if (memcmp(midibuffer, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(midibuffer, size); } else { ret = (void *) _WM_ParseNewMidi(midibuffer, size); } if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } WM_SYMBOL int WildMidi_FastSeek(midi * handle, unsigned long int *sample_pos) { struct _mdi *mdi; struct _event *event; struct _note *note_data; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (sample_pos == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL seek position pointer)", 0); return (-1); } mdi = (struct _mdi *) handle; _WM_Lock(&mdi->lock); event = mdi->current_event; /* make sure we havent asked for a positions beyond the end of the song. */ if (*sample_pos > mdi->extra_info.approx_total_samples) { /* if so set the position to the end of the song */ *sample_pos = mdi->extra_info.approx_total_samples; } /* was end of song requested and are we are there? */ if (*sample_pos == mdi->extra_info.approx_total_samples) { /* yes */ _WM_Unlock(&mdi->lock); return (0); } /* did we want to fast forward? */ if (mdi->extra_info.current_sample > *sample_pos) { /* no - reset some stuff */ event = mdi->events; _WM_ResetToStart(handle); mdi->extra_info.current_sample = 0; mdi->samples_to_mix = 0; } if ((mdi->extra_info.current_sample + mdi->samples_to_mix) > *sample_pos) { mdi->samples_to_mix = (mdi->extra_info.current_sample + mdi->samples_to_mix) - *sample_pos; mdi->extra_info.current_sample = *sample_pos; } else { mdi->extra_info.current_sample += mdi->samples_to_mix; mdi->samples_to_mix = 0; while ((!mdi->samples_to_mix) && (event->do_event)) { event->do_event(mdi, &event->event_data); mdi->samples_to_mix = event->samples_to_next; if ((mdi->extra_info.current_sample + mdi->samples_to_mix) > *sample_pos) { mdi->samples_to_mix = (mdi->extra_info.current_sample + mdi->samples_to_mix) - *sample_pos; mdi->extra_info.current_sample = *sample_pos; } else { mdi->extra_info.current_sample += mdi->samples_to_mix; mdi->samples_to_mix = 0; } event++; } mdi->current_event = event; } /* * Clear notes as this is a fast seek so we only care * about new notes. * * NOTE: This function is for performance only. * Might need a WildMidi_SlowSeek if we need better accuracy. */ note_data = mdi->note; if (note_data) { do { note_data->active = 0; if (note_data->replay) { note_data->replay = NULL; } note_data = note_data->next; } while (note_data); } mdi->note = NULL; /* clear the reverb buffers since we not gonna be using them here */ _WM_reset_reverb(mdi->reverb); _WM_Unlock(&mdi->lock); return (0); } WM_SYMBOL int WildMidi_SongSeek (midi * handle, int8_t nextsong) { struct _mdi *mdi; struct _event *event; struct _event *event_new; struct _note *note_data; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } mdi = (struct _mdi *) handle; _WM_Lock(&mdi->lock); if ((!mdi->is_type2) && (nextsong != 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(Illegal use. Only usable with files detected to be type 2 compatible.", 0); _WM_Unlock(&mdi->lock); return (-1); } if ((nextsong > 1) || (nextsong < -1)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(Invalid nextsong setting. -1 is previous song, 0 start of current song, 1 is next song)", 0); _WM_Unlock(&mdi->lock); return (-1); } event = mdi->current_event; if (nextsong == -1) { /* goto start of previous song */ /* * So with this one we have to go back 2 eof's * then forward 1 event to get to the start of * the previous song. * NOTE: We will automatically stop at the start * of the data. */ uint8_t eof_cnt = 1; while (event != mdi->events) { if (event[-1].do_event == _WM_do_meta_endoftrack) { if (eof_cnt == 0) { break; } eof_cnt = 0; } event--; } event_new = event; event = mdi->events; _WM_ResetToStart(handle); } else if (nextsong == 1) { /* goto start of next song */ while (event->do_event != NULL) { if (event->do_event == _WM_do_meta_endoftrack) { event++; if (event->do_event == NULL) { event--; goto START_THIS_SONG; } else { break; } } event++; } event_new = event; event = mdi->current_event; } else { START_THIS_SONG: /* goto start of this song */ /* first find the offset */ while (event != mdi->events) { if (event[-1].do_event == _WM_do_meta_endoftrack) { break; } event--; } event_new = event; event = mdi->events; _WM_ResetToStart(handle); } while (event != event_new) { event->do_event(mdi, &event->event_data); mdi->extra_info.current_sample += event->samples_to_next; event++; } mdi->current_event = event; note_data = mdi->note; if (note_data) { do { note_data->active = 0; if (note_data->replay) { note_data->replay = NULL; } note_data = note_data->next; } while (note_data); } mdi->note = NULL; _WM_Unlock(&mdi->lock); return (0); } WM_SYMBOL int WildMidi_GetOutput(midi * handle, int8_t *buffer, uint32_t size) { if (__builtin_expect((!WM_Initialized), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (__builtin_expect((handle == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (__builtin_expect((buffer == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL buffer pointer)", 0); return (-1); } if (__builtin_expect((size == 0), 0)) { return (0); } if (__builtin_expect((!!(size % 4)), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(size not a multiple of 4)", 0); return (-1); } if (((struct _mdi *) handle)->extra_info.mixer_options & WM_MO_ENHANCED_RESAMPLING) { if (!gauss_table) init_gauss(); return (WM_GetOutput_Gauss(handle, buffer, size)); } return (WM_GetOutput_Linear(handle, buffer, size)); } WM_SYMBOL int WildMidi_GetMidiOutput(midi * handle, int8_t **buffer, uint32_t *size) { if (__builtin_expect((!WM_Initialized), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (__builtin_expect((handle == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } if (__builtin_expect((buffer == NULL), 0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL buffer pointer)", 0); return (-1); } return _WM_Event2Midi(handle, (uint8_t **)buffer, size); } WM_SYMBOL int WildMidi_SetOption(midi * handle, uint16_t options, uint16_t setting) { struct _mdi *mdi; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (-1); } mdi = (struct _mdi *) handle; _WM_Lock(&mdi->lock); if ((!(options & 0x800F)) || (options & 0x7FF0)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid option)", 0); _WM_Unlock(&mdi->lock); return (-1); } if (setting & 0x7FF0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid setting)", 0); _WM_Unlock(&mdi->lock); return (-1); } mdi->extra_info.mixer_options = ((mdi->extra_info.mixer_options & (0x80FF ^ options)) | (options & setting)); if (options & WM_MO_LOG_VOLUME) { _WM_AdjustChannelVolumes(mdi, 16); // Settings greater than 15 // adjusts all channels } else if (options & WM_MO_REVERB) { _WM_reset_reverb(mdi->reverb); } _WM_Unlock(&mdi->lock); return (0); } WM_SYMBOL int WildMidi_SetCvtOption(uint16_t tag, uint16_t setting) { _WM_Lock(&WM_ConvertOptions.lock); switch (tag) { case WM_CO_XMI_TYPE: /* validation happens in xmidi.c */ WM_ConvertOptions.xmi_convert_type = setting; break; case WM_CO_FREQUENCY: /* validation happens in format */ WM_ConvertOptions.frequency = setting; break; default: _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid setting)", 0); _WM_Unlock(&WM_ConvertOptions.lock); return (-1); } _WM_Unlock(&WM_ConvertOptions.lock); return (0); } WM_SYMBOL struct _WM_Info * WildMidi_GetInfo(midi * handle) { struct _mdi *mdi = (struct _mdi *) handle; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (NULL); } _WM_Lock(&mdi->lock); if (mdi->tmp_info == NULL) { mdi->tmp_info = malloc(sizeof(struct _WM_Info)); if (mdi->tmp_info == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to set info", 0); _WM_Unlock(&mdi->lock); return (NULL); } mdi->tmp_info->copyright = NULL; } mdi->tmp_info->current_sample = mdi->extra_info.current_sample; mdi->tmp_info->approx_total_samples = mdi->extra_info.approx_total_samples; mdi->tmp_info->mixer_options = mdi->extra_info.mixer_options; mdi->tmp_info->total_midi_time = (mdi->tmp_info->approx_total_samples * 1000) / _WM_SampleRate; if (mdi->extra_info.copyright) { free(mdi->tmp_info->copyright); mdi->tmp_info->copyright = malloc(strlen(mdi->extra_info.copyright) + 1); if (mdi->tmp_info->copyright == NULL) { free(mdi->tmp_info); mdi->tmp_info = NULL; _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to set copyright", 0); _WM_Unlock(&mdi->lock); return (NULL); } else { strcpy(mdi->tmp_info->copyright, mdi->extra_info.copyright); } } else { mdi->tmp_info->copyright = NULL; } _WM_Unlock(&mdi->lock); return ((struct _WM_Info *)mdi->tmp_info); } WM_SYMBOL int WildMidi_Shutdown(void) { if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (-1); } while (first_handle) { /* closes open handle and rotates the handles list. */ WildMidi_Close((struct _mdi *) first_handle->handle); } WM_FreePatches(); free_gauss(); /* reset the globals */ _cvt_reset_options (); _WM_MasterVolume = 948; _WM_MixerOptions = 0; _WM_fix_release = 0; _WM_auto_amp = 0; _WM_auto_amp_with_amp = 0; _WM_reverb_room_width = 16.875f; _WM_reverb_room_length = 22.5f; _WM_reverb_listen_posx = 8.4375f; _WM_reverb_listen_posy = 16.875f; WM_Initialized = 0; if (_WM_Global_ErrorS != NULL) free(_WM_Global_ErrorS); return (0); } /* char * WildMidi_GetLyric(midi * handle) Returns points to a \0 terminated string that contains the data contained in the last read lyric or text meta event. Or returns NULL if no lyric is waiting to be read. Force read from text meta event by including WM_MO_TEXTASLYRIC in the options in WildMidi_Init. Programs calling this only need to read the pointer. Cleanup is done by the lib. Once WildMidi_GetLyric is called it will return NULL on subsiquent calls until the next lyric event is processed during a WildMidi_GetOutput call. */ WM_SYMBOL char * WildMidi_GetLyric (midi * handle) { struct _mdi *mdi = (struct _mdi *) handle; char * lyric = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (handle == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0); return (NULL); } _WM_Lock(&mdi->lock); lyric = mdi->lyric; mdi->lyric = NULL; _WM_Unlock(&mdi->lock); return (lyric); } /* * Return Last Error Message */ WM_SYMBOL char * WildMidi_GetError (void) { return (_WM_Global_ErrorS); } /* * Clear any error message */ WM_SYMBOL void WildMidi_ClearError (void) { _WM_Global_ErrorI = 0; if (_WM_Global_ErrorS != NULL) { free(_WM_Global_ErrorS); _WM_Global_ErrorS = NULL; } return; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2529_1
crossvul-cpp_data_good_5252_0
/* Mac-Telnet - Connect to RouterOS or mactelnetd devices via MAC address Copyright (C) 2010, Håkon Nessjøen <haakon.nessjoen@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #define _BSD_SOURCE #include <libintl.h> #include <locale.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pwd.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #if defined(__APPLE__) # include <libkern/OSByteOrder.h> # define htole16 OSSwapHostToLittleInt16 #elif defined(__FreeBSD__) #include <sys/endian.h> #else #include <endian.h> #endif #if defined(__FreeBSD__) || defined(__APPLE__) #include <sys/types.h> #include <net/ethernet.h> #else #include <netinet/ether.h> #endif #include <arpa/inet.h> #include <netinet/in.h> #include <sys/time.h> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #ifdef __linux__ #include <linux/if_ether.h> #include <sys/mman.h> #endif #include "md5.h" #include "protocol.h" #include "console.h" #include "interfaces.h" #include "config.h" #include "mactelnet.h" #include "mndp.h" #include "autologin.h" #include "utlist.h" #define PROGRAM_NAME "MAC-Telnet" #define _(String) gettext (String) static int sockfd = 0; static int insockfd; static unsigned int outcounter = 0; static long incounter = -1; static int sessionkey = 0; static int running = 1; static unsigned char use_raw_socket = 0; static unsigned char terminal_mode = 0; static unsigned char srcmac[ETH_ALEN]; static unsigned char dstmac[ETH_ALEN]; static struct in_addr sourceip; static struct in_addr destip; static int sourceport; static int connect_timeout = CONNECT_TIMEOUT; static char run_mndp = 0; static int mndp_timeout = 0; static int is_a_tty = 1; static int quiet_mode = 0; static int batch_mode = 0; static int no_autologin = 0; static char autologin_path[255]; static int keepalive_counter = 0; static unsigned char pass_salt[16]; static char username[MT_MNDP_MAX_STRING_SIZE]; static char password[MT_MNDP_MAX_STRING_SIZE]; static char nonpriv_username[MT_MNDP_MAX_STRING_SIZE]; struct net_interface *interfaces=NULL; struct net_interface *active_interface; /* Protocol data direction */ unsigned char mt_direction_fromserver = 0; static unsigned int send_socket; static int handle_packet(unsigned char *data, int data_len); static void print_version() { fprintf(stderr, PROGRAM_NAME " " PROGRAM_VERSION "\n"); } void drop_privileges(char *username) { struct passwd *user = (struct passwd *) getpwnam(username); if (user == NULL) { fprintf(stderr, _("Failed dropping privileges. The user %s is not a valid username on local system.\n"), username); exit(1); } if (getuid() == 0) { /* process is running as root, drop privileges */ if (setgid(user->pw_gid) != 0) { fprintf(stderr, _("setgid: Error dropping group privileges\n")); exit(1); } if (setuid(user->pw_uid) != 0) { fprintf(stderr, _("setuid: Error dropping user privileges\n")); exit(1); } /* Verify if the privileges were developed. */ if (setuid(0) != -1) { fprintf(stderr, _("Failed to drop privileges\n")); exit(1); } } } static int send_udp(struct mt_packet *packet, int retransmit) { int sent_bytes; /* Clear keepalive counter */ keepalive_counter = 0; if (!use_raw_socket) { /* Init SendTo struct */ struct sockaddr_in socket_address; socket_address.sin_family = AF_INET; socket_address.sin_port = htons(MT_MACTELNET_PORT); socket_address.sin_addr.s_addr = htonl(INADDR_BROADCAST); sent_bytes = sendto(send_socket, packet->data, packet->size, 0, (struct sockaddr*)&socket_address, sizeof(socket_address)); } else { sent_bytes = net_send_udp(sockfd, active_interface, srcmac, dstmac, &sourceip, sourceport, &destip, MT_MACTELNET_PORT, packet->data, packet->size); } /* * Retransmit packet if no data is received within * retransmit_intervals milliseconds. */ if (retransmit) { int i; for (i = 0; i < MAX_RETRANSMIT_INTERVALS; ++i) { fd_set read_fds; int reads; struct timeval timeout; int interval = retransmit_intervals[i] * 1000; /* Init select */ FD_ZERO(&read_fds); FD_SET(insockfd, &read_fds); timeout.tv_sec = 0; timeout.tv_usec = interval; /* Wait for data or timeout */ reads = select(insockfd + 1, &read_fds, NULL, NULL, &timeout); if (reads && FD_ISSET(insockfd, &read_fds)) { unsigned char buff[MT_PACKET_LEN]; int result; bzero(buff, sizeof(buff)); result = recvfrom(insockfd, buff, sizeof(buff), 0, 0, 0); /* Handle incoming packets, waiting for an ack */ if (result > 0 && handle_packet(buff, result) == MT_PTYPE_ACK) { return sent_bytes; } } /* Retransmit */ send_udp(packet, 0); } if (is_a_tty && terminal_mode) { reset_term(); } fprintf(stderr, _("\nConnection timed out\n")); exit(1); } return sent_bytes; } static void send_auth(char *username, char *password) { struct mt_packet data; unsigned short width = 0; unsigned short height = 0; char *terminal = getenv("TERM"); char md5data[100]; unsigned char md5sum[17]; int plen, act_pass_len; md5_state_t state; #if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE) mlock(md5data, sizeof(md5data)); mlock(md5sum, sizeof(md5data)); #endif /* calculate the actual password's length */ act_pass_len = strnlen(password, 82); /* Concat string of 0 + password + pass_salt */ md5data[0] = 0; memcpy(md5data + 1, password, act_pass_len); /* in case that password is long, calculate only using the used-up parts */ memcpy(md5data + 1 + act_pass_len, pass_salt, 16); /* Generate md5 sum of md5data with a leading 0 */ md5_init(&state); md5_append(&state, (const md5_byte_t *)md5data, 1 + act_pass_len + 16); md5_finish(&state, (md5_byte_t *)md5sum + 1); md5sum[0] = 0; /* Send combined packet to server */ init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter); plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17); plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username)); plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal)); if (is_a_tty && get_terminal_size(&width, &height) != -1) { width = htole16(width); height = htole16(height); plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2); plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2); } outcounter += plen; /* TODO: handle result */ send_udp(&data, 1); } static void sig_winch(int sig) { unsigned short width,height; struct mt_packet data; int plen; /* terminal height/width has changed, inform server */ if (get_terminal_size(&width, &height) != -1) { init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter); width = htole16(width); height = htole16(height); plen = add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2); plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2); outcounter += plen; send_udp(&data, 1); } /* reinstate signal handler */ signal(SIGWINCH, sig_winch); } static int handle_packet(unsigned char *data, int data_len) { struct mt_mactelnet_hdr pkthdr; /* Minimal size checks (pings are not supported here) */ if (data_len < MT_HEADER_LEN){ return -1; } parse_packet(data, &pkthdr); /* We only care about packets with correct sessionkey */ if (pkthdr.seskey != sessionkey) { return -1; } /* Handle data packets */ if (pkthdr.ptype == MT_PTYPE_DATA) { struct mt_packet odata; struct mt_mactelnet_control_hdr cpkt; int success = 0; /* Always transmit ACKNOWLEDGE packets in response to DATA packets */ init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN)); send_udp(&odata, 0); /* Accept first packet, and all packets greater than incounter, and if counter has wrapped around. */ if (pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) { incounter = pkthdr.counter; } else { /* Ignore double or old packets */ return -1; } /* Parse controlpacket data */ success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt); while (success) { /* If we receive pass_salt, transmit auth data back */ if (cpkt.cptype == MT_CPTYPE_PASSSALT) { /* check validity, server sends exactly 16 bytes */ if (cpkt.length != 16) { fprintf(stderr, _("Invalid salt length: %d (instead of 16) received from server %s\n"), cpkt.length, ether_ntoa((struct ether_addr *)dstmac)); } memcpy(pass_salt, cpkt.data, 16); send_auth(username, password); } /* If the (remaining) data did not have a control-packet magic byte sequence, the data is raw terminal data to be outputted to the terminal. */ else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) { fwrite((const void *)cpkt.data, 1, cpkt.length, stdout); } /* END_AUTH means that the user/password negotiation is done, and after this point terminal data may arrive, so we set up the terminal to raw mode. */ else if (cpkt.cptype == MT_CPTYPE_END_AUTH) { /* we have entered "terminal mode" */ terminal_mode = 1; if (is_a_tty) { /* stop input buffering at all levels. Give full control of terminal to RouterOS */ raw_term(); setvbuf(stdin, (char*)NULL, _IONBF, 0); /* Add resize signal handler */ signal(SIGWINCH, sig_winch); } } /* Parse next controlpacket */ success = parse_control_packet(NULL, 0, &cpkt); } } else if (pkthdr.ptype == MT_PTYPE_ACK) { /* Handled elsewhere */ } /* The server wants to terminate the connection, we have to oblige */ else if (pkthdr.ptype == MT_PTYPE_END) { struct mt_packet odata; /* Acknowledge the disconnection by sending a END packet in return */ init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0); send_udp(&odata, 0); if (!quiet_mode) { fprintf(stderr, _("Connection closed.\n")); } /* exit */ running = 0; } else { fprintf(stderr, _("Unhandeled packet type: %d received from server %s\n"), pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac)); return -1; } return pkthdr.ptype; } static int find_interface() { fd_set read_fds; struct mt_packet data; struct sockaddr_in myip; unsigned char emptymac[ETH_ALEN]; int testsocket; struct timeval timeout; int optval = 1; struct net_interface *interface; /* TODO: reread interfaces on HUP */ //bzero(&interfaces, sizeof(struct net_interface) * MAX_INTERFACES); bzero(emptymac, ETH_ALEN); if (net_get_interfaces(&interfaces) <= 0) { fprintf(stderr, _("Error: No suitable devices found\n")); exit(1); } DL_FOREACH(interfaces, interface) { /* Skip loopback interfaces */ if (memcmp("lo", interface->name, 2) == 0) { continue; } /* Initialize receiving socket on the device chosen */ myip.sin_family = AF_INET; memcpy((void *)&myip.sin_addr, interface->ipv4_addr, IPV4_ALEN); myip.sin_port = htons(sourceport); /* Initialize socket and bind to udp port */ if ((testsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { continue; } setsockopt(testsocket, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)); setsockopt(testsocket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (bind(testsocket, (struct sockaddr *)&myip, sizeof(struct sockaddr_in)) == -1) { close(testsocket); continue; } /* Ensure that we have mac-address for this interface */ if (!interface->has_mac) { close(testsocket); continue; } /* Set the global socket handle and source mac address for send_udp() */ send_socket = testsocket; memcpy(srcmac, interface->mac_addr, ETH_ALEN); active_interface = interface; /* Send a SESSIONSTART message with the current device */ init_packet(&data, MT_PTYPE_SESSIONSTART, srcmac, dstmac, sessionkey, 0); send_udp(&data, 0); timeout.tv_sec = connect_timeout; timeout.tv_usec = 0; FD_ZERO(&read_fds); FD_SET(insockfd, &read_fds); select(insockfd + 1, &read_fds, NULL, NULL, &timeout); if (FD_ISSET(insockfd, &read_fds)) { /* We got a response, this is the correct device to use */ return 1; } close(testsocket); } return 0; } /* * TODO: Rewrite main() when all sub-functionality is tested */ int main (int argc, char **argv) { int result; struct mt_packet data; struct sockaddr_in si_me; struct autologin_profile *login_profile; struct net_interface *interface, *tmp; unsigned char buff[MT_PACKET_LEN]; unsigned char print_help = 0, have_username = 0, have_password = 0; unsigned char drop_priv = 0; int c; int optval = 1; strncpy(autologin_path, AUTOLOGIN_PATH, sizeof(autologin_path)); setlocale(LC_ALL, ""); bindtextdomain("mactelnet","/usr/share/locale"); textdomain("mactelnet"); while (1) { c = getopt(argc, argv, "lnqt:u:p:U:vh?BAa:"); if (c == -1) { break; } switch (c) { case 'n': use_raw_socket = 1; break; case 'u': /* Save username */ strncpy(username, optarg, sizeof(username) - 1); username[sizeof(username) - 1] = '\0'; have_username = 1; break; case 'p': /* Save password */ #if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE) mlock(password, sizeof(password)); #endif strncpy(password, optarg, sizeof(password) - 1); password[sizeof(password) - 1] = '\0'; have_password = 1; break; case 'U': /* Save nonpriv_username */ strncpy(nonpriv_username, optarg, sizeof(nonpriv_username) - 1); nonpriv_username[sizeof(nonpriv_username) - 1] = '\0'; drop_priv = 1; break; case 't': connect_timeout = atoi(optarg); mndp_timeout = connect_timeout; break; case 'v': print_version(); exit(0); break; case 'q': quiet_mode = 1; break; case 'l': run_mndp = 1; break; case 'B': batch_mode = 1; break; case 'A': no_autologin = 1; break; case 'a': strncpy(autologin_path, optarg, sizeof(autologin_path) - 1); autologin_path[sizeof(autologin_path) - 1] = '\0'; break; case 'h': case '?': print_help = 1; break; } } if (run_mndp) { return mndp(mndp_timeout, batch_mode); } if (argc - optind < 1 || print_help) { print_version(); fprintf(stderr, _("Usage: %s <MAC|identity> [-h] [-n] [-a <path>] [-A] [-t <timeout>] [-u <user>] [-p <password>] [-U <user>] | -l [-B] [-t <timeout>]\n"), argv[0]); if (print_help) { fprintf(stderr, _("\nParameters:\n" " MAC MAC-Address of the RouterOS/mactelnetd device. Use mndp to\n" " discover it.\n" " identity The identity/name of your destination device. Uses\n" " MNDP protocol to find it.\n" " -l List/Search for routers nearby (MNDP). You may use -t to set timeout.\n" " -B Batch mode. Use computer readable output (CSV), for use with -l.\n" " -n Do not use broadcast packets. Less insecure but requires\n" " root privileges.\n" " -a <path> Use specified path instead of the default: " AUTOLOGIN_PATH " for autologin config file.\n" " -A Disable autologin feature.\n" " -t <timeout> Amount of seconds to wait for a response on each interface.\n" " -u <user> Specify username on command line.\n" " -p <password> Specify password on command line.\n" " -U <user> Drop privileges to this user. Used in conjunction with -n\n" " for security.\n" " -q Quiet mode.\n" " -h This help.\n" "\n")); } return 1; } is_a_tty = isatty(fileno(stdout)) && isatty(fileno(stdin)); if (!is_a_tty) { quiet_mode = 1; } if (!no_autologin) { autologin_readfile(autologin_path); login_profile = autologin_find_profile(argv[optind]); if (!quiet_mode && login_profile != NULL && (login_profile->hasUsername || login_profile->hasPassword)) { fprintf(stderr, _("Using autologin credentials from %s\n"), autologin_path); } if (!have_username) { if (login_profile != NULL && login_profile->hasUsername) { have_username = 1; strncpy(username, login_profile->username, sizeof(username) - 1); username[sizeof(username) - 1] = '\0'; } } if (!have_password) { if (login_profile != NULL && login_profile->hasPassword) { have_password = 1; strncpy(password, login_profile->password, sizeof(password) - 1); password[sizeof(password) - 1] = '\0'; } } } /* Seed randomizer */ srand(time(NULL)); if (use_raw_socket) { if (geteuid() != 0) { fprintf(stderr, _("You need to have root privileges to use the -n parameter.\n")); return 1; } sockfd = net_init_raw_socket(); if (drop_priv) { drop_privileges(nonpriv_username); } } else if (drop_priv) { fprintf(stderr, _("The -U option must be used in conjunction with the -n parameter.\n")); return 1; } /* Receive regular udp packets with this socket */ insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (insockfd < 0) { perror("insockfd"); return 1; } if (!use_raw_socket) { if (setsockopt(insockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) { perror("SO_BROADCAST"); return 1; } } /* Need to use, to be able to autodetect which interface to use */ setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval)); /* Get mac-address from string, or check for hostname via mndp */ if (!query_mndp_or_mac(argv[optind], dstmac, !quiet_mode)) { /* No valid mac address found, abort */ return 1; } if (!have_username) { if (!quiet_mode) { printf(_("Login: ")); fflush(stdout); } scanf("%127s", username); } if (!have_password) { char *tmp; tmp = getpass(quiet_mode ? "" : _("Password: ")); #if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE) mlock(password, sizeof(password)); #endif strncpy(password, tmp, sizeof(password) - 1); password[sizeof(password) - 1] = '\0'; /* security */ memset(tmp, 0, strlen(tmp)); #ifdef __linux__ free(tmp); #endif } /* Set random source port */ sourceport = 1024 + (rand() % 1024); /* Set up global info about the connection */ inet_pton(AF_INET, (char *)"255.255.255.255", &destip); memcpy(&sourceip, &(si_me.sin_addr), IPV4_ALEN); /* Session key */ sessionkey = rand() % 65535; /* stop output buffering */ setvbuf(stdout, (char*)NULL, _IONBF, 0); if (!quiet_mode) { printf(_("Connecting to %s..."), ether_ntoa((struct ether_addr *)dstmac)); } /* Initialize receiving socket on the device chosen */ memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(sourceport); /* Bind to udp port */ if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) { fprintf(stderr, _("Error binding to %s:%d, %s\n"), inet_ntoa(si_me.sin_addr), sourceport, strerror(errno)); return 1; } if (!find_interface() || (result = recvfrom(insockfd, buff, sizeof(buff), 0, 0, 0)) < 1) { fprintf(stderr, _("Connection failed.\n")); return 1; } if (!quiet_mode) { printf(_("done\n")); } /* Handle first received packet */ handle_packet(buff, result); init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, 0); outcounter += add_control_packet(&data, MT_CPTYPE_BEGINAUTH, NULL, 0); /* TODO: handle result of send_udp */ result = send_udp(&data, 1); while (running) { fd_set read_fds; int reads; static int terminal_gone = 0; struct timeval timeout; /* Init select */ FD_ZERO(&read_fds); if (!terminal_gone) { FD_SET(0, &read_fds); } FD_SET(insockfd, &read_fds); timeout.tv_sec = 1; timeout.tv_usec = 0; /* Wait for data or timeout */ reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout); if (reads > 0) { /* Handle data from server */ if (FD_ISSET(insockfd, &read_fds)) { bzero(buff, sizeof(buff)); result = recvfrom(insockfd, buff, sizeof(buff), 0, 0, 0); handle_packet(buff, result); } /* Handle data from keyboard/local terminal */ if (FD_ISSET(0, &read_fds) && terminal_mode) { unsigned char keydata[512]; int datalen; datalen = read(STDIN_FILENO, &keydata, sizeof(keydata)); if (datalen > 0) { /* Data received, transmit to server */ init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter); add_control_packet(&data, MT_CPTYPE_PLAINDATA, &keydata, datalen); outcounter += datalen; send_udp(&data, 1); } else { terminal_gone = 1; } } /* Handle select() timeout */ } else { /* handle keepalive counter, transmit keepalive packet every 10 seconds of inactivity */ if (keepalive_counter++ == 10) { struct mt_packet odata; init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, outcounter); send_udp(&odata, 0); } } } if (is_a_tty && terminal_mode) { /* Reset terminal back to old settings */ reset_term(); } close(sockfd); close(insockfd); DL_FOREACH_SAFE(interfaces, interface, tmp) { DL_DELETE(interfaces, interface); free(interface); } return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5252_0
crossvul-cpp_data_good_5112_0
/* cosine.c * * CoSine IPNOS L2 debug output parsing * Copyright (c) 2002 by Motonori Shindo <motonori@shin.do> * * Wiretap Library * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include "wtap-int.h" #include "cosine.h" #include "file_wrappers.h" #include <stdlib.h> #include <string.h> /* IPNOS: CONFIG VPN(100) VR(1.1.1.1)# diags ipnos diags: Control (1/0) :: layer-2 ? Registered commands for area "layer-2" apply-pkt-log-profile Configure packet logging on an interface create-pkt-log-profile Set packet-log-profile to be used for packet logging (see layer-2 pkt-log) detail Get Layer 2 low-level details ipnos diags: Control (1/0) :: layer-2 create ? create-pkt-log-profile <pkt-log-profile-id ctl-tx-trace-length ctl-rx-trace-length data-tx-trace-length data-rx-trace-length pe-logging-or-control-blade> ipnos diags: Control (1/0) :: layer-2 create 1 32 32 0 0 0 ipnos diags: Control (1/0) :: layer-2 create 2 32 32 100 100 0 ipnos diags: Control (1/0) :: layer-2 apply ? apply-pkt-log-profile <slot port channel subif pkt-log-profile-id> ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 1 Successfully applied packet-log-profile on LI -- Note that only the control packets are logged because the data packet size parameters are 0 in profile 1 IPNOS: CONFIG VPN(200) VR(3.3.3.3)# ping 20.20.20.43 vpn 200 : [max tries 4, timeout 5 seconds, data length 64 bytes, ttl 255] ping #1 ok, RTT 0.000 seconds ping #2 ok, RTT 0.000 seconds ping #3 ok, RTT 0.000 seconds ping #4 ok, RTT 0.000 seconds [finished] IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000] 2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000] ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0 Successfully applied packet-log-profile on LI ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 2 Successfully applied packet-log-profile on LI -- Note that both control and data packets are logged because the data packet size parameter is 100 in profile 2 Please ignore the event-log messages getting mixed up with the ping command ping 20.20.20.43 cou2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6B 60 84 AA 2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000] 00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6D FE FA AA 2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6B 60 84 AA 2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000] 00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6D FE FA AA nt 1 length 500 vpn 200 : [max tries 1, timeout 5 seconds, data length 500 bytes, ttl 255] 2000-2-1,18:20:24.1: l2-tx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4070, 0x801] 00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 27 00 00 FF 01 69 51 14 14 14 22 14 14 14 2B 08 00 AD B8 00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F ping #1 ok, RTT 0.010 seconds 2000-2-1,18:20:24.1: l2-rx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4071, 0x30801] 00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 23 00 00 FF 01 69 55 14 14 14 2B 14 14 14 22 00 00 B5 B8 00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F [finished] IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6B 60 84 AA 2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000] 00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6D FE FA AA 2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6B 60 84 AA 2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000] 00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6D FE FA AA ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0 Successfully applied packet-log-profile on LI ipnos diags: Control (1/0) :: */ /* XXX TODO: o Handle a case where an empty line doesn't exists as a delimiter of each packet. If the output is sent to a control blade and displayed as an event log, there's always an empty line between each packet output, but it may not be true when it is an PE output. o Some telnet client on Windows may put in a line break at 80 columns when it save the session to a text file ("CRT" is such an example). I don't think it's a good idea for the telnet client to do so, but CRT is widely used in Windows community, I should take care of that in the future. */ /* Magic text to check for CoSine L2 debug output */ #define COSINE_HDR_MAGIC_STR1 "l2-tx" #define COSINE_HDR_MAGIC_STR2 "l2-rx" /* Magic text for start of packet */ #define COSINE_REC_MAGIC_STR1 COSINE_HDR_MAGIC_STR1 #define COSINE_REC_MAGIC_STR2 COSINE_HDR_MAGIC_STR2 #define COSINE_HEADER_LINES_TO_CHECK 200 #define COSINE_LINE_LENGTH 240 static gboolean empty_line(const gchar *line); static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info, char *hdr); static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info); static gboolean cosine_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset); static gboolean cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info); static int parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info); static int parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset); /* Returns TRUE if the line appears to be an empty line. Otherwise it returns FALSE. */ static gboolean empty_line(const gchar *line) { while (*line) { if (g_ascii_isspace(*line)) { line++; continue; } else { break; } } if (*line == '\0') return TRUE; else return FALSE; } /* Seeks to the beginning of the next packet, and returns the byte offset. Copy the header line to hdr. Returns -1 on failure, and sets "*err" to the error and sets "*err_info" to null or an additional error string. */ static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info, char *hdr) { gint64 cur_off; char buf[COSINE_LINE_LENGTH]; while (1) { cur_off = file_tell(wth->fh); if (cur_off == -1) { /* Error */ *err = file_error(wth->fh, err_info); return -1; } if (file_gets(buf, sizeof(buf), wth->fh) == NULL) { *err = file_error(wth->fh, err_info); return -1; } if (strstr(buf, COSINE_REC_MAGIC_STR1) || strstr(buf, COSINE_REC_MAGIC_STR2)) { g_strlcpy(hdr, buf, COSINE_LINE_LENGTH); return cur_off; } } return -1; } /* Look through the first part of a file to see if this is * a CoSine L2 debug output. * * Returns TRUE if it is, FALSE if it isn't or if we get an I/O error; * if we get an I/O error, "*err" will be set to a non-zero value and * "*err_info" will be set to null or an additional error string. */ static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info) { char buf[COSINE_LINE_LENGTH]; gsize reclen; guint line; buf[COSINE_LINE_LENGTH-1] = '\0'; for (line = 0; line < COSINE_HEADER_LINES_TO_CHECK; line++) { if (file_gets(buf, COSINE_LINE_LENGTH, wth->fh) == NULL) { /* EOF or error. */ *err = file_error(wth->fh, err_info); return FALSE; } reclen = strlen(buf); if (reclen < strlen(COSINE_HDR_MAGIC_STR1) || reclen < strlen(COSINE_HDR_MAGIC_STR2)) { continue; } if (strstr(buf, COSINE_HDR_MAGIC_STR1) || strstr(buf, COSINE_HDR_MAGIC_STR2)) { return TRUE; } } *err = 0; return FALSE; } wtap_open_return_val cosine_open(wtap *wth, int *err, gchar **err_info) { /* Look for CoSine header */ if (!cosine_check_file_type(wth, err, err_info)) { if (*err != 0 && *err != WTAP_ERR_SHORT_READ) return WTAP_OPEN_ERROR; return WTAP_OPEN_NOT_MINE; } if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */ return WTAP_OPEN_ERROR; wth->file_encap = WTAP_ENCAP_COSINE; wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_COSINE; wth->snapshot_length = 0; /* not known */ wth->subtype_read = cosine_read; wth->subtype_seek_read = cosine_seek_read; wth->file_tsprec = WTAP_TSPREC_CSEC; return WTAP_OPEN_MINE; } /* Find the next packet and parse it; called from wtap_read(). */ static gboolean cosine_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; char line[COSINE_LINE_LENGTH]; /* Find the next packet */ offset = cosine_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; *data_offset = offset; /* Parse the header and convert the ASCII hex dump to binary data */ return parse_cosine_packet(wth->fh, &wth->phdr, wth->frame_buffer, line, err, err_info); } /* Used to read packets in random-access fashion */ static gboolean cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { char line[COSINE_LINE_LENGTH]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) return FALSE; if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Parse the header and convert the ASCII hex dump to binary data */ return parse_cosine_packet(wth->random_fh, phdr, buf, line, err, err_info); } /* Parses a packet record header. There are two possible formats: 1) output to a control blade with date and time 2002-5-10,20:1:31.4: l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] 2) output to PE without date and time l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] */ static gboolean parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec; guint pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; guint8 *pd; int i, hex_lines, n, caplen = 0; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return FALSE; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return FALSE; } yy = mm = dd = hr = min = sec = csec = 0; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (empty_line(line)) { break; } if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers"); return FALSE; } caplen += n; } phdr->caplen = caplen; return TRUE; } /* Take a string representing one line from a hex dump and converts * the text to binary data. We place the bytes in the buffer at the * specified offset. * * Returns number of bytes successfully read, -1 if bad. */ static int parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset) { int num_items_scanned, i; unsigned int bytes[16]; num_items_scanned = sscanf(rec, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x", &bytes[0], &bytes[1], &bytes[2], &bytes[3], &bytes[4], &bytes[5], &bytes[6], &bytes[7], &bytes[8], &bytes[9], &bytes[10], &bytes[11], &bytes[12], &bytes[13], &bytes[14], &bytes[15]); if (num_items_scanned == 0) return -1; if (num_items_scanned > 16) num_items_scanned = 16; for (i=0; i<num_items_scanned; i++) { buf[byte_offset + i] = (guint8)bytes[i]; } return num_items_scanned; } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
./CrossVul/dataset_final_sorted/CWE-119/c/good_5112_0
crossvul-cpp_data_bad_121_0
/* linux/drivers/cdrom/cdrom.c Copyright (c) 1996, 1997 David A. van Leeuwen. Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org> Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk> May be copied or modified under the terms of the GNU General Public License. See linux/COPYING for more information. Uniform CD-ROM driver for Linux. See Documentation/cdrom/cdrom-standard.tex for usage information. The routines in the file provide a uniform interface between the software that uses CD-ROMs and the various low-level drivers that actually talk to the hardware. Suggestions are welcome. Patches that work are more welcome though. ;-) To Do List: ---------------------------------- -- Modify sysctl/proc interface. I plan on having one directory per drive, with entries for outputing general drive information, and sysctl based tunable parameters such as whether the tray should auto-close for that drive. Suggestions (or patches) for this welcome! Revision History ---------------------------------- 1.00 Date Unknown -- David van Leeuwen <david@tm.tno.nl> -- Initial version by David A. van Leeuwen. I don't have a detailed changelog for the 1.x series, David? 2.00 Dec 2, 1997 -- Erik Andersen <andersee@debian.org> -- New maintainer! As David A. van Leeuwen has been too busy to actively maintain and improve this driver, I am now carrying on the torch. If you have a problem with this driver, please feel free to contact me. -- Added (rudimentary) sysctl interface. I realize this is really weak right now, and is _very_ badly implemented. It will be improved... -- Modified CDROM_DISC_STATUS so that it is now incorporated into the Uniform CD-ROM driver via the cdrom_count_tracks function. The cdrom_count_tracks function helps resolve some of the false assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check for the correct media type when mounting or playing audio from a CD. -- Remove the calls to verify_area and only use the copy_from_user and copy_to_user stuff, since these calls now provide their own memory checking with the 2.1.x kernels. -- Major update to return codes so that errors from low-level drivers are passed on through (thanks to Gerd Knorr for pointing out this problem). -- Made it so if a function isn't implemented in a low-level driver, ENOSYS is now returned instead of EINVAL. -- Simplified some complex logic so that the source code is easier to read. -- Other stuff I probably forgot to mention (lots of changes). 2.01 to 2.11 Dec 1997-Jan 1998 -- TO-DO! Write changelogs for 2.01 to 2.12. 2.12 Jan 24, 1998 -- Erik Andersen <andersee@debian.org> -- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros. It turns out that copy_*_user does not return EFAULT on error, but instead returns the number of bytes not copied. I was returning whatever non-zero stuff came back from the copy_*_user functions directly, which would result in strange errors. 2.13 July 17, 1998 -- Erik Andersen <andersee@debian.org> -- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed of the drive. Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing this out and providing a simple fix. -- Fixed the procfs-unload-module bug with the fill_inode procfs callback. thanks to Andrea Arcangeli -- Fixed it so that the /proc entry now also shows up when cdrom is compiled into the kernel. Before it only worked when loaded as a module. 2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org> -- Fixed a bug in cdrom_media_changed and handling of reporting that the media had changed for devices that _don't_ implement media_changed. Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug. -- Made a few things more pedanticly correct. 2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk> -- New maintainers! Erik was too busy to continue the work on the driver, so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk> will do their best to follow in his footsteps 2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk> -- Check if drive is capable of doing what we ask before blindly changing cdi->options in various ioctl. -- Added version to proc entry. 2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk> -- Fixed an error in open_for_data where we would sometimes not return the correct error value. Thanks Huba Gaspar <huba@softcell.hu>. -- Fixed module usage count - usage was based on /proc/sys/dev instead of /proc/sys/dev/cdrom. This could lead to an oops when other modules had entries in dev. Feb 02 - real bug was in sysctl.c where dev would be removed even though it was used. cdrom.c just illuminated that bug. 2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk> -- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has been "rewritten" because capabilities and options aren't in sync. They should be... -- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way. -- Added CDROM_RESET ioctl. -- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly. -- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs from parsing /proc/sys/dev/cdrom/info. 2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk> -- Check capability mask from low level driver when counting tracks as per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>. 2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk> -- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of CDC_CLOSE_TRAY. -- proc info didn't mask against capabilities mask. 3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk> -- Unified audio ioctl handling across CD-ROM drivers. A lot of the code was duplicated before. Drives that support the generic packet interface are now being fed packets from here instead. -- First attempt at adding support for MMC2 commands - for DVD and CD-R(W) drives. Only the DVD parts are in now - the interface used is the same as for the audio ioctls. -- ioctl cleanups. if a drive couldn't play audio, it didn't get a change to perform device specific ioctls as well. -- Defined CDROM_CAN(CDC_XXX) for checking the capabilities. -- Put in sysctl files for autoclose, autoeject, check_media, debug, and lock. -- /proc/sys/dev/cdrom/info has been updated to also contain info about CD-Rx and DVD capabilities. -- Now default to checking media type. -- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for doing this anyway, with the generic_packet addition. 3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk> -- Fix up the sysctl handling so that the option flags get set correctly. -- Fix up ioctl handling so the device specific ones actually get called :). 3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk> -- Fixed volume control on SCSI drives (or others with longer audio page). -- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath <andrewtv@usa.net> for telling me and for having defined the various DVD structures and ioctls in the first place! He designed the original DVD patches for ide-cd and while I rearranged and unified them, the interface is still the same. 3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk> -- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only CDROMREADTOCENTRY and CDROMREADTOCHDR are left. -- Moved the CDROMREADxxx ioctls in here. -- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls and exported functions. -- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands to now read GPCMD_ for the new generic packet interface. All low level drivers are updated as well. -- Various other cleanups. 3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk> -- Fixed a couple of possible memory leaks (if an operation failed and we didn't free the buffer before returning the error). -- Integrated Uniform CD Changer handling from Richard Sharman <rsharman@pobox.com>. -- Defined CD_DVD and CD_CHANGER log levels. -- Fixed the CDROMREADxxx ioctls. -- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few drives supported it. We lose the index part, however. -- Small modifications to accommodate opens of /dev/hdc1, required for ide-cd to handle multisession discs. -- Export cdrom_mode_sense and cdrom_mode_select. -- init_cdrom_command() for setting up a cgc command. 3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk> -- Changed the interface for CDROM_SEND_PACKET. Before it was virtually impossible to send the drive data in a sensible way. -- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and dvd_read_manufact. -- Added setup of write mode for packet writing. -- Fixed CDDA ripping with cdda2wav - accept much larger requests of number of frames and split the reads in blocks of 8. 3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk> -- Added support for changing the region of DVD drives. -- Added sense data to generic command. 3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de> -- Do same "read header length" trick in cdrom_get_disc_info() as we do in cdrom_get_track_info() -- some drive don't obey specs and fail if they can't supply the full Mt Fuji size table. -- Deleted stuff related to setting up write modes. It has a different home now. -- Clear header length in mode_select unconditionally. -- Removed the register_disk() that was added, not needed here. 3.08 May 1, 2000 - Jens Axboe <axboe@suse.de> -- Fix direction flag in setup_send_key and setup_report_key. This gave some SCSI adapters problems. -- Always return -EROFS for write opens -- Convert to module_init/module_exit style init and remove some of the #ifdef MODULE stuff -- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid, DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and dvd_do_auth passed uninitialized data to drive because init_cdrom_command did not clear a 0 sized buffer. 3.09 May 12, 2000 - Jens Axboe <axboe@suse.de> -- Fix Video-CD on SCSI drives that don't support READ_CD command. In that case switch block size and issue plain READ_10 again, then switch back. 3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de> -- Fix volume control on CD's - old SCSI-II drives now use their own code, as doing MODE6 stuff in here is really not my intention. -- Use READ_DISC_INFO for more reliable end-of-disc. 3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de> -- Fix bug in getting rpc phase 2 region info. -- Reinstate "correct" CDROMPLAYTRKIND 3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de> -- Use quiet bit on packet commands not known to work 3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de> -- Various fixes and lots of cleanups not listed :-) -- Locking fixes -- Mt Rainier support -- DVD-RAM write open fixes Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov <appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units. Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW 2.4.x patch by Andy Polyakov <appro@fy.chalmers.se> -------------------------------------------------------------------------*/ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define REVISION "Revision: 3.20" #define VERSION "Id: cdrom.c 3.20 2003/12/17" /* I use an error-log mask to give fine grain control over the type of messages dumped to the system logs. The available masks include: */ #define CD_NOTHING 0x0 #define CD_WARNING 0x1 #define CD_REG_UNREG 0x2 #define CD_DO_IOCTL 0x4 #define CD_OPEN 0x8 #define CD_CLOSE 0x10 #define CD_COUNT_TRACKS 0x20 #define CD_CHANGER 0x40 #define CD_DVD 0x80 /* Define this to remove _all_ the debugging messages */ /* #define ERRLOGMASK CD_NOTHING */ #define ERRLOGMASK CD_WARNING /* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */ /* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */ #include <linux/module.h> #include <linux/fs.h> #include <linux/major.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/cdrom.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/blkpg.h> #include <linux/init.h> #include <linux/fcntl.h> #include <linux/blkdev.h> #include <linux/times.h> #include <linux/uaccess.h> #include <scsi/scsi_request.h> /* used to tell the module to turn on full debugging messages */ static bool debug; /* default compatibility mode */ static bool autoclose=1; static bool autoeject; static bool lockdoor = 1; /* will we ever get to use this... sigh. */ static bool check_media_type; /* automatically restart mrw format */ static bool mrw_format_restart = 1; module_param(debug, bool, 0); module_param(autoclose, bool, 0); module_param(autoeject, bool, 0); module_param(lockdoor, bool, 0); module_param(check_media_type, bool, 0); module_param(mrw_format_restart, bool, 0); static DEFINE_MUTEX(cdrom_mutex); static const char *mrw_format_status[] = { "not mrw", "bgformat inactive", "bgformat active", "mrw complete", }; static const char *mrw_address_space[] = { "DMA", "GAA" }; #if (ERRLOGMASK != CD_NOTHING) #define cd_dbg(type, fmt, ...) \ do { \ if ((ERRLOGMASK & type) || debug == 1) \ pr_debug(fmt, ##__VA_ARGS__); \ } while (0) #else #define cd_dbg(type, fmt, ...) \ do { \ if (0 && (ERRLOGMASK & type) || debug == 1) \ pr_debug(fmt, ##__VA_ARGS__); \ } while (0) #endif /* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in a lot of places. This macro makes the code more clear. */ #define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type)) /* * Another popular OS uses 7 seconds as the hard timeout for default * commands, so it is a good choice for us as well. */ #define CDROM_DEF_TIMEOUT (7 * HZ) /* Not-exported routines. */ static void cdrom_sysctl_register(void); static LIST_HEAD(cdrom_list); int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi, struct packet_command *cgc) { if (cgc->sense) { cgc->sense->sense_key = 0x05; cgc->sense->asc = 0x20; cgc->sense->ascq = 0x00; } cgc->stat = -EIO; return -EIO; } EXPORT_SYMBOL(cdrom_dummy_generic_packet); static int cdrom_flush_cache(struct cdrom_device_info *cdi) { struct packet_command cgc; init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_FLUSH_CACHE; cgc.timeout = 5 * 60 * HZ; return cdi->ops->generic_packet(cdi, &cgc); } /* requires CD R/RW */ static int cdrom_get_disc_info(struct cdrom_device_info *cdi, disc_information *di) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; int ret, buflen; /* set up command and get the disc info */ init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ); cgc.cmd[0] = GPCMD_READ_DISC_INFO; cgc.cmd[8] = cgc.buflen = 2; cgc.quiet = 1; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; /* not all drives have the same disc_info length, so requeue * packet with the length the drive tells us it can supply */ buflen = be16_to_cpu(di->disc_information_length) + sizeof(di->disc_information_length); if (buflen > sizeof(disc_information)) buflen = sizeof(disc_information); cgc.cmd[8] = cgc.buflen = buflen; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; /* return actual fill size */ return buflen; } /* This macro makes sure we don't have to check on cdrom_device_ops * existence in the run-time routines below. Change_capability is a * hack to have the capability flags defined const, while we can still * change it here without gcc complaining at every line. */ #define ENSURE(call, bits) \ do { \ if (cdo->call == NULL) \ *change_capability &= ~(bits); \ } while (0) /* * the first prototypes used 0x2c as the page code for the mrw mode page, * subsequently this was changed to 0x03. probe the one used by this drive */ static int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[16]; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.timeout = HZ; cgc.quiet = 1; if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) { cdi->mrw_mode_page = MRW_MODE_PC; return 0; } else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) { cdi->mrw_mode_page = MRW_MODE_PC_PRE1; return 0; } return 1; } static int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write) { struct packet_command cgc; struct mrw_feature_desc *mfd; unsigned char buffer[16]; int ret; *write = 0; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; cgc.cmd[3] = CDF_MRW; cgc.cmd[8] = sizeof(buffer); cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) return ret; mfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)]; if (be16_to_cpu(mfd->feature_code) != CDF_MRW) return 1; *write = mfd->write; if ((ret = cdrom_mrw_probe_pc(cdi))) { *write = 0; return ret; } return 0; } static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont) { struct packet_command cgc; unsigned char buffer[12]; int ret; pr_info("%sstarting format\n", cont ? "Re" : ""); /* * FmtData bit set (bit 4), format type is 1 */ init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE); cgc.cmd[0] = GPCMD_FORMAT_UNIT; cgc.cmd[1] = (1 << 4) | 1; cgc.timeout = 5 * 60 * HZ; /* * 4 byte format list header, 8 byte format list descriptor */ buffer[1] = 1 << 1; buffer[3] = 8; /* * nr_blocks field */ buffer[4] = 0xff; buffer[5] = 0xff; buffer[6] = 0xff; buffer[7] = 0xff; buffer[8] = 0x24 << 2; buffer[11] = cont; ret = cdi->ops->generic_packet(cdi, &cgc); if (ret) pr_info("bgformat failed\n"); return ret; } static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed) { struct packet_command cgc; init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_CLOSE_TRACK; /* * Session = 1, Track = 0 */ cgc.cmd[1] = !!immed; cgc.cmd[2] = 1 << 1; cgc.timeout = 5 * 60 * HZ; return cdi->ops->generic_packet(cdi, &cgc); } static int cdrom_mrw_exit(struct cdrom_device_info *cdi) { disc_information di; int ret; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < (int)offsetof(typeof(di),disc_type)) return 1; ret = 0; if (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) { pr_info("issuing MRW background format suspend\n"); ret = cdrom_mrw_bgformat_susp(cdi, 0); } if (!ret && cdi->media_written) ret = cdrom_flush_cache(cdi); return ret; } static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space) { struct packet_command cgc; struct mode_page_header *mph; char buffer[16]; int ret, offset, size; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.buffer = buffer; cgc.buflen = sizeof(buffer); ret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0); if (ret) return ret; mph = (struct mode_page_header *)buffer; offset = be16_to_cpu(mph->desc_length); size = be16_to_cpu(mph->mode_data_length) + 2; buffer[offset + 3] = space; cgc.buflen = size; ret = cdrom_mode_select(cdi, &cgc); if (ret) return ret; pr_info("%s: mrw address space %s selected\n", cdi->name, mrw_address_space[space]); return 0; } int register_cdrom(struct cdrom_device_info *cdi) { static char banner_printed; const struct cdrom_device_ops *cdo = cdi->ops; int *change_capability = (int *)&cdo->capability; /* hack */ cd_dbg(CD_OPEN, "entering register_cdrom\n"); if (cdo->open == NULL || cdo->release == NULL) return -EINVAL; if (!banner_printed) { pr_info("Uniform CD-ROM driver " REVISION "\n"); banner_printed = 1; cdrom_sysctl_register(); } ENSURE(drive_status, CDC_DRIVE_STATUS); if (cdo->check_events == NULL && cdo->media_changed == NULL) *change_capability = ~(CDC_MEDIA_CHANGED | CDC_SELECT_DISC); ENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY); ENSURE(lock_door, CDC_LOCK); ENSURE(select_speed, CDC_SELECT_SPEED); ENSURE(get_last_session, CDC_MULTI_SESSION); ENSURE(get_mcn, CDC_MCN); ENSURE(reset, CDC_RESET); ENSURE(generic_packet, CDC_GENERIC_PACKET); cdi->mc_flags = 0; cdi->options = CDO_USE_FFLAGS; if (autoclose == 1 && CDROM_CAN(CDC_CLOSE_TRAY)) cdi->options |= (int) CDO_AUTO_CLOSE; if (autoeject == 1 && CDROM_CAN(CDC_OPEN_TRAY)) cdi->options |= (int) CDO_AUTO_EJECT; if (lockdoor == 1) cdi->options |= (int) CDO_LOCK; if (check_media_type == 1) cdi->options |= (int) CDO_CHECK_TYPE; if (CDROM_CAN(CDC_MRW_W)) cdi->exit = cdrom_mrw_exit; if (cdi->disk) cdi->cdda_method = CDDA_BPC_FULL; else cdi->cdda_method = CDDA_OLD; WARN_ON(!cdo->generic_packet); cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" registered\n", cdi->name); mutex_lock(&cdrom_mutex); list_add(&cdi->list, &cdrom_list); mutex_unlock(&cdrom_mutex); return 0; } #undef ENSURE void unregister_cdrom(struct cdrom_device_info *cdi) { cd_dbg(CD_OPEN, "entering unregister_cdrom\n"); mutex_lock(&cdrom_mutex); list_del(&cdi->list); mutex_unlock(&cdrom_mutex); if (cdi->exit) cdi->exit(cdi); cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" unregistered\n", cdi->name); } int cdrom_get_media_event(struct cdrom_device_info *cdi, struct media_event_desc *med) { struct packet_command cgc; unsigned char buffer[8]; struct event_header *eh = (struct event_header *)buffer; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION; cgc.cmd[1] = 1; /* IMMED */ cgc.cmd[4] = 1 << 4; /* media event */ cgc.cmd[8] = sizeof(buffer); cgc.quiet = 1; if (cdi->ops->generic_packet(cdi, &cgc)) return 1; if (be16_to_cpu(eh->data_len) < sizeof(*med)) return 1; if (eh->nea || eh->notification_class != 0x4) return 1; memcpy(med, &buffer[sizeof(*eh)], sizeof(*med)); return 0; } static int cdrom_get_random_writable(struct cdrom_device_info *cdi, struct rwrt_feature_desc *rfd) { struct packet_command cgc; char buffer[24]; int ret; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; /* often 0x46 */ cgc.cmd[3] = CDF_RWRT; /* often 0x0020 */ cgc.cmd[8] = sizeof(buffer); /* often 0x18 */ cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) return ret; memcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd)); return 0; } static int cdrom_has_defect_mgt(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[16]; __be16 *feature_code; int ret; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; cgc.cmd[3] = CDF_HWDM; cgc.cmd[8] = sizeof(buffer); cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) return ret; feature_code = (__be16 *) &buffer[sizeof(struct feature_header)]; if (be16_to_cpu(*feature_code) == CDF_HWDM) return 0; return 1; } static int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write) { struct rwrt_feature_desc rfd; int ret; *write = 0; if ((ret = cdrom_get_random_writable(cdi, &rfd))) return ret; if (CDF_RWRT == be16_to_cpu(rfd.feature_code)) *write = 1; return 0; } static int cdrom_media_erasable(struct cdrom_device_info *cdi) { disc_information di; int ret; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < offsetof(typeof(di), n_first_track)) return -1; return di.erasable; } /* * FIXME: check RO bit */ static int cdrom_dvdram_open_write(struct cdrom_device_info *cdi) { int ret = cdrom_media_erasable(cdi); /* * allow writable open if media info read worked and media is * erasable, _or_ if it fails since not all drives support it */ if (!ret) return 1; return 0; } static int cdrom_mrw_open_write(struct cdrom_device_info *cdi) { disc_information di; int ret; /* * always reset to DMA lba space on open */ if (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) { pr_err("failed setting lba address space\n"); return 1; } ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < offsetof(typeof(di),disc_type)) return 1; if (!di.erasable) return 1; /* * mrw_status * 0 - not MRW formatted * 1 - MRW bgformat started, but not running or complete * 2 - MRW bgformat in progress * 3 - MRW formatting complete */ ret = 0; pr_info("open: mrw_status '%s'\n", mrw_format_status[di.mrw_status]); if (!di.mrw_status) ret = 1; else if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE && mrw_format_restart) ret = cdrom_mrw_bgformat(cdi, 1); return ret; } static int mo_open_write(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[255]; int ret; init_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ); cgc.quiet = 1; /* * obtain write protect information as per * drivers/scsi/sd.c:sd_read_write_protect_flag */ ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0); if (ret) ret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0); if (ret) { cgc.buflen = 255; ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0); } /* drive gave us no info, let the user go ahead */ if (ret) return 0; return buffer[3] & 0x80; } static int cdrom_ram_open_write(struct cdrom_device_info *cdi) { struct rwrt_feature_desc rfd; int ret; if ((ret = cdrom_has_defect_mgt(cdi))) return ret; if ((ret = cdrom_get_random_writable(cdi, &rfd))) return ret; else if (CDF_RWRT == be16_to_cpu(rfd.feature_code)) ret = !rfd.curr; cd_dbg(CD_OPEN, "can open for random write\n"); return ret; } static void cdrom_mmc3_profile(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[32]; int ret, mmc3_profile; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; cgc.cmd[1] = 0; cgc.cmd[2] = cgc.cmd[3] = 0; /* Starting Feature Number */ cgc.cmd[8] = sizeof(buffer); /* Allocation Length */ cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) mmc3_profile = 0xffff; else mmc3_profile = (buffer[6] << 8) | buffer[7]; cdi->mmc3_profile = mmc3_profile; } static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi) { switch (cdi->mmc3_profile) { case 0x12: /* DVD-RAM */ case 0x1A: /* DVD+RW */ case 0x43: /* BD-RE */ return 0; default: return 1; } } /* * returns 0 for ok to open write, non-0 to disallow */ static int cdrom_open_write(struct cdrom_device_info *cdi) { int mrw, mrw_write, ram_write; int ret = 1; mrw = 0; if (!cdrom_is_mrw(cdi, &mrw_write)) mrw = 1; if (CDROM_CAN(CDC_MO_DRIVE)) ram_write = 1; else (void) cdrom_is_random_writable(cdi, &ram_write); if (mrw) cdi->mask &= ~CDC_MRW; else cdi->mask |= CDC_MRW; if (mrw_write) cdi->mask &= ~CDC_MRW_W; else cdi->mask |= CDC_MRW_W; if (ram_write) cdi->mask &= ~CDC_RAM; else cdi->mask |= CDC_RAM; if (CDROM_CAN(CDC_MRW_W)) ret = cdrom_mrw_open_write(cdi); else if (CDROM_CAN(CDC_DVD_RAM)) ret = cdrom_dvdram_open_write(cdi); else if (CDROM_CAN(CDC_RAM) && !CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE)) ret = cdrom_ram_open_write(cdi); else if (CDROM_CAN(CDC_MO_DRIVE)) ret = mo_open_write(cdi); else if (!cdrom_is_dvd_rw(cdi)) ret = 0; return ret; } static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi) { struct packet_command cgc; if (cdi->mmc3_profile != 0x1a) { cd_dbg(CD_CLOSE, "%s: No DVD+RW\n", cdi->name); return; } if (!cdi->media_written) { cd_dbg(CD_CLOSE, "%s: DVD+RW media clean\n", cdi->name); return; } pr_info("%s: dirty DVD+RW media, \"finalizing\"\n", cdi->name); init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_FLUSH_CACHE; cgc.timeout = 30*HZ; cdi->ops->generic_packet(cdi, &cgc); init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_CLOSE_TRACK; cgc.timeout = 3000*HZ; cgc.quiet = 1; cdi->ops->generic_packet(cdi, &cgc); init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_CLOSE_TRACK; cgc.cmd[2] = 2; /* Close session */ cgc.quiet = 1; cgc.timeout = 3000*HZ; cdi->ops->generic_packet(cdi, &cgc); cdi->media_written = 0; } static int cdrom_close_write(struct cdrom_device_info *cdi) { #if 0 return cdrom_flush_cache(cdi); #else return 0; #endif } /* badly broken, I know. Is due for a fixup anytime. */ static void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype *tracks) { struct cdrom_tochdr header; struct cdrom_tocentry entry; int ret, i; tracks->data = 0; tracks->audio = 0; tracks->cdi = 0; tracks->xa = 0; tracks->error = 0; cd_dbg(CD_COUNT_TRACKS, "entering cdrom_count_tracks\n"); /* Grab the TOC header so we can see how many tracks there are */ ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header); if (ret) { if (ret == -ENOMEDIUM) tracks->error = CDS_NO_DISC; else tracks->error = CDS_NO_INFO; return; } /* check what type of tracks are on this disc */ entry.cdte_format = CDROM_MSF; for (i = header.cdth_trk0; i <= header.cdth_trk1; i++) { entry.cdte_track = i; if (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) { tracks->error = CDS_NO_INFO; return; } if (entry.cdte_ctrl & CDROM_DATA_TRACK) { if (entry.cdte_format == 0x10) tracks->cdi++; else if (entry.cdte_format == 0x20) tracks->xa++; else tracks->data++; } else { tracks->audio++; } cd_dbg(CD_COUNT_TRACKS, "track %d: format=%d, ctrl=%d\n", i, entry.cdte_format, entry.cdte_ctrl); } cd_dbg(CD_COUNT_TRACKS, "disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\n", header.cdth_trk1, tracks->audio, tracks->data, tracks->cdi, tracks->xa); } static int open_for_data(struct cdrom_device_info *cdi) { int ret; const struct cdrom_device_ops *cdo = cdi->ops; tracktype tracks; cd_dbg(CD_OPEN, "entering open_for_data\n"); /* Check if the driver can report drive status. If it can, we can do clever things. If it can't, well, we at least tried! */ if (cdo->drive_status != NULL) { ret = cdo->drive_status(cdi, CDSL_CURRENT); cd_dbg(CD_OPEN, "drive_status=%d\n", ret); if (ret == CDS_TRAY_OPEN) { cd_dbg(CD_OPEN, "the tray is open...\n"); /* can/may i close it? */ if (CDROM_CAN(CDC_CLOSE_TRAY) && cdi->options & CDO_AUTO_CLOSE) { cd_dbg(CD_OPEN, "trying to close the tray\n"); ret=cdo->tray_move(cdi,0); if (ret) { cd_dbg(CD_OPEN, "bummer. tried to close the tray but failed.\n"); /* Ignore the error from the low level driver. We don't care why it couldn't close the tray. We only care that there is no disc in the drive, since that is the _REAL_ problem here.*/ ret=-ENOMEDIUM; goto clean_up_and_return; } } else { cd_dbg(CD_OPEN, "bummer. this drive can't close the tray.\n"); ret=-ENOMEDIUM; goto clean_up_and_return; } /* Ok, the door should be closed now.. Check again */ ret = cdo->drive_status(cdi, CDSL_CURRENT); if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) { cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n"); cd_dbg(CD_OPEN, "tray might not contain a medium\n"); ret=-ENOMEDIUM; goto clean_up_and_return; } cd_dbg(CD_OPEN, "the tray is now closed\n"); } /* the door should be closed now, check for the disc */ ret = cdo->drive_status(cdi, CDSL_CURRENT); if (ret!=CDS_DISC_OK) { ret = -ENOMEDIUM; goto clean_up_and_return; } } cdrom_count_tracks(cdi, &tracks); if (tracks.error == CDS_NO_DISC) { cd_dbg(CD_OPEN, "bummer. no disc.\n"); ret=-ENOMEDIUM; goto clean_up_and_return; } /* CD-Players which don't use O_NONBLOCK, workman * for example, need bit CDO_CHECK_TYPE cleared! */ if (tracks.data==0) { if (cdi->options & CDO_CHECK_TYPE) { /* give people a warning shot, now that CDO_CHECK_TYPE is the default case! */ cd_dbg(CD_OPEN, "bummer. wrong media type.\n"); cd_dbg(CD_WARNING, "pid %d must open device O_NONBLOCK!\n", (unsigned int)task_pid_nr(current)); ret=-EMEDIUMTYPE; goto clean_up_and_return; } else { cd_dbg(CD_OPEN, "wrong media type, but CDO_CHECK_TYPE not set\n"); } } cd_dbg(CD_OPEN, "all seems well, opening the devicen"); /* all seems well, we can open the device */ ret = cdo->open(cdi, 0); /* open for data */ cd_dbg(CD_OPEN, "opening the device gave me %d\n", ret); /* After all this careful checking, we shouldn't have problems opening the device, but we don't want the device locked if this somehow fails... */ if (ret) { cd_dbg(CD_OPEN, "open device failed\n"); goto clean_up_and_return; } if (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) { cdo->lock_door(cdi, 1); cd_dbg(CD_OPEN, "door locked\n"); } cd_dbg(CD_OPEN, "device opened successfully\n"); return ret; /* Something failed. Try to unlock the drive, because some drivers (notably ide-cd) lock the drive after every command. This produced a nasty bug where after mount failed, the drive would remain locked! This ensures that the drive gets unlocked after a mount fails. This is a goto to avoid bloating the driver with redundant code. */ clean_up_and_return: cd_dbg(CD_OPEN, "open failed\n"); if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) { cdo->lock_door(cdi, 0); cd_dbg(CD_OPEN, "door unlocked\n"); } return ret; } /* We use the open-option O_NONBLOCK to indicate that the * purpose of opening is only for subsequent ioctl() calls; no device * integrity checks are performed. * * We hope that all cd-player programs will adopt this convention. It * is in their own interest: device control becomes a lot easier * this way. */ int cdrom_open(struct cdrom_device_info *cdi, struct block_device *bdev, fmode_t mode) { int ret; cd_dbg(CD_OPEN, "entering cdrom_open\n"); /* if this was a O_NONBLOCK open and we should honor the flags, * do a quick open without drive/disc integrity checks. */ cdi->use_count++; if ((mode & FMODE_NDELAY) && (cdi->options & CDO_USE_FFLAGS)) { ret = cdi->ops->open(cdi, 1); } else { ret = open_for_data(cdi); if (ret) goto err; cdrom_mmc3_profile(cdi); if (mode & FMODE_WRITE) { ret = -EROFS; if (cdrom_open_write(cdi)) goto err_release; if (!CDROM_CAN(CDC_RAM)) goto err_release; ret = 0; cdi->media_written = 0; } } if (ret) goto err; cd_dbg(CD_OPEN, "Use count for \"/dev/%s\" now %d\n", cdi->name, cdi->use_count); return 0; err_release: if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) { cdi->ops->lock_door(cdi, 0); cd_dbg(CD_OPEN, "door unlocked\n"); } cdi->ops->release(cdi); err: cdi->use_count--; return ret; } /* This code is similar to that in open_for_data. The routine is called whenever an audio play operation is requested. */ static int check_for_audio_disc(struct cdrom_device_info *cdi, const struct cdrom_device_ops *cdo) { int ret; tracktype tracks; cd_dbg(CD_OPEN, "entering check_for_audio_disc\n"); if (!(cdi->options & CDO_CHECK_TYPE)) return 0; if (cdo->drive_status != NULL) { ret = cdo->drive_status(cdi, CDSL_CURRENT); cd_dbg(CD_OPEN, "drive_status=%d\n", ret); if (ret == CDS_TRAY_OPEN) { cd_dbg(CD_OPEN, "the tray is open...\n"); /* can/may i close it? */ if (CDROM_CAN(CDC_CLOSE_TRAY) && cdi->options & CDO_AUTO_CLOSE) { cd_dbg(CD_OPEN, "trying to close the tray\n"); ret=cdo->tray_move(cdi,0); if (ret) { cd_dbg(CD_OPEN, "bummer. tried to close tray but failed.\n"); /* Ignore the error from the low level driver. We don't care why it couldn't close the tray. We only care that there is no disc in the drive, since that is the _REAL_ problem here.*/ return -ENOMEDIUM; } } else { cd_dbg(CD_OPEN, "bummer. this driver can't close the tray.\n"); return -ENOMEDIUM; } /* Ok, the door should be closed now.. Check again */ ret = cdo->drive_status(cdi, CDSL_CURRENT); if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) { cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n"); return -ENOMEDIUM; } if (ret!=CDS_DISC_OK) { cd_dbg(CD_OPEN, "bummer. disc isn't ready.\n"); return -EIO; } cd_dbg(CD_OPEN, "the tray is now closed\n"); } } cdrom_count_tracks(cdi, &tracks); if (tracks.error) return(tracks.error); if (tracks.audio==0) return -EMEDIUMTYPE; return 0; } void cdrom_release(struct cdrom_device_info *cdi, fmode_t mode) { const struct cdrom_device_ops *cdo = cdi->ops; int opened_for_data; cd_dbg(CD_CLOSE, "entering cdrom_release\n"); if (cdi->use_count > 0) cdi->use_count--; if (cdi->use_count == 0) { cd_dbg(CD_CLOSE, "Use count for \"/dev/%s\" now zero\n", cdi->name); cdrom_dvd_rw_close_write(cdi); if ((cdo->capability & CDC_LOCK) && !cdi->keeplocked) { cd_dbg(CD_CLOSE, "Unlocking door!\n"); cdo->lock_door(cdi, 0); } } opened_for_data = !(cdi->options & CDO_USE_FFLAGS) || !(mode & FMODE_NDELAY); /* * flush cache on last write release */ if (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data) cdrom_close_write(cdi); cdo->release(cdi); if (cdi->use_count == 0) { /* last process that closes dev*/ if (opened_for_data && cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY)) cdo->tray_move(cdi, 1); } } static int cdrom_read_mech_status(struct cdrom_device_info *cdi, struct cdrom_changer_info *buf) { struct packet_command cgc; const struct cdrom_device_ops *cdo = cdi->ops; int length; /* * Sanyo changer isn't spec compliant (doesn't use regular change * LOAD_UNLOAD command, and it doesn't implement the mech status * command below */ if (cdi->sanyo_slot) { buf->hdr.nslots = 3; buf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot; for (length = 0; length < 3; length++) { buf->slots[length].disc_present = 1; buf->slots[length].change = 0; } return 0; } length = sizeof(struct cdrom_mechstat_header) + cdi->capacity * sizeof(struct cdrom_slot); init_cdrom_command(&cgc, buf, length, CGC_DATA_READ); cgc.cmd[0] = GPCMD_MECHANISM_STATUS; cgc.cmd[8] = (length >> 8) & 0xff; cgc.cmd[9] = length & 0xff; return cdo->generic_packet(cdi, &cgc); } static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot) { struct cdrom_changer_info *info; int ret; cd_dbg(CD_CHANGER, "entering cdrom_slot_status()\n"); if (cdi->sanyo_slot) return CDS_NO_INFO; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((ret = cdrom_read_mech_status(cdi, info))) goto out_free; if (info->slots[slot].disc_present) ret = CDS_DISC_OK; else ret = CDS_NO_DISC; out_free: kfree(info); return ret; } /* Return the number of slots for an ATAPI/SCSI cdrom, * return 1 if not a changer. */ int cdrom_number_of_slots(struct cdrom_device_info *cdi) { int status; int nslots = 1; struct cdrom_changer_info *info; cd_dbg(CD_CHANGER, "entering cdrom_number_of_slots()\n"); /* cdrom_read_mech_status requires a valid value for capacity: */ cdi->capacity = 0; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((status = cdrom_read_mech_status(cdi, info)) == 0) nslots = info->hdr.nslots; kfree(info); return nslots; } /* If SLOT < 0, unload the current slot. Otherwise, try to load SLOT. */ static int cdrom_load_unload(struct cdrom_device_info *cdi, int slot) { struct packet_command cgc; cd_dbg(CD_CHANGER, "entering cdrom_load_unload()\n"); if (cdi->sanyo_slot && slot < 0) return 0; init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_LOAD_UNLOAD; cgc.cmd[4] = 2 + (slot >= 0); cgc.cmd[8] = slot; cgc.timeout = 60 * HZ; /* The Sanyo 3 CD changer uses byte 7 of the GPCMD_TEST_UNIT_READY to command to switch CDs instead of using the GPCMD_LOAD_UNLOAD opcode. */ if (cdi->sanyo_slot && -1 < slot) { cgc.cmd[0] = GPCMD_TEST_UNIT_READY; cgc.cmd[7] = slot; cgc.cmd[4] = cgc.cmd[8] = 0; cdi->sanyo_slot = slot ? slot : 3; } return cdi->ops->generic_packet(cdi, &cgc); } static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot) { struct cdrom_changer_info *info; int curslot; int ret; cd_dbg(CD_CHANGER, "entering cdrom_select_disc()\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -EDRIVE_CANT_DO_THIS; if (cdi->ops->check_events) cdi->ops->check_events(cdi, 0, slot); else cdi->ops->media_changed(cdi, slot); if (slot == CDSL_NONE) { /* set media changed bits, on both queues */ cdi->mc_flags = 0x3; return cdrom_load_unload(cdi, -1); } info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((ret = cdrom_read_mech_status(cdi, info))) { kfree(info); return ret; } curslot = info->hdr.curslot; kfree(info); if (cdi->use_count > 1 || cdi->keeplocked) { if (slot == CDSL_CURRENT) { return curslot; } else { return -EBUSY; } } /* Specifying CDSL_CURRENT will attempt to load the currnet slot, which is useful if it had been previously unloaded. Whether it can or not, it returns the current slot. Similarly, if slot happens to be the current one, we still try and load it. */ if (slot == CDSL_CURRENT) slot = curslot; /* set media changed bits on both queues */ cdi->mc_flags = 0x3; if ((ret = cdrom_load_unload(cdi, slot))) return ret; return slot; } /* * As cdrom implements an extra ioctl consumer for media changed * event, it needs to buffer ->check_events() output, such that event * is not lost for both the usual VFS and ioctl paths. * cdi->{vfs|ioctl}_events are used to buffer pending events for each * path. * * XXX: Locking is non-existent. cdi->ops->check_events() can be * called in parallel and buffering fields are accessed without any * exclusion. The original media_changed code had the same problem. * It might be better to simply deprecate CDROM_MEDIA_CHANGED ioctl * and remove this cruft altogether. It doesn't have much usefulness * at this point. */ static void cdrom_update_events(struct cdrom_device_info *cdi, unsigned int clearing) { unsigned int events; events = cdi->ops->check_events(cdi, clearing, CDSL_CURRENT); cdi->vfs_events |= events; cdi->ioctl_events |= events; } unsigned int cdrom_check_events(struct cdrom_device_info *cdi, unsigned int clearing) { unsigned int events; cdrom_update_events(cdi, clearing); events = cdi->vfs_events; cdi->vfs_events = 0; return events; } EXPORT_SYMBOL(cdrom_check_events); /* We want to make media_changed accessible to the user through an * ioctl. The main problem now is that we must double-buffer the * low-level implementation, to assure that the VFS and the user both * see a medium change once. */ static int media_changed(struct cdrom_device_info *cdi, int queue) { unsigned int mask = (1 << (queue & 1)); int ret = !!(cdi->mc_flags & mask); bool changed; if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return ret; /* changed since last call? */ if (cdi->ops->check_events) { BUG_ON(!queue); /* shouldn't be called from VFS path */ cdrom_update_events(cdi, DISK_EVENT_MEDIA_CHANGE); changed = cdi->ioctl_events & DISK_EVENT_MEDIA_CHANGE; cdi->ioctl_events = 0; } else changed = cdi->ops->media_changed(cdi, CDSL_CURRENT); if (changed) { cdi->mc_flags = 0x3; /* set bit on both queues */ ret |= 1; cdi->media_written = 0; } cdi->mc_flags &= ~mask; /* clear bit */ return ret; } int cdrom_media_changed(struct cdrom_device_info *cdi) { /* This talks to the VFS, which doesn't like errors - just 1 or 0. * Returning "0" is always safe (media hasn't been changed). Do that * if the low-level cdrom driver dosn't support media changed. */ if (cdi == NULL || cdi->ops->media_changed == NULL) return 0; if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return 0; return media_changed(cdi, 0); } /* Requests to the low-level drivers will /always/ be done in the following format convention: CDROM_LBA: all data-related requests. CDROM_MSF: all audio-related requests. However, a low-level implementation is allowed to refuse this request, and return information in its own favorite format. It doesn't make sense /at all/ to ask for a play_audio in LBA format, or ask for multi-session info in MSF format. However, for backward compatibility these format requests will be satisfied, but the requests to the low-level drivers will be sanitized in the more meaningful format indicated above. */ static void sanitize_format(union cdrom_addr *addr, u_char * curr, u_char requested) { if (*curr == requested) return; /* nothing to be done! */ if (requested == CDROM_LBA) { addr->lba = (int) addr->msf.frame + 75 * (addr->msf.second - 2 + 60 * addr->msf.minute); } else { /* CDROM_MSF */ int lba = addr->lba; addr->msf.frame = lba % 75; lba /= 75; lba += 2; addr->msf.second = lba % 60; addr->msf.minute = lba / 60; } *curr = requested; } void init_cdrom_command(struct packet_command *cgc, void *buf, int len, int type) { memset(cgc, 0, sizeof(struct packet_command)); if (buf) memset(buf, 0, len); cgc->buffer = (char *) buf; cgc->buflen = len; cgc->data_direction = type; cgc->timeout = CDROM_DEF_TIMEOUT; } /* DVD handling */ #define copy_key(dest,src) memcpy((dest), (src), sizeof(dvd_key)) #define copy_chal(dest,src) memcpy((dest), (src), sizeof(dvd_challenge)) static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type) { cgc->cmd[0] = GPCMD_REPORT_KEY; cgc->cmd[10] = type | (agid << 6); switch (type) { case 0: case 8: case 5: { cgc->buflen = 8; break; } case 1: { cgc->buflen = 16; break; } case 2: case 4: { cgc->buflen = 12; break; } } cgc->cmd[9] = cgc->buflen; cgc->data_direction = CGC_DATA_READ; } static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type) { cgc->cmd[0] = GPCMD_SEND_KEY; cgc->cmd[10] = type | (agid << 6); switch (type) { case 1: { cgc->buflen = 16; break; } case 3: { cgc->buflen = 12; break; } case 6: { cgc->buflen = 8; break; } } cgc->cmd[9] = cgc->buflen; cgc->data_direction = CGC_DATA_WRITE; } static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai) { int ret; u_char buf[20]; struct packet_command cgc; const struct cdrom_device_ops *cdo = cdi->ops; rpc_state_t rpc_state; memset(buf, 0, sizeof(buf)); init_cdrom_command(&cgc, buf, 0, CGC_DATA_READ); switch (ai->type) { /* LU data send */ case DVD_LU_SEND_AGID: cd_dbg(CD_DVD, "entering DVD_LU_SEND_AGID\n"); cgc.quiet = 1; setup_report_key(&cgc, ai->lsa.agid, 0); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lsa.agid = buf[7] >> 6; /* Returning data, let host change state */ break; case DVD_LU_SEND_KEY1: cd_dbg(CD_DVD, "entering DVD_LU_SEND_KEY1\n"); setup_report_key(&cgc, ai->lsk.agid, 2); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; copy_key(ai->lsk.key, &buf[4]); /* Returning data, let host change state */ break; case DVD_LU_SEND_CHALLENGE: cd_dbg(CD_DVD, "entering DVD_LU_SEND_CHALLENGE\n"); setup_report_key(&cgc, ai->lsc.agid, 1); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; copy_chal(ai->lsc.chal, &buf[4]); /* Returning data, let host change state */ break; /* Post-auth key */ case DVD_LU_SEND_TITLE_KEY: cd_dbg(CD_DVD, "entering DVD_LU_SEND_TITLE_KEY\n"); cgc.quiet = 1; setup_report_key(&cgc, ai->lstk.agid, 4); cgc.cmd[5] = ai->lstk.lba; cgc.cmd[4] = ai->lstk.lba >> 8; cgc.cmd[3] = ai->lstk.lba >> 16; cgc.cmd[2] = ai->lstk.lba >> 24; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lstk.cpm = (buf[4] >> 7) & 1; ai->lstk.cp_sec = (buf[4] >> 6) & 1; ai->lstk.cgms = (buf[4] >> 4) & 3; copy_key(ai->lstk.title_key, &buf[5]); /* Returning data, let host change state */ break; case DVD_LU_SEND_ASF: cd_dbg(CD_DVD, "entering DVD_LU_SEND_ASF\n"); setup_report_key(&cgc, ai->lsasf.agid, 5); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lsasf.asf = buf[7] & 1; break; /* LU data receive (LU changes state) */ case DVD_HOST_SEND_CHALLENGE: cd_dbg(CD_DVD, "entering DVD_HOST_SEND_CHALLENGE\n"); setup_send_key(&cgc, ai->hsc.agid, 1); buf[1] = 0xe; copy_chal(&buf[4], ai->hsc.chal); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->type = DVD_LU_SEND_KEY1; break; case DVD_HOST_SEND_KEY2: cd_dbg(CD_DVD, "entering DVD_HOST_SEND_KEY2\n"); setup_send_key(&cgc, ai->hsk.agid, 3); buf[1] = 0xa; copy_key(&buf[4], ai->hsk.key); if ((ret = cdo->generic_packet(cdi, &cgc))) { ai->type = DVD_AUTH_FAILURE; return ret; } ai->type = DVD_AUTH_ESTABLISHED; break; /* Misc */ case DVD_INVALIDATE_AGID: cgc.quiet = 1; cd_dbg(CD_DVD, "entering DVD_INVALIDATE_AGID\n"); setup_report_key(&cgc, ai->lsa.agid, 0x3f); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; break; /* Get region settings */ case DVD_LU_SEND_RPC_STATE: cd_dbg(CD_DVD, "entering DVD_LU_SEND_RPC_STATE\n"); setup_report_key(&cgc, 0, 8); memset(&rpc_state, 0, sizeof(rpc_state_t)); cgc.buffer = (char *) &rpc_state; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lrpcs.type = rpc_state.type_code; ai->lrpcs.vra = rpc_state.vra; ai->lrpcs.ucca = rpc_state.ucca; ai->lrpcs.region_mask = rpc_state.region_mask; ai->lrpcs.rpc_scheme = rpc_state.rpc_scheme; break; /* Set region settings */ case DVD_HOST_SEND_RPC_STATE: cd_dbg(CD_DVD, "entering DVD_HOST_SEND_RPC_STATE\n"); setup_send_key(&cgc, 0, 6); buf[1] = 6; buf[4] = ai->hrpcs.pdrc; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; break; default: cd_dbg(CD_WARNING, "Invalid DVD key ioctl (%d)\n", ai->type); return -ENOTTY; } return 0; } static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { unsigned char buf[21], *base; struct dvd_layer *layer; const struct cdrom_device_ops *cdo = cdi->ops; int ret, layer_num = s->physical.layer_num; if (layer_num >= DVD_LAYERS) return -EINVAL; init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[6] = layer_num; cgc->cmd[7] = s->type; cgc->cmd[9] = cgc->buflen & 0xff; /* * refrain from reporting errors on non-existing layers (mainly) */ cgc->quiet = 1; ret = cdo->generic_packet(cdi, cgc); if (ret) return ret; base = &buf[4]; layer = &s->physical.layer[layer_num]; /* * place the data... really ugly, but at least we won't have to * worry about endianess in userspace. */ memset(layer, 0, sizeof(*layer)); layer->book_version = base[0] & 0xf; layer->book_type = base[0] >> 4; layer->min_rate = base[1] & 0xf; layer->disc_size = base[1] >> 4; layer->layer_type = base[2] & 0xf; layer->track_path = (base[2] >> 4) & 1; layer->nlayers = (base[2] >> 5) & 3; layer->track_density = base[3] & 0xf; layer->linear_density = base[3] >> 4; layer->start_sector = base[5] << 16 | base[6] << 8 | base[7]; layer->end_sector = base[9] << 16 | base[10] << 8 | base[11]; layer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15]; layer->bca = base[16] >> 7; return 0; } static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret; u_char buf[8]; const struct cdrom_device_ops *cdo = cdi->ops; init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[6] = s->copyright.layer_num; cgc->cmd[7] = s->type; cgc->cmd[8] = cgc->buflen >> 8; cgc->cmd[9] = cgc->buflen & 0xff; ret = cdo->generic_packet(cdi, cgc); if (ret) return ret; s->copyright.cpst = buf[4]; s->copyright.rmi = buf[5]; return 0; } static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret, size; u_char *buf; const struct cdrom_device_ops *cdo = cdi->ops; size = sizeof(s->disckey.value) + 4; buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; init_cdrom_command(cgc, buf, size, CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[7] = s->type; cgc->cmd[8] = size >> 8; cgc->cmd[9] = size & 0xff; cgc->cmd[10] = s->disckey.agid << 6; ret = cdo->generic_packet(cdi, cgc); if (!ret) memcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value)); kfree(buf); return ret; } static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret, size = 4 + 188; u_char *buf; const struct cdrom_device_ops *cdo = cdi->ops; buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; init_cdrom_command(cgc, buf, size, CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[7] = s->type; cgc->cmd[9] = cgc->buflen & 0xff; ret = cdo->generic_packet(cdi, cgc); if (ret) goto out; s->bca.len = buf[0] << 8 | buf[1]; if (s->bca.len < 12 || s->bca.len > 188) { cd_dbg(CD_WARNING, "Received invalid BCA length (%d)\n", s->bca.len); ret = -EIO; goto out; } memcpy(s->bca.value, &buf[4], s->bca.len); ret = 0; out: kfree(buf); return ret; } static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret = 0, size; u_char *buf; const struct cdrom_device_ops *cdo = cdi->ops; size = sizeof(s->manufact.value) + 4; buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; init_cdrom_command(cgc, buf, size, CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[7] = s->type; cgc->cmd[8] = size >> 8; cgc->cmd[9] = size & 0xff; ret = cdo->generic_packet(cdi, cgc); if (ret) goto out; s->manufact.len = buf[0] << 8 | buf[1]; if (s->manufact.len < 0) { cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d)\n", s->manufact.len); ret = -EIO; } else { if (s->manufact.len > 2048) { cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d): truncating to 2048\n", s->manufact.len); s->manufact.len = 2048; } memcpy(s->manufact.value, &buf[4], s->manufact.len); } out: kfree(buf); return ret; } static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { switch (s->type) { case DVD_STRUCT_PHYSICAL: return dvd_read_physical(cdi, s, cgc); case DVD_STRUCT_COPYRIGHT: return dvd_read_copyright(cdi, s, cgc); case DVD_STRUCT_DISCKEY: return dvd_read_disckey(cdi, s, cgc); case DVD_STRUCT_BCA: return dvd_read_bca(cdi, s, cgc); case DVD_STRUCT_MANUFACT: return dvd_read_manufact(cdi, s, cgc); default: cd_dbg(CD_WARNING, ": Invalid DVD structure read requested (%d)\n", s->type); return -EINVAL; } } int cdrom_mode_sense(struct cdrom_device_info *cdi, struct packet_command *cgc, int page_code, int page_control) { const struct cdrom_device_ops *cdo = cdi->ops; memset(cgc->cmd, 0, sizeof(cgc->cmd)); cgc->cmd[0] = GPCMD_MODE_SENSE_10; cgc->cmd[2] = page_code | (page_control << 6); cgc->cmd[7] = cgc->buflen >> 8; cgc->cmd[8] = cgc->buflen & 0xff; cgc->data_direction = CGC_DATA_READ; return cdo->generic_packet(cdi, cgc); } int cdrom_mode_select(struct cdrom_device_info *cdi, struct packet_command *cgc) { const struct cdrom_device_ops *cdo = cdi->ops; memset(cgc->cmd, 0, sizeof(cgc->cmd)); memset(cgc->buffer, 0, 2); cgc->cmd[0] = GPCMD_MODE_SELECT_10; cgc->cmd[1] = 0x10; /* PF */ cgc->cmd[7] = cgc->buflen >> 8; cgc->cmd[8] = cgc->buflen & 0xff; cgc->data_direction = CGC_DATA_WRITE; return cdo->generic_packet(cdi, cgc); } static int cdrom_read_subchannel(struct cdrom_device_info *cdi, struct cdrom_subchnl *subchnl, int mcn) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; char buffer[32]; int ret; init_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ); cgc.cmd[0] = GPCMD_READ_SUBCHANNEL; cgc.cmd[1] = subchnl->cdsc_format;/* MSF or LBA addressing */ cgc.cmd[2] = 0x40; /* request subQ data */ cgc.cmd[3] = mcn ? 2 : 1; cgc.cmd[8] = 16; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; subchnl->cdsc_audiostatus = cgc.buffer[1]; subchnl->cdsc_ctrl = cgc.buffer[5] & 0xf; subchnl->cdsc_trk = cgc.buffer[6]; subchnl->cdsc_ind = cgc.buffer[7]; if (subchnl->cdsc_format == CDROM_LBA) { subchnl->cdsc_absaddr.lba = ((cgc.buffer[8] << 24) | (cgc.buffer[9] << 16) | (cgc.buffer[10] << 8) | (cgc.buffer[11])); subchnl->cdsc_reladdr.lba = ((cgc.buffer[12] << 24) | (cgc.buffer[13] << 16) | (cgc.buffer[14] << 8) | (cgc.buffer[15])); } else { subchnl->cdsc_reladdr.msf.minute = cgc.buffer[13]; subchnl->cdsc_reladdr.msf.second = cgc.buffer[14]; subchnl->cdsc_reladdr.msf.frame = cgc.buffer[15]; subchnl->cdsc_absaddr.msf.minute = cgc.buffer[9]; subchnl->cdsc_absaddr.msf.second = cgc.buffer[10]; subchnl->cdsc_absaddr.msf.frame = cgc.buffer[11]; } return 0; } /* * Specific READ_10 interface */ static int cdrom_read_cd(struct cdrom_device_info *cdi, struct packet_command *cgc, int lba, int blocksize, int nblocks) { const struct cdrom_device_ops *cdo = cdi->ops; memset(&cgc->cmd, 0, sizeof(cgc->cmd)); cgc->cmd[0] = GPCMD_READ_10; cgc->cmd[2] = (lba >> 24) & 0xff; cgc->cmd[3] = (lba >> 16) & 0xff; cgc->cmd[4] = (lba >> 8) & 0xff; cgc->cmd[5] = lba & 0xff; cgc->cmd[6] = (nblocks >> 16) & 0xff; cgc->cmd[7] = (nblocks >> 8) & 0xff; cgc->cmd[8] = nblocks & 0xff; cgc->buflen = blocksize * nblocks; return cdo->generic_packet(cdi, cgc); } /* very generic interface for reading the various types of blocks */ static int cdrom_read_block(struct cdrom_device_info *cdi, struct packet_command *cgc, int lba, int nblocks, int format, int blksize) { const struct cdrom_device_ops *cdo = cdi->ops; memset(&cgc->cmd, 0, sizeof(cgc->cmd)); cgc->cmd[0] = GPCMD_READ_CD; /* expected sector size - cdda,mode1,etc. */ cgc->cmd[1] = format << 2; /* starting address */ cgc->cmd[2] = (lba >> 24) & 0xff; cgc->cmd[3] = (lba >> 16) & 0xff; cgc->cmd[4] = (lba >> 8) & 0xff; cgc->cmd[5] = lba & 0xff; /* number of blocks */ cgc->cmd[6] = (nblocks >> 16) & 0xff; cgc->cmd[7] = (nblocks >> 8) & 0xff; cgc->cmd[8] = nblocks & 0xff; cgc->buflen = blksize * nblocks; /* set the header info returned */ switch (blksize) { case CD_FRAMESIZE_RAW0 : cgc->cmd[9] = 0x58; break; case CD_FRAMESIZE_RAW1 : cgc->cmd[9] = 0x78; break; case CD_FRAMESIZE_RAW : cgc->cmd[9] = 0xf8; break; default : cgc->cmd[9] = 0x10; } return cdo->generic_packet(cdi, cgc); } static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf, int lba, int nframes) { struct packet_command cgc; int ret = 0; int nr; cdi->last_sense = 0; memset(&cgc, 0, sizeof(cgc)); /* * start with will ra.nframes size, back down if alloc fails */ nr = nframes; do { cgc.buffer = kmalloc(CD_FRAMESIZE_RAW * nr, GFP_KERNEL); if (cgc.buffer) break; nr >>= 1; } while (nr); if (!nr) return -ENOMEM; cgc.data_direction = CGC_DATA_READ; while (nframes > 0) { if (nr > nframes) nr = nframes; ret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW); if (ret) break; if (copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) { ret = -EFAULT; break; } ubuf += CD_FRAMESIZE_RAW * nr; nframes -= nr; lba += nr; } kfree(cgc.buffer); return ret; } static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf, int lba, int nframes) { struct request_queue *q = cdi->disk->queue; struct request *rq; struct scsi_request *req; struct bio *bio; unsigned int len; int nr, ret = 0; if (!q) return -ENXIO; if (!blk_queue_scsi_passthrough(q)) { WARN_ONCE(true, "Attempt read CDDA info through a non-SCSI queue\n"); return -EINVAL; } cdi->last_sense = 0; while (nframes) { nr = nframes; if (cdi->cdda_method == CDDA_BPC_SINGLE) nr = 1; if (nr * CD_FRAMESIZE_RAW > (queue_max_sectors(q) << 9)) nr = (queue_max_sectors(q) << 9) / CD_FRAMESIZE_RAW; len = nr * CD_FRAMESIZE_RAW; rq = blk_get_request(q, REQ_OP_SCSI_IN, GFP_KERNEL); if (IS_ERR(rq)) { ret = PTR_ERR(rq); break; } req = scsi_req(rq); ret = blk_rq_map_user(q, rq, NULL, ubuf, len, GFP_KERNEL); if (ret) { blk_put_request(rq); break; } req->cmd[0] = GPCMD_READ_CD; req->cmd[1] = 1 << 2; req->cmd[2] = (lba >> 24) & 0xff; req->cmd[3] = (lba >> 16) & 0xff; req->cmd[4] = (lba >> 8) & 0xff; req->cmd[5] = lba & 0xff; req->cmd[6] = (nr >> 16) & 0xff; req->cmd[7] = (nr >> 8) & 0xff; req->cmd[8] = nr & 0xff; req->cmd[9] = 0xf8; req->cmd_len = 12; rq->timeout = 60 * HZ; bio = rq->bio; blk_execute_rq(q, cdi->disk, rq, 0); if (scsi_req(rq)->result) { struct request_sense *s = req->sense; ret = -EIO; cdi->last_sense = s->sense_key; } if (blk_rq_unmap_user(bio)) ret = -EFAULT; blk_put_request(rq); if (ret) break; nframes -= nr; lba += nr; ubuf += len; } return ret; } static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf, int lba, int nframes) { int ret; if (cdi->cdda_method == CDDA_OLD) return cdrom_read_cdda_old(cdi, ubuf, lba, nframes); retry: /* * for anything else than success and io error, we need to retry */ ret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes); if (!ret || ret != -EIO) return ret; /* * I've seen drives get sense 4/8/3 udma crc errors on multi * frame dma, so drop to single frame dma if we need to */ if (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) { pr_info("dropping to single frame dma\n"); cdi->cdda_method = CDDA_BPC_SINGLE; goto retry; } /* * so we have an io error of some sort with multi frame dma. if the * condition wasn't a hardware error * problems, not for any error */ if (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b) return ret; pr_info("dropping to old style cdda (sense=%x)\n", cdi->last_sense); cdi->cdda_method = CDDA_OLD; return cdrom_read_cdda_old(cdi, ubuf, lba, nframes); } static int cdrom_ioctl_multisession(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_multisession ms_info; u8 requested_format; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMMULTISESSION\n"); if (!(cdi->ops->capability & CDC_MULTI_SESSION)) return -ENOSYS; if (copy_from_user(&ms_info, argp, sizeof(ms_info))) return -EFAULT; requested_format = ms_info.addr_format; if (requested_format != CDROM_MSF && requested_format != CDROM_LBA) return -EINVAL; ms_info.addr_format = CDROM_LBA; ret = cdi->ops->get_last_session(cdi, &ms_info); if (ret) return ret; sanitize_format(&ms_info.addr, &ms_info.addr_format, requested_format); if (copy_to_user(argp, &ms_info, sizeof(ms_info))) return -EFAULT; cd_dbg(CD_DO_IOCTL, "CDROMMULTISESSION successful\n"); return 0; } static int cdrom_ioctl_eject(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT\n"); if (!CDROM_CAN(CDC_OPEN_TRAY)) return -ENOSYS; if (cdi->use_count != 1 || cdi->keeplocked) return -EBUSY; if (CDROM_CAN(CDC_LOCK)) { int ret = cdi->ops->lock_door(cdi, 0); if (ret) return ret; } return cdi->ops->tray_move(cdi, 1); } static int cdrom_ioctl_closetray(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROMCLOSETRAY\n"); if (!CDROM_CAN(CDC_CLOSE_TRAY)) return -ENOSYS; return cdi->ops->tray_move(cdi, 0); } static int cdrom_ioctl_eject_sw(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT_SW\n"); if (!CDROM_CAN(CDC_OPEN_TRAY)) return -ENOSYS; if (cdi->keeplocked) return -EBUSY; cdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT); if (arg) cdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT; return 0; } static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi, unsigned long arg) { struct cdrom_changer_info *info; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n"); if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return -ENOSYS; /* cannot select disc or select current disc */ if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT) return media_changed(cdi, 1); if ((unsigned int)arg >= cdi->capacity) return -EINVAL; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; ret = cdrom_read_mech_status(cdi, info); if (!ret) ret = info->slots[arg].change; kfree(info); return ret; } static int cdrom_ioctl_set_options(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SET_OPTIONS\n"); /* * Options need to be in sync with capability. * Too late for that, so we have to check each one separately. */ switch (arg) { case CDO_USE_FFLAGS: case CDO_CHECK_TYPE: break; case CDO_LOCK: if (!CDROM_CAN(CDC_LOCK)) return -ENOSYS; break; case 0: return cdi->options; /* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */ default: if (!CDROM_CAN(arg)) return -ENOSYS; } cdi->options |= (int) arg; return cdi->options; } static int cdrom_ioctl_clear_options(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_CLEAR_OPTIONS\n"); cdi->options &= ~(int) arg; return cdi->options; } static int cdrom_ioctl_select_speed(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_SPEED\n"); if (!CDROM_CAN(CDC_SELECT_SPEED)) return -ENOSYS; return cdi->ops->select_speed(cdi, arg); } static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -ENOSYS; if (arg != CDSL_CURRENT && arg != CDSL_NONE) { if ((int)arg >= cdi->capacity) return -EINVAL; } /* * ->select_disc is a hook to allow a driver-specific way of * seleting disc. However, since there is no equivalent hook for * cdrom_slot_status this may not actually be useful... */ if (cdi->ops->select_disc) return cdi->ops->select_disc(cdi, arg); cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n"); return cdrom_select_disc(cdi, arg); } static int cdrom_ioctl_reset(struct cdrom_device_info *cdi, struct block_device *bdev) { cd_dbg(CD_DO_IOCTL, "entering CDROM_RESET\n"); if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (!CDROM_CAN(CDC_RESET)) return -ENOSYS; invalidate_bdev(bdev); return cdi->ops->reset(cdi); } static int cdrom_ioctl_lock_door(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "%socking door\n", arg ? "L" : "Unl"); if (!CDROM_CAN(CDC_LOCK)) return -EDRIVE_CANT_DO_THIS; cdi->keeplocked = arg ? 1 : 0; /* * Don't unlock the door on multiple opens by default, but allow * root to do so. */ if (cdi->use_count != 1 && !arg && !capable(CAP_SYS_ADMIN)) return -EBUSY; return cdi->ops->lock_door(cdi, arg); } static int cdrom_ioctl_debug(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "%sabling debug\n", arg ? "En" : "Dis"); if (!capable(CAP_SYS_ADMIN)) return -EACCES; debug = arg ? 1 : 0; return debug; } static int cdrom_ioctl_get_capability(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_CAPABILITY\n"); return (cdi->ops->capability & ~cdi->mask); } /* * The following function is implemented, although very few audio * discs give Universal Product Code information, which should just be * the Medium Catalog Number on the box. Note, that the way the code * is written on the CD is /not/ uniform across all discs! */ static int cdrom_ioctl_get_mcn(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_mcn mcn; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_MCN\n"); if (!(cdi->ops->capability & CDC_MCN)) return -ENOSYS; ret = cdi->ops->get_mcn(cdi, &mcn); if (ret) return ret; if (copy_to_user(argp, &mcn, sizeof(mcn))) return -EFAULT; cd_dbg(CD_DO_IOCTL, "CDROM_GET_MCN successful\n"); return 0; } static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (((int)arg >= cdi->capacity)) return -EINVAL; return cdrom_slot_status(cdi, arg); } /* * Ok, this is where problems start. The current interface for the * CDROM_DISC_STATUS ioctl is flawed. It makes the false assumption that * CDs are all CDS_DATA_1 or all CDS_AUDIO, etc. Unfortunately, while this * is often the case, it is also very common for CDs to have some tracks * with data, and some tracks with audio. Just because I feel like it, * I declare the following to be the best way to cope. If the CD has ANY * data tracks on it, it will be returned as a data CD. If it has any XA * tracks, I will return it as that. Now I could simplify this interface * by combining these returns with the above, but this more clearly * demonstrates the problem with the current interface. Too bad this * wasn't designed to use bitmasks... -Erik * * Well, now we have the option CDS_MIXED: a mixed-type CD. * User level programmers might feel the ioctl is not very useful. * ---david */ static int cdrom_ioctl_disc_status(struct cdrom_device_info *cdi) { tracktype tracks; cd_dbg(CD_DO_IOCTL, "entering CDROM_DISC_STATUS\n"); cdrom_count_tracks(cdi, &tracks); if (tracks.error) return tracks.error; /* Policy mode on */ if (tracks.audio > 0) { if (!tracks.data && !tracks.cdi && !tracks.xa) return CDS_AUDIO; else return CDS_MIXED; } if (tracks.cdi > 0) return CDS_XA_2_2; if (tracks.xa > 0) return CDS_XA_2_1; if (tracks.data > 0) return CDS_DATA_1; /* Policy mode off */ cd_dbg(CD_WARNING, "This disc doesn't have any tracks I recognize!\n"); return CDS_NO_INFO; } static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROM_CHANGER_NSLOTS\n"); return cdi->capacity; } static int cdrom_ioctl_get_subchnl(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_subchnl q; u8 requested, back; int ret; /* cd_dbg(CD_DO_IOCTL,"entering CDROMSUBCHNL\n");*/ if (copy_from_user(&q, argp, sizeof(q))) return -EFAULT; requested = q.cdsc_format; if (requested != CDROM_MSF && requested != CDROM_LBA) return -EINVAL; q.cdsc_format = CDROM_MSF; ret = cdi->ops->audio_ioctl(cdi, CDROMSUBCHNL, &q); if (ret) return ret; back = q.cdsc_format; /* local copy */ sanitize_format(&q.cdsc_absaddr, &back, requested); sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested); if (copy_to_user(argp, &q, sizeof(q))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */ return 0; } static int cdrom_ioctl_read_tochdr(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_tochdr header; int ret; /* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCHDR\n"); */ if (copy_from_user(&header, argp, sizeof(header))) return -EFAULT; ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header); if (ret) return ret; if (copy_to_user(argp, &header, sizeof(header))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCHDR successful\n"); */ return 0; } static int cdrom_ioctl_read_tocentry(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_tocentry entry; u8 requested_format; int ret; /* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCENTRY\n"); */ if (copy_from_user(&entry, argp, sizeof(entry))) return -EFAULT; requested_format = entry.cdte_format; if (requested_format != CDROM_MSF && requested_format != CDROM_LBA) return -EINVAL; /* make interface to low-level uniform */ entry.cdte_format = CDROM_MSF; ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry); if (ret) return ret; sanitize_format(&entry.cdte_addr, &entry.cdte_format, requested_format); if (copy_to_user(argp, &entry, sizeof(entry))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCENTRY successful\n"); */ return 0; } static int cdrom_ioctl_play_msf(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_msf msf; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; if (copy_from_user(&msf, argp, sizeof(msf))) return -EFAULT; return cdi->ops->audio_ioctl(cdi, CDROMPLAYMSF, &msf); } static int cdrom_ioctl_play_trkind(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_ti ti; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYTRKIND\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; if (copy_from_user(&ti, argp, sizeof(ti))) return -EFAULT; ret = check_for_audio_disc(cdi, cdi->ops); if (ret) return ret; return cdi->ops->audio_ioctl(cdi, CDROMPLAYTRKIND, &ti); } static int cdrom_ioctl_volctrl(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_volctrl volume; cd_dbg(CD_DO_IOCTL, "entering CDROMVOLCTRL\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; if (copy_from_user(&volume, argp, sizeof(volume))) return -EFAULT; return cdi->ops->audio_ioctl(cdi, CDROMVOLCTRL, &volume); } static int cdrom_ioctl_volread(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_volctrl volume; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMVOLREAD\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; ret = cdi->ops->audio_ioctl(cdi, CDROMVOLREAD, &volume); if (ret) return ret; if (copy_to_user(argp, &volume, sizeof(volume))) return -EFAULT; return 0; } static int cdrom_ioctl_audioctl(struct cdrom_device_info *cdi, unsigned int cmd) { int ret; cd_dbg(CD_DO_IOCTL, "doing audio ioctl (start/stop/pause/resume)\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; ret = check_for_audio_disc(cdi, cdi->ops); if (ret) return ret; return cdi->ops->audio_ioctl(cdi, cmd, NULL); } /* * Required when we need to use READ_10 to issue other than 2048 block * reads */ static int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; struct modesel_head mh; memset(&mh, 0, sizeof(mh)); mh.block_desc_length = 0x08; mh.block_length_med = (size >> 8) & 0xff; mh.block_length_lo = size & 0xff; memset(&cgc, 0, sizeof(cgc)); cgc.cmd[0] = 0x15; cgc.cmd[1] = 1 << 4; cgc.cmd[4] = 12; cgc.buflen = sizeof(mh); cgc.buffer = (char *) &mh; cgc.data_direction = CGC_DATA_WRITE; mh.block_desc_length = 0x08; mh.block_length_med = (size >> 8) & 0xff; mh.block_length_lo = size & 0xff; return cdo->generic_packet(cdi, &cgc); } static int cdrom_get_track_info(struct cdrom_device_info *cdi, __u16 track, __u8 type, track_information *ti) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; int ret, buflen; init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ); cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO; cgc.cmd[1] = type & 3; cgc.cmd[4] = (track & 0xff00) >> 8; cgc.cmd[5] = track & 0xff; cgc.cmd[8] = 8; cgc.quiet = 1; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; buflen = be16_to_cpu(ti->track_information_length) + sizeof(ti->track_information_length); if (buflen > sizeof(track_information)) buflen = sizeof(track_information); cgc.cmd[8] = cgc.buflen = buflen; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; /* return actual fill size */ return buflen; } /* return the last written block on the CD-R media. this is for the udf file system. */ int cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written) { struct cdrom_tocentry toc; disc_information di; track_information ti; __u32 last_track; int ret = -1, ti_size; if (!CDROM_CAN(CDC_GENERIC_PACKET)) goto use_toc; ret = cdrom_get_disc_info(cdi, &di); if (ret < (int)(offsetof(typeof(di), last_track_lsb) + sizeof(di.last_track_lsb))) goto use_toc; /* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */ last_track = (di.last_track_msb << 8) | di.last_track_lsb; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); if (ti_size < (int)offsetof(typeof(ti), track_start)) goto use_toc; /* if this track is blank, try the previous. */ if (ti.blank) { if (last_track == 1) goto use_toc; last_track--; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); } if (ti_size < (int)(offsetof(typeof(ti), track_size) + sizeof(ti.track_size))) goto use_toc; /* if last recorded field is valid, return it. */ if (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address) + sizeof(ti.last_rec_address))) { *last_written = be32_to_cpu(ti.last_rec_address); } else { /* make it up instead */ *last_written = be32_to_cpu(ti.track_start) + be32_to_cpu(ti.track_size); if (ti.free_blocks) *last_written -= (be32_to_cpu(ti.free_blocks) + 7); } return 0; /* this is where we end up if the drive either can't do a GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if it doesn't give enough information or fails. then we return the toc contents. */ use_toc: toc.cdte_format = CDROM_MSF; toc.cdte_track = CDROM_LEADOUT; if ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc))) return ret; sanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA); *last_written = toc.cdte_addr.lba; return 0; } /* return the next writable block. also for udf file system. */ static int cdrom_get_next_writable(struct cdrom_device_info *cdi, long *next_writable) { disc_information di; track_information ti; __u16 last_track; int ret, ti_size; if (!CDROM_CAN(CDC_GENERIC_PACKET)) goto use_last_written; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < offsetof(typeof(di), last_track_lsb) + sizeof(di.last_track_lsb)) goto use_last_written; /* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */ last_track = (di.last_track_msb << 8) | di.last_track_lsb; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); if (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start)) goto use_last_written; /* if this track is blank, try the previous. */ if (ti.blank) { if (last_track == 1) goto use_last_written; last_track--; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); if (ti_size < 0) goto use_last_written; } /* if next recordable address field is valid, use it. */ if (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable) + sizeof(ti.next_writable)) { *next_writable = be32_to_cpu(ti.next_writable); return 0; } use_last_written: ret = cdrom_get_last_written(cdi, next_writable); if (ret) { *next_writable = 0; return ret; } else { *next_writable += 7; return 0; } } static noinline int mmc_ioctl_cdrom_read_data(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc, int cmd) { struct request_sense sense; struct cdrom_msf msf; int blocksize = 0, format = 0, lba; int ret; switch (cmd) { case CDROMREADRAW: blocksize = CD_FRAMESIZE_RAW; break; case CDROMREADMODE1: blocksize = CD_FRAMESIZE; format = 2; break; case CDROMREADMODE2: blocksize = CD_FRAMESIZE_RAW0; break; } if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf))) return -EFAULT; lba = msf_to_lba(msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0); /* FIXME: we need upper bound checking, too!! */ if (lba < 0) return -EINVAL; cgc->buffer = kzalloc(blocksize, GFP_KERNEL); if (cgc->buffer == NULL) return -ENOMEM; memset(&sense, 0, sizeof(sense)); cgc->sense = &sense; cgc->data_direction = CGC_DATA_READ; ret = cdrom_read_block(cdi, cgc, lba, 1, format, blocksize); if (ret && sense.sense_key == 0x05 && sense.asc == 0x20 && sense.ascq == 0x00) { /* * SCSI-II devices are not required to support * READ_CD, so let's try switching block size */ /* FIXME: switch back again... */ ret = cdrom_switch_blocksize(cdi, blocksize); if (ret) goto out; cgc->sense = NULL; ret = cdrom_read_cd(cdi, cgc, lba, blocksize, 1); ret |= cdrom_switch_blocksize(cdi, blocksize); } if (!ret && copy_to_user(arg, cgc->buffer, blocksize)) ret = -EFAULT; out: kfree(cgc->buffer); return ret; } static noinline int mmc_ioctl_cdrom_read_audio(struct cdrom_device_info *cdi, void __user *arg) { struct cdrom_read_audio ra; int lba; if (copy_from_user(&ra, (struct cdrom_read_audio __user *)arg, sizeof(ra))) return -EFAULT; if (ra.addr_format == CDROM_MSF) lba = msf_to_lba(ra.addr.msf.minute, ra.addr.msf.second, ra.addr.msf.frame); else if (ra.addr_format == CDROM_LBA) lba = ra.addr.lba; else return -EINVAL; /* FIXME: we need upper bound checking, too!! */ if (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES) return -EINVAL; return cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes); } static noinline int mmc_ioctl_cdrom_subchannel(struct cdrom_device_info *cdi, void __user *arg) { int ret; struct cdrom_subchnl q; u_char requested, back; if (copy_from_user(&q, (struct cdrom_subchnl __user *)arg, sizeof(q))) return -EFAULT; requested = q.cdsc_format; if (!((requested == CDROM_MSF) || (requested == CDROM_LBA))) return -EINVAL; ret = cdrom_read_subchannel(cdi, &q, 0); if (ret) return ret; back = q.cdsc_format; /* local copy */ sanitize_format(&q.cdsc_absaddr, &back, requested); sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested); if (copy_to_user((struct cdrom_subchnl __user *)arg, &q, sizeof(q))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */ return 0; } static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc) { const struct cdrom_device_ops *cdo = cdi->ops; struct cdrom_msf msf; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n"); if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf))) return -EFAULT; cgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF; cgc->cmd[3] = msf.cdmsf_min0; cgc->cmd[4] = msf.cdmsf_sec0; cgc->cmd[5] = msf.cdmsf_frame0; cgc->cmd[6] = msf.cdmsf_min1; cgc->cmd[7] = msf.cdmsf_sec1; cgc->cmd[8] = msf.cdmsf_frame1; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_cdrom_play_blk(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc) { const struct cdrom_device_ops *cdo = cdi->ops; struct cdrom_blk blk; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYBLK\n"); if (copy_from_user(&blk, (struct cdrom_blk __user *)arg, sizeof(blk))) return -EFAULT; cgc->cmd[0] = GPCMD_PLAY_AUDIO_10; cgc->cmd[2] = (blk.from >> 24) & 0xff; cgc->cmd[3] = (blk.from >> 16) & 0xff; cgc->cmd[4] = (blk.from >> 8) & 0xff; cgc->cmd[5] = blk.from & 0xff; cgc->cmd[7] = (blk.len >> 8) & 0xff; cgc->cmd[8] = blk.len & 0xff; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_cdrom_volume(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc, unsigned int cmd) { struct cdrom_volctrl volctrl; unsigned char buffer[32]; char mask[sizeof(buffer)]; unsigned short offset; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMVOLUME\n"); if (copy_from_user(&volctrl, (struct cdrom_volctrl __user *)arg, sizeof(volctrl))) return -EFAULT; cgc->buffer = buffer; cgc->buflen = 24; ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0); if (ret) return ret; /* originally the code depended on buffer[1] to determine how much data is available for transfer. buffer[1] is unfortunately ambigious and the only reliable way seem to be to simply skip over the block descriptor... */ offset = 8 + be16_to_cpu(*(__be16 *)(buffer + 6)); if (offset + 16 > sizeof(buffer)) return -E2BIG; if (offset + 16 > cgc->buflen) { cgc->buflen = offset + 16; ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0); if (ret) return ret; } /* sanity check */ if ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE || buffer[offset + 1] < 14) return -EINVAL; /* now we have the current volume settings. if it was only a CDROMVOLREAD, return these values */ if (cmd == CDROMVOLREAD) { volctrl.channel0 = buffer[offset+9]; volctrl.channel1 = buffer[offset+11]; volctrl.channel2 = buffer[offset+13]; volctrl.channel3 = buffer[offset+15]; if (copy_to_user((struct cdrom_volctrl __user *)arg, &volctrl, sizeof(volctrl))) return -EFAULT; return 0; } /* get the volume mask */ cgc->buffer = mask; ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 1); if (ret) return ret; buffer[offset + 9] = volctrl.channel0 & mask[offset + 9]; buffer[offset + 11] = volctrl.channel1 & mask[offset + 11]; buffer[offset + 13] = volctrl.channel2 & mask[offset + 13]; buffer[offset + 15] = volctrl.channel3 & mask[offset + 15]; /* set volume */ cgc->buffer = buffer + offset - 8; memset(cgc->buffer, 0, 8); return cdrom_mode_select(cdi, cgc); } static noinline int mmc_ioctl_cdrom_start_stop(struct cdrom_device_info *cdi, struct packet_command *cgc, int cmd) { const struct cdrom_device_ops *cdo = cdi->ops; cd_dbg(CD_DO_IOCTL, "entering CDROMSTART/CDROMSTOP\n"); cgc->cmd[0] = GPCMD_START_STOP_UNIT; cgc->cmd[1] = 1; cgc->cmd[4] = (cmd == CDROMSTART) ? 1 : 0; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_cdrom_pause_resume(struct cdrom_device_info *cdi, struct packet_command *cgc, int cmd) { const struct cdrom_device_ops *cdo = cdi->ops; cd_dbg(CD_DO_IOCTL, "entering CDROMPAUSE/CDROMRESUME\n"); cgc->cmd[0] = GPCMD_PAUSE_RESUME; cgc->cmd[8] = (cmd == CDROMRESUME) ? 1 : 0; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_dvd_read_struct(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc) { int ret; dvd_struct *s; int size = sizeof(dvd_struct); if (!CDROM_CAN(CDC_DVD)) return -ENOSYS; s = memdup_user(arg, size); if (IS_ERR(s)) return PTR_ERR(s); cd_dbg(CD_DO_IOCTL, "entering DVD_READ_STRUCT\n"); ret = dvd_read_struct(cdi, s, cgc); if (ret) goto out; if (copy_to_user(arg, s, size)) ret = -EFAULT; out: kfree(s); return ret; } static noinline int mmc_ioctl_dvd_auth(struct cdrom_device_info *cdi, void __user *arg) { int ret; dvd_authinfo ai; if (!CDROM_CAN(CDC_DVD)) return -ENOSYS; cd_dbg(CD_DO_IOCTL, "entering DVD_AUTH\n"); if (copy_from_user(&ai, (dvd_authinfo __user *)arg, sizeof(ai))) return -EFAULT; ret = dvd_do_auth(cdi, &ai); if (ret) return ret; if (copy_to_user((dvd_authinfo __user *)arg, &ai, sizeof(ai))) return -EFAULT; return 0; } static noinline int mmc_ioctl_cdrom_next_writable(struct cdrom_device_info *cdi, void __user *arg) { int ret; long next = 0; cd_dbg(CD_DO_IOCTL, "entering CDROM_NEXT_WRITABLE\n"); ret = cdrom_get_next_writable(cdi, &next); if (ret) return ret; if (copy_to_user((long __user *)arg, &next, sizeof(next))) return -EFAULT; return 0; } static noinline int mmc_ioctl_cdrom_last_written(struct cdrom_device_info *cdi, void __user *arg) { int ret; long last = 0; cd_dbg(CD_DO_IOCTL, "entering CDROM_LAST_WRITTEN\n"); ret = cdrom_get_last_written(cdi, &last); if (ret) return ret; if (copy_to_user((long __user *)arg, &last, sizeof(last))) return -EFAULT; return 0; } static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd, unsigned long arg) { struct packet_command cgc; void __user *userptr = (void __user *)arg; memset(&cgc, 0, sizeof(cgc)); /* build a unified command and queue it through cdo->generic_packet() */ switch (cmd) { case CDROMREADRAW: case CDROMREADMODE1: case CDROMREADMODE2: return mmc_ioctl_cdrom_read_data(cdi, userptr, &cgc, cmd); case CDROMREADAUDIO: return mmc_ioctl_cdrom_read_audio(cdi, userptr); case CDROMSUBCHNL: return mmc_ioctl_cdrom_subchannel(cdi, userptr); case CDROMPLAYMSF: return mmc_ioctl_cdrom_play_msf(cdi, userptr, &cgc); case CDROMPLAYBLK: return mmc_ioctl_cdrom_play_blk(cdi, userptr, &cgc); case CDROMVOLCTRL: case CDROMVOLREAD: return mmc_ioctl_cdrom_volume(cdi, userptr, &cgc, cmd); case CDROMSTART: case CDROMSTOP: return mmc_ioctl_cdrom_start_stop(cdi, &cgc, cmd); case CDROMPAUSE: case CDROMRESUME: return mmc_ioctl_cdrom_pause_resume(cdi, &cgc, cmd); case DVD_READ_STRUCT: return mmc_ioctl_dvd_read_struct(cdi, userptr, &cgc); case DVD_AUTH: return mmc_ioctl_dvd_auth(cdi, userptr); case CDROM_NEXT_WRITABLE: return mmc_ioctl_cdrom_next_writable(cdi, userptr); case CDROM_LAST_WRITTEN: return mmc_ioctl_cdrom_last_written(cdi, userptr); } return -ENOTTY; } /* * Just about every imaginable ioctl is supported in the Uniform layer * these days. * ATAPI / SCSI specific code now mainly resides in mmc_ioctl(). */ int cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int ret; /* * Try the generic SCSI command ioctl's first. */ ret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp); if (ret != -ENOTTY) return ret; switch (cmd) { case CDROMMULTISESSION: return cdrom_ioctl_multisession(cdi, argp); case CDROMEJECT: return cdrom_ioctl_eject(cdi); case CDROMCLOSETRAY: return cdrom_ioctl_closetray(cdi); case CDROMEJECT_SW: return cdrom_ioctl_eject_sw(cdi, arg); case CDROM_MEDIA_CHANGED: return cdrom_ioctl_media_changed(cdi, arg); case CDROM_SET_OPTIONS: return cdrom_ioctl_set_options(cdi, arg); case CDROM_CLEAR_OPTIONS: return cdrom_ioctl_clear_options(cdi, arg); case CDROM_SELECT_SPEED: return cdrom_ioctl_select_speed(cdi, arg); case CDROM_SELECT_DISC: return cdrom_ioctl_select_disc(cdi, arg); case CDROMRESET: return cdrom_ioctl_reset(cdi, bdev); case CDROM_LOCKDOOR: return cdrom_ioctl_lock_door(cdi, arg); case CDROM_DEBUG: return cdrom_ioctl_debug(cdi, arg); case CDROM_GET_CAPABILITY: return cdrom_ioctl_get_capability(cdi); case CDROM_GET_MCN: return cdrom_ioctl_get_mcn(cdi, argp); case CDROM_DRIVE_STATUS: return cdrom_ioctl_drive_status(cdi, arg); case CDROM_DISC_STATUS: return cdrom_ioctl_disc_status(cdi); case CDROM_CHANGER_NSLOTS: return cdrom_ioctl_changer_nslots(cdi); } /* * Use the ioctls that are implemented through the generic_packet() * interface. this may look at bit funny, but if -ENOTTY is * returned that particular ioctl is not implemented and we * let it go through the device specific ones. */ if (CDROM_CAN(CDC_GENERIC_PACKET)) { ret = mmc_ioctl(cdi, cmd, arg); if (ret != -ENOTTY) return ret; } /* * Note: most of the cd_dbg() calls are commented out here, * because they fill up the sys log when CD players poll * the drive. */ switch (cmd) { case CDROMSUBCHNL: return cdrom_ioctl_get_subchnl(cdi, argp); case CDROMREADTOCHDR: return cdrom_ioctl_read_tochdr(cdi, argp); case CDROMREADTOCENTRY: return cdrom_ioctl_read_tocentry(cdi, argp); case CDROMPLAYMSF: return cdrom_ioctl_play_msf(cdi, argp); case CDROMPLAYTRKIND: return cdrom_ioctl_play_trkind(cdi, argp); case CDROMVOLCTRL: return cdrom_ioctl_volctrl(cdi, argp); case CDROMVOLREAD: return cdrom_ioctl_volread(cdi, argp); case CDROMSTART: case CDROMSTOP: case CDROMPAUSE: case CDROMRESUME: return cdrom_ioctl_audioctl(cdi, cmd); } return -ENOSYS; } EXPORT_SYMBOL(cdrom_get_last_written); EXPORT_SYMBOL(register_cdrom); EXPORT_SYMBOL(unregister_cdrom); EXPORT_SYMBOL(cdrom_open); EXPORT_SYMBOL(cdrom_release); EXPORT_SYMBOL(cdrom_ioctl); EXPORT_SYMBOL(cdrom_media_changed); EXPORT_SYMBOL(cdrom_number_of_slots); EXPORT_SYMBOL(cdrom_mode_select); EXPORT_SYMBOL(cdrom_mode_sense); EXPORT_SYMBOL(init_cdrom_command); EXPORT_SYMBOL(cdrom_get_media_event); #ifdef CONFIG_SYSCTL #define CDROM_STR_SIZE 1000 static struct cdrom_sysctl_settings { char info[CDROM_STR_SIZE]; /* general info */ int autoclose; /* close tray upon mount, etc */ int autoeject; /* eject on umount */ int debug; /* turn on debugging messages */ int lock; /* lock the door on device open */ int check; /* check media type */ } cdrom_sysctl_settings; enum cdrom_print_option { CTL_NAME, CTL_SPEED, CTL_SLOTS, CTL_CAPABILITY }; static int cdrom_print_info(const char *header, int val, char *info, int *pos, enum cdrom_print_option option) { const int max_size = sizeof(cdrom_sysctl_settings.info); struct cdrom_device_info *cdi; int ret; ret = scnprintf(info + *pos, max_size - *pos, header); if (!ret) return 1; *pos += ret; list_for_each_entry(cdi, &cdrom_list, list) { switch (option) { case CTL_NAME: ret = scnprintf(info + *pos, max_size - *pos, "\t%s", cdi->name); break; case CTL_SPEED: ret = scnprintf(info + *pos, max_size - *pos, "\t%d", cdi->speed); break; case CTL_SLOTS: ret = scnprintf(info + *pos, max_size - *pos, "\t%d", cdi->capacity); break; case CTL_CAPABILITY: ret = scnprintf(info + *pos, max_size - *pos, "\t%d", CDROM_CAN(val) != 0); break; default: pr_info("invalid option%d\n", option); return 1; } if (!ret) return 1; *pos += ret; } return 0; } static int cdrom_sysctl_info(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int pos; char *info = cdrom_sysctl_settings.info; const int max_size = sizeof(cdrom_sysctl_settings.info); if (!*lenp || (*ppos && !write)) { *lenp = 0; return 0; } mutex_lock(&cdrom_mutex); pos = sprintf(info, "CD-ROM information, " VERSION "\n"); if (cdrom_print_info("\ndrive name:\t", 0, info, &pos, CTL_NAME)) goto done; if (cdrom_print_info("\ndrive speed:\t", 0, info, &pos, CTL_SPEED)) goto done; if (cdrom_print_info("\ndrive # of slots:", 0, info, &pos, CTL_SLOTS)) goto done; if (cdrom_print_info("\nCan close tray:\t", CDC_CLOSE_TRAY, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan open tray:\t", CDC_OPEN_TRAY, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan lock tray:\t", CDC_LOCK, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan change speed:", CDC_SELECT_SPEED, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan select disk:", CDC_SELECT_DISC, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read multisession:", CDC_MULTI_SESSION, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read MCN:\t", CDC_MCN, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nReports media changed:", CDC_MEDIA_CHANGED, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan play audio:\t", CDC_PLAY_AUDIO, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write CD-R:\t", CDC_CD_R, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write CD-RW:", CDC_CD_RW, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read DVD:\t", CDC_DVD, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write DVD-R:", CDC_DVD_R, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write DVD-RAM:", CDC_DVD_RAM, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read MRW:\t", CDC_MRW, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write MRW:\t", CDC_MRW_W, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write RAM:\t", CDC_RAM, info, &pos, CTL_CAPABILITY)) goto done; if (!scnprintf(info + pos, max_size - pos, "\n\n")) goto done; doit: mutex_unlock(&cdrom_mutex); return proc_dostring(ctl, write, buffer, lenp, ppos); done: pr_info("info buffer too small\n"); goto doit; } /* Unfortunately, per device settings are not implemented through procfs/sysctl yet. When they are, this will naturally disappear. For now just update all drives. Later this will become the template on which new registered drives will be based. */ static void cdrom_update_settings(void) { struct cdrom_device_info *cdi; mutex_lock(&cdrom_mutex); list_for_each_entry(cdi, &cdrom_list, list) { if (autoclose && CDROM_CAN(CDC_CLOSE_TRAY)) cdi->options |= CDO_AUTO_CLOSE; else if (!autoclose) cdi->options &= ~CDO_AUTO_CLOSE; if (autoeject && CDROM_CAN(CDC_OPEN_TRAY)) cdi->options |= CDO_AUTO_EJECT; else if (!autoeject) cdi->options &= ~CDO_AUTO_EJECT; if (lockdoor && CDROM_CAN(CDC_LOCK)) cdi->options |= CDO_LOCK; else if (!lockdoor) cdi->options &= ~CDO_LOCK; if (check_media_type) cdi->options |= CDO_CHECK_TYPE; else cdi->options &= ~CDO_CHECK_TYPE; } mutex_unlock(&cdrom_mutex); } static int cdrom_sysctl_handler(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; ret = proc_dointvec(ctl, write, buffer, lenp, ppos); if (write) { /* we only care for 1 or 0. */ autoclose = !!cdrom_sysctl_settings.autoclose; autoeject = !!cdrom_sysctl_settings.autoeject; debug = !!cdrom_sysctl_settings.debug; lockdoor = !!cdrom_sysctl_settings.lock; check_media_type = !!cdrom_sysctl_settings.check; /* update the option flags according to the changes. we don't have per device options through sysctl yet, but we will have and then this will disappear. */ cdrom_update_settings(); } return ret; } /* Place files in /proc/sys/dev/cdrom */ static struct ctl_table cdrom_table[] = { { .procname = "info", .data = &cdrom_sysctl_settings.info, .maxlen = CDROM_STR_SIZE, .mode = 0444, .proc_handler = cdrom_sysctl_info, }, { .procname = "autoclose", .data = &cdrom_sysctl_settings.autoclose, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "autoeject", .data = &cdrom_sysctl_settings.autoeject, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "debug", .data = &cdrom_sysctl_settings.debug, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "lock", .data = &cdrom_sysctl_settings.lock, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "check_media", .data = &cdrom_sysctl_settings.check, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler }, { } }; static struct ctl_table cdrom_cdrom_table[] = { { .procname = "cdrom", .maxlen = 0, .mode = 0555, .child = cdrom_table, }, { } }; /* Make sure that /proc/sys/dev is there */ static struct ctl_table cdrom_root_table[] = { { .procname = "dev", .maxlen = 0, .mode = 0555, .child = cdrom_cdrom_table, }, { } }; static struct ctl_table_header *cdrom_sysctl_header; static void cdrom_sysctl_register(void) { static int initialized; if (initialized == 1) return; cdrom_sysctl_header = register_sysctl_table(cdrom_root_table); /* set the defaults */ cdrom_sysctl_settings.autoclose = autoclose; cdrom_sysctl_settings.autoeject = autoeject; cdrom_sysctl_settings.debug = debug; cdrom_sysctl_settings.lock = lockdoor; cdrom_sysctl_settings.check = check_media_type; initialized = 1; } static void cdrom_sysctl_unregister(void) { if (cdrom_sysctl_header) unregister_sysctl_table(cdrom_sysctl_header); } #else /* CONFIG_SYSCTL */ static void cdrom_sysctl_register(void) { } static void cdrom_sysctl_unregister(void) { } #endif /* CONFIG_SYSCTL */ static int __init cdrom_init(void) { cdrom_sysctl_register(); return 0; } static void __exit cdrom_exit(void) { pr_info("Uniform CD-ROM driver unloaded\n"); cdrom_sysctl_unregister(); } module_init(cdrom_init); module_exit(cdrom_exit); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/bad_121_0
crossvul-cpp_data_good_343_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include "libopensc/internal.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = MIN(file->size, sizeof buf); sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = MIN(file->size, sizeof buf); sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_343_8
crossvul-cpp_data_good_4897_0
/* Router advertisement * Copyright (C) 2005 6WIND <jean-mickael.guerin@6wind.com> * Copyright (C) 1999 Kunihiro Ishiguro * * This file is part of GNU Zebra. * * GNU Zebra is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * GNU Zebra is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Zebra; see the file COPYING. If not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include <zebra.h> #include "memory.h" #include "sockopt.h" #include "thread.h" #include "if.h" #include "log.h" #include "prefix.h" #include "linklist.h" #include "command.h" #include "privs.h" #include "vrf.h" #include "zebra/interface.h" #include "zebra/rtadv.h" #include "zebra/debug.h" #include "zebra/rib.h" #include "zebra/zserv.h" extern struct zebra_privs_t zserv_privs; #if defined (HAVE_IPV6) && defined (HAVE_RTADV) #ifdef OPEN_BSD #include <netinet/icmp6.h> #endif /* If RFC2133 definition is used. */ #ifndef IPV6_JOIN_GROUP #define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP #endif #ifndef IPV6_LEAVE_GROUP #define IPV6_LEAVE_GROUP IPV6_DROP_MEMBERSHIP #endif #define ALLNODE "ff02::1" #define ALLROUTER "ff02::2" extern struct zebra_t zebrad; enum rtadv_event {RTADV_START, RTADV_STOP, RTADV_TIMER, RTADV_TIMER_MSEC, RTADV_READ}; static void rtadv_event (struct zebra_vrf *, enum rtadv_event, int); static int if_join_all_router (int, struct interface *); static int if_leave_all_router (int, struct interface *); static int rtadv_recv_packet (int sock, u_char *buf, int buflen, struct sockaddr_in6 *from, ifindex_t *ifindex, int *hoplimit) { int ret; struct msghdr msg; struct iovec iov; struct cmsghdr *cmsgptr; struct in6_addr dst; char adata[1024]; /* Fill in message and iovec. */ msg.msg_name = (void *) from; msg.msg_namelen = sizeof (struct sockaddr_in6); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = (void *) adata; msg.msg_controllen = sizeof adata; iov.iov_base = buf; iov.iov_len = buflen; /* If recvmsg fail return minus value. */ ret = recvmsg (sock, &msg, 0); if (ret < 0) return ret; for (cmsgptr = ZCMSG_FIRSTHDR(&msg); cmsgptr != NULL; cmsgptr = CMSG_NXTHDR(&msg, cmsgptr)) { /* I want interface index which this packet comes from. */ if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_PKTINFO) { struct in6_pktinfo *ptr; ptr = (struct in6_pktinfo *) CMSG_DATA (cmsgptr); *ifindex = ptr->ipi6_ifindex; memcpy(&dst, &ptr->ipi6_addr, sizeof(ptr->ipi6_addr)); } /* Incoming packet's hop limit. */ if (cmsgptr->cmsg_level == IPPROTO_IPV6 && cmsgptr->cmsg_type == IPV6_HOPLIMIT) { int *hoptr = (int *) CMSG_DATA (cmsgptr); *hoplimit = *hoptr; } } return ret; } #define RTADV_MSG_SIZE 4096 /* Send router advertisement packet. */ static void rtadv_send_packet (int sock, struct interface *ifp) { struct msghdr msg; struct iovec iov; struct cmsghdr *cmsgptr; struct in6_pktinfo *pkt; struct sockaddr_in6 addr; #ifdef HAVE_STRUCT_SOCKADDR_DL struct sockaddr_dl *sdl; #endif /* HAVE_STRUCT_SOCKADDR_DL */ static void *adata = NULL; unsigned char buf[RTADV_MSG_SIZE]; struct nd_router_advert *rtadv; int ret; int len = 0; struct zebra_if *zif; struct rtadv_prefix *rprefix; u_char all_nodes_addr[] = {0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; struct listnode *node; u_int16_t pkt_RouterLifetime; /* * Allocate control message bufffer. This is dynamic because * CMSG_SPACE is not guaranteed not to call a function. Note that * the size will be different on different architectures due to * differing alignment rules. */ if (adata == NULL) { /* XXX Free on shutdown. */ adata = malloc(CMSG_SPACE(sizeof(struct in6_pktinfo))); if (adata == NULL) zlog_err("rtadv_send_packet: can't malloc control data\n"); } /* Logging of packet. */ if (IS_ZEBRA_DEBUG_PACKET) zlog_debug ("Router advertisement send to %s", ifp->name); /* Fill in sockaddr_in6. */ memset (&addr, 0, sizeof (struct sockaddr_in6)); addr.sin6_family = AF_INET6; #ifdef SIN6_LEN addr.sin6_len = sizeof (struct sockaddr_in6); #endif /* SIN6_LEN */ addr.sin6_port = htons (IPPROTO_ICMPV6); IPV6_ADDR_COPY (&addr.sin6_addr, all_nodes_addr); /* Fetch interface information. */ zif = ifp->info; /* Make router advertisement message. */ rtadv = (struct nd_router_advert *) buf; rtadv->nd_ra_type = ND_ROUTER_ADVERT; rtadv->nd_ra_code = 0; rtadv->nd_ra_cksum = 0; rtadv->nd_ra_curhoplimit = 64; /* RFC4191: Default Router Preference is 0 if Router Lifetime is 0. */ rtadv->nd_ra_flags_reserved = zif->rtadv.AdvDefaultLifetime == 0 ? 0 : zif->rtadv.DefaultPreference; rtadv->nd_ra_flags_reserved <<= 3; if (zif->rtadv.AdvManagedFlag) rtadv->nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED; if (zif->rtadv.AdvOtherConfigFlag) rtadv->nd_ra_flags_reserved |= ND_RA_FLAG_OTHER; if (zif->rtadv.AdvHomeAgentFlag) rtadv->nd_ra_flags_reserved |= ND_RA_FLAG_HOME_AGENT; /* Note that according to Neighbor Discovery (RFC 4861 [18]), * AdvDefaultLifetime is by default based on the value of * MaxRtrAdvInterval. AdvDefaultLifetime is used in the Router Lifetime * field of Router Advertisements. Given that this field is expressed * in seconds, a small MaxRtrAdvInterval value can result in a zero * value for this field. To prevent this, routers SHOULD keep * AdvDefaultLifetime in at least one second, even if the use of * MaxRtrAdvInterval would result in a smaller value. -- RFC6275, 7.5 */ pkt_RouterLifetime = zif->rtadv.AdvDefaultLifetime != -1 ? zif->rtadv.AdvDefaultLifetime : MAX (1, 0.003 * zif->rtadv.MaxRtrAdvInterval); rtadv->nd_ra_router_lifetime = htons (pkt_RouterLifetime); rtadv->nd_ra_reachable = htonl (zif->rtadv.AdvReachableTime); rtadv->nd_ra_retransmit = htonl (0); len = sizeof (struct nd_router_advert); /* If both the Home Agent Preference and Home Agent Lifetime are set to * their default values specified above, this option SHOULD NOT be * included in the Router Advertisement messages sent by this home * agent. -- RFC6275, 7.4 */ if ( zif->rtadv.AdvHomeAgentFlag && (zif->rtadv.HomeAgentPreference || zif->rtadv.HomeAgentLifetime != -1) ) { struct nd_opt_homeagent_info *ndopt_hai = (struct nd_opt_homeagent_info *)(buf + len); ndopt_hai->nd_opt_hai_type = ND_OPT_HA_INFORMATION; ndopt_hai->nd_opt_hai_len = 1; ndopt_hai->nd_opt_hai_reserved = 0; ndopt_hai->nd_opt_hai_preference = htons(zif->rtadv.HomeAgentPreference); /* 16-bit unsigned integer. The lifetime associated with the home * agent in units of seconds. The default value is the same as the * Router Lifetime, as specified in the main body of the Router * Advertisement. The maximum value corresponds to 18.2 hours. A * value of 0 MUST NOT be used. -- RFC6275, 7.5 */ ndopt_hai->nd_opt_hai_lifetime = htons ( zif->rtadv.HomeAgentLifetime != -1 ? zif->rtadv.HomeAgentLifetime : MAX (1, pkt_RouterLifetime) /* 0 is OK for RL, but not for HAL*/ ); len += sizeof(struct nd_opt_homeagent_info); } if (zif->rtadv.AdvIntervalOption) { struct nd_opt_adv_interval *ndopt_adv = (struct nd_opt_adv_interval *)(buf + len); ndopt_adv->nd_opt_ai_type = ND_OPT_ADV_INTERVAL; ndopt_adv->nd_opt_ai_len = 1; ndopt_adv->nd_opt_ai_reserved = 0; ndopt_adv->nd_opt_ai_interval = htonl(zif->rtadv.MaxRtrAdvInterval); len += sizeof(struct nd_opt_adv_interval); } /* Fill in prefix. */ for (ALL_LIST_ELEMENTS_RO (zif->rtadv.AdvPrefixList, node, rprefix)) { struct nd_opt_prefix_info *pinfo; pinfo = (struct nd_opt_prefix_info *) (buf + len); pinfo->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION; pinfo->nd_opt_pi_len = 4; pinfo->nd_opt_pi_prefix_len = rprefix->prefix.prefixlen; pinfo->nd_opt_pi_flags_reserved = 0; if (rprefix->AdvOnLinkFlag) pinfo->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK; if (rprefix->AdvAutonomousFlag) pinfo->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO; if (rprefix->AdvRouterAddressFlag) pinfo->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_RADDR; pinfo->nd_opt_pi_valid_time = htonl (rprefix->AdvValidLifetime); pinfo->nd_opt_pi_preferred_time = htonl (rprefix->AdvPreferredLifetime); pinfo->nd_opt_pi_reserved2 = 0; IPV6_ADDR_COPY (&pinfo->nd_opt_pi_prefix, &rprefix->prefix.prefix); #ifdef DEBUG { u_char buf[INET6_ADDRSTRLEN]; zlog_debug ("DEBUG %s", inet_ntop (AF_INET6, &pinfo->nd_opt_pi_prefix, buf, INET6_ADDRSTRLEN)); } #endif /* DEBUG */ len += sizeof (struct nd_opt_prefix_info); } /* Hardware address. */ if (ifp->hw_addr_len != 0) { buf[len++] = ND_OPT_SOURCE_LINKADDR; /* Option length should be rounded up to next octet if the link address does not end on an octet boundary. */ buf[len++] = (ifp->hw_addr_len + 9) >> 3; memcpy (buf + len, ifp->hw_addr, ifp->hw_addr_len); len += ifp->hw_addr_len; /* Pad option to end on an octet boundary. */ memset (buf + len, 0, -(ifp->hw_addr_len + 2) & 0x7); len += -(ifp->hw_addr_len + 2) & 0x7; } /* MTU */ if (zif->rtadv.AdvLinkMTU) { struct nd_opt_mtu * opt = (struct nd_opt_mtu *) (buf + len); opt->nd_opt_mtu_type = ND_OPT_MTU; opt->nd_opt_mtu_len = 1; opt->nd_opt_mtu_reserved = 0; opt->nd_opt_mtu_mtu = htonl (zif->rtadv.AdvLinkMTU); len += sizeof (struct nd_opt_mtu); } msg.msg_name = (void *) &addr; msg.msg_namelen = sizeof (struct sockaddr_in6); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = (void *) adata; msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo)); msg.msg_flags = 0; iov.iov_base = buf; iov.iov_len = len; cmsgptr = ZCMSG_FIRSTHDR(&msg); cmsgptr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); cmsgptr->cmsg_level = IPPROTO_IPV6; cmsgptr->cmsg_type = IPV6_PKTINFO; pkt = (struct in6_pktinfo *) CMSG_DATA (cmsgptr); memset (&pkt->ipi6_addr, 0, sizeof (struct in6_addr)); pkt->ipi6_ifindex = ifp->ifindex; ret = sendmsg (sock, &msg, 0); if (ret < 0) { zlog_err ("rtadv_send_packet: sendmsg %d (%s)\n", errno, safe_strerror(errno)); } } static int rtadv_timer (struct thread *thread) { struct zebra_vrf *zvrf = THREAD_ARG (thread); struct listnode *node, *nnode; struct interface *ifp; struct zebra_if *zif; int period; zvrf->rtadv.ra_timer = NULL; if (zvrf->rtadv.adv_msec_if_count == 0) { period = 1000; /* 1 s */ rtadv_event (zvrf, RTADV_TIMER, 1 /* 1 s */); } else { period = 10; /* 10 ms */ rtadv_event (zvrf, RTADV_TIMER_MSEC, 10 /* 10 ms */); } for (ALL_LIST_ELEMENTS (vrf_iflist (zvrf->vrf_id), node, nnode, ifp)) { if (if_is_loopback (ifp) || ! if_is_operative (ifp)) continue; zif = ifp->info; if (zif->rtadv.AdvSendAdvertisements) { zif->rtadv.AdvIntervalTimer -= period; if (zif->rtadv.AdvIntervalTimer <= 0) { /* FIXME: using MaxRtrAdvInterval each time isn't what section 6.2.4 of RFC4861 tells to do. */ zif->rtadv.AdvIntervalTimer = zif->rtadv.MaxRtrAdvInterval; rtadv_send_packet (zvrf->rtadv.sock, ifp); } } } return 0; } static void rtadv_process_solicit (struct interface *ifp) { struct zebra_vrf *zvrf = vrf_info_lookup (ifp->vrf_id); zlog_info ("Router solicitation received on %s vrf %u", ifp->name, zvrf->vrf_id); rtadv_send_packet (zvrf->rtadv.sock, ifp); } static void rtadv_process_advert (void) { zlog_info ("Router advertisement received"); } static void rtadv_process_packet (u_char *buf, unsigned int len, ifindex_t ifindex, int hoplimit, vrf_id_t vrf_id) { struct icmp6_hdr *icmph; struct interface *ifp; struct zebra_if *zif; /* Interface search. */ ifp = if_lookup_by_index_vrf (ifindex, vrf_id); if (ifp == NULL) { zlog_warn ("Unknown interface index: %d, vrf %u", ifindex, vrf_id); return; } if (if_is_loopback (ifp)) return; /* Check interface configuration. */ zif = ifp->info; if (! zif->rtadv.AdvSendAdvertisements) return; /* ICMP message length check. */ if (len < sizeof (struct icmp6_hdr)) { zlog_warn ("Invalid ICMPV6 packet length: %d", len); return; } icmph = (struct icmp6_hdr *) buf; /* ICMP message type check. */ if (icmph->icmp6_type != ND_ROUTER_SOLICIT && icmph->icmp6_type != ND_ROUTER_ADVERT) { zlog_warn ("Unwanted ICMPV6 message type: %d", icmph->icmp6_type); return; } /* Hoplimit check. */ if (hoplimit >= 0 && hoplimit != 255) { zlog_warn ("Invalid hoplimit %d for router advertisement ICMP packet", hoplimit); return; } /* Check ICMP message type. */ if (icmph->icmp6_type == ND_ROUTER_SOLICIT) rtadv_process_solicit (ifp); else if (icmph->icmp6_type == ND_ROUTER_ADVERT) rtadv_process_advert (); return; } static int rtadv_read (struct thread *thread) { int sock; int len; u_char buf[RTADV_MSG_SIZE]; struct sockaddr_in6 from; ifindex_t ifindex = 0; int hoplimit = -1; struct zebra_vrf *zvrf = THREAD_ARG (thread); sock = THREAD_FD (thread); zvrf->rtadv.ra_read = NULL; /* Register myself. */ rtadv_event (zvrf, RTADV_READ, sock); len = rtadv_recv_packet (sock, buf, sizeof (buf), &from, &ifindex, &hoplimit); if (len < 0) { zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno)); return len; } rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id); return 0; } static int rtadv_make_socket (vrf_id_t vrf_id) { int sock; int ret; struct icmp6_filter filter; if ( zserv_privs.change (ZPRIVS_RAISE) ) zlog_err ("rtadv_make_socket: could not raise privs, %s", safe_strerror (errno) ); sock = vrf_socket (AF_INET6, SOCK_RAW, IPPROTO_ICMPV6, vrf_id); if ( zserv_privs.change (ZPRIVS_LOWER) ) zlog_err ("rtadv_make_socket: could not lower privs, %s", safe_strerror (errno) ); /* When we can't make ICMPV6 socket simply back. Router advertisement feature will not be supported. */ if (sock < 0) { close (sock); return -1; } ret = setsockopt_ipv6_pktinfo (sock, 1); if (ret < 0) { close (sock); return ret; } ret = setsockopt_ipv6_multicast_loop (sock, 0); if (ret < 0) { close (sock); return ret; } ret = setsockopt_ipv6_unicast_hops (sock, 255); if (ret < 0) { close (sock); return ret; } ret = setsockopt_ipv6_multicast_hops (sock, 255); if (ret < 0) { close (sock); return ret; } ret = setsockopt_ipv6_hoplimit (sock, 1); if (ret < 0) { close (sock); return ret; } ICMP6_FILTER_SETBLOCKALL(&filter); ICMP6_FILTER_SETPASS (ND_ROUTER_SOLICIT, &filter); ICMP6_FILTER_SETPASS (ND_ROUTER_ADVERT, &filter); ret = setsockopt (sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filter, sizeof (struct icmp6_filter)); if (ret < 0) { zlog_info ("ICMP6_FILTER set fail: %s", safe_strerror (errno)); return ret; } return sock; } static struct rtadv_prefix * rtadv_prefix_new (void) { return XCALLOC (MTYPE_RTADV_PREFIX, sizeof (struct rtadv_prefix)); } static void rtadv_prefix_free (struct rtadv_prefix *rtadv_prefix) { XFREE (MTYPE_RTADV_PREFIX, rtadv_prefix); } static struct rtadv_prefix * rtadv_prefix_lookup (struct list *rplist, struct prefix_ipv6 *p) { struct listnode *node; struct rtadv_prefix *rprefix; for (ALL_LIST_ELEMENTS_RO (rplist, node, rprefix)) if (prefix_same ((struct prefix *) &rprefix->prefix, (struct prefix *) p)) return rprefix; return NULL; } static struct rtadv_prefix * rtadv_prefix_get (struct list *rplist, struct prefix_ipv6 *p) { struct rtadv_prefix *rprefix; rprefix = rtadv_prefix_lookup (rplist, p); if (rprefix) return rprefix; rprefix = rtadv_prefix_new (); memcpy (&rprefix->prefix, p, sizeof (struct prefix_ipv6)); listnode_add (rplist, rprefix); return rprefix; } static void rtadv_prefix_set (struct zebra_if *zif, struct rtadv_prefix *rp) { struct rtadv_prefix *rprefix; rprefix = rtadv_prefix_get (zif->rtadv.AdvPrefixList, &rp->prefix); /* Set parameters. */ rprefix->AdvValidLifetime = rp->AdvValidLifetime; rprefix->AdvPreferredLifetime = rp->AdvPreferredLifetime; rprefix->AdvOnLinkFlag = rp->AdvOnLinkFlag; rprefix->AdvAutonomousFlag = rp->AdvAutonomousFlag; rprefix->AdvRouterAddressFlag = rp->AdvRouterAddressFlag; } static int rtadv_prefix_reset (struct zebra_if *zif, struct rtadv_prefix *rp) { struct rtadv_prefix *rprefix; rprefix = rtadv_prefix_lookup (zif->rtadv.AdvPrefixList, &rp->prefix); if (rprefix != NULL) { listnode_delete (zif->rtadv.AdvPrefixList, (void *) rprefix); rtadv_prefix_free (rprefix); return 1; } else return 0; } DEFUN (ipv6_nd_suppress_ra, ipv6_nd_suppress_ra_cmd, "ipv6 nd suppress-ra", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Suppress Router Advertisement\n") { struct interface *ifp; struct zebra_if *zif; struct zebra_vrf *zvrf; ifp = vty->index; zif = ifp->info; zvrf = vrf_info_lookup (ifp->vrf_id); if (if_is_loopback (ifp)) { vty_out (vty, "Invalid interface%s", VTY_NEWLINE); return CMD_WARNING; } if (zif->rtadv.AdvSendAdvertisements) { zif->rtadv.AdvSendAdvertisements = 0; zif->rtadv.AdvIntervalTimer = 0; zvrf->rtadv.adv_if_count--; if_leave_all_router (zvrf->rtadv.sock, ifp); if (zvrf->rtadv.adv_if_count == 0) rtadv_event (zvrf, RTADV_STOP, 0); } return CMD_SUCCESS; } DEFUN (no_ipv6_nd_suppress_ra, no_ipv6_nd_suppress_ra_cmd, "no ipv6 nd suppress-ra", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Suppress Router Advertisement\n") { struct interface *ifp; struct zebra_if *zif; struct zebra_vrf *zvrf; ifp = vty->index; zif = ifp->info; zvrf = vrf_info_lookup (ifp->vrf_id); if (if_is_loopback (ifp)) { vty_out (vty, "Invalid interface%s", VTY_NEWLINE); return CMD_WARNING; } if (! zif->rtadv.AdvSendAdvertisements) { zif->rtadv.AdvSendAdvertisements = 1; zif->rtadv.AdvIntervalTimer = 0; zvrf->rtadv.adv_if_count++; if_join_all_router (zvrf->rtadv.sock, ifp); if (zvrf->rtadv.adv_if_count == 1) rtadv_event (zvrf, RTADV_START, zvrf->rtadv.sock); } return CMD_SUCCESS; } DEFUN (ipv6_nd_ra_interval_msec, ipv6_nd_ra_interval_msec_cmd, "ipv6 nd ra-interval msec <70-1800000>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router Advertisement interval\n" "Router Advertisement interval in milliseconds\n") { unsigned interval; struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; struct zebra_vrf *zvrf = vrf_info_lookup (ifp->vrf_id); VTY_GET_INTEGER_RANGE ("router advertisement interval", interval, argv[0], 70, 1800000); if ((zif->rtadv.AdvDefaultLifetime != -1 && interval > (unsigned)zif->rtadv.AdvDefaultLifetime * 1000)) { vty_out (vty, "This ra-interval would conflict with configured ra-lifetime!%s", VTY_NEWLINE); return CMD_WARNING; } if (zif->rtadv.MaxRtrAdvInterval % 1000) zvrf->rtadv.adv_msec_if_count--; if (interval % 1000) zvrf->rtadv.adv_msec_if_count++; zif->rtadv.MaxRtrAdvInterval = interval; zif->rtadv.MinRtrAdvInterval = 0.33 * interval; zif->rtadv.AdvIntervalTimer = 0; return CMD_SUCCESS; } DEFUN (ipv6_nd_ra_interval, ipv6_nd_ra_interval_cmd, "ipv6 nd ra-interval <1-1800>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router Advertisement interval\n" "Router Advertisement interval in seconds\n") { unsigned interval; struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; struct zebra_vrf *zvrf = vrf_info_lookup (ifp->vrf_id); VTY_GET_INTEGER_RANGE ("router advertisement interval", interval, argv[0], 1, 1800); if ((zif->rtadv.AdvDefaultLifetime != -1 && interval > (unsigned)zif->rtadv.AdvDefaultLifetime)) { vty_out (vty, "This ra-interval would conflict with configured ra-lifetime!%s", VTY_NEWLINE); return CMD_WARNING; } if (zif->rtadv.MaxRtrAdvInterval % 1000) zvrf->rtadv.adv_msec_if_count--; /* convert to milliseconds */ interval = interval * 1000; zif->rtadv.MaxRtrAdvInterval = interval; zif->rtadv.MinRtrAdvInterval = 0.33 * interval; zif->rtadv.AdvIntervalTimer = 0; return CMD_SUCCESS; } DEFUN (no_ipv6_nd_ra_interval, no_ipv6_nd_ra_interval_cmd, "no ipv6 nd ra-interval", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router Advertisement interval\n") { struct interface *ifp; struct zebra_if *zif; struct zebra_vrf *zvrf; ifp = (struct interface *) vty->index; zif = ifp->info; zvrf = vrf_info_lookup (ifp->vrf_id); if (zif->rtadv.MaxRtrAdvInterval % 1000) zvrf->rtadv.adv_msec_if_count--; zif->rtadv.MaxRtrAdvInterval = RTADV_MAX_RTR_ADV_INTERVAL; zif->rtadv.MinRtrAdvInterval = RTADV_MIN_RTR_ADV_INTERVAL; zif->rtadv.AdvIntervalTimer = zif->rtadv.MaxRtrAdvInterval; return CMD_SUCCESS; } ALIAS (no_ipv6_nd_ra_interval, no_ipv6_nd_ra_interval_val_cmd, "no ipv6 nd ra-interval <1-1800>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router Advertisement interval\n") ALIAS (no_ipv6_nd_ra_interval, no_ipv6_nd_ra_interval_msec_val_cmd, "no ipv6 nd ra-interval msec <1-1800000>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router Advertisement interval\n" "Router Advertisement interval in milliseconds\n") DEFUN (ipv6_nd_ra_lifetime, ipv6_nd_ra_lifetime_cmd, "ipv6 nd ra-lifetime <0-9000>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router lifetime\n" "Router lifetime in seconds (0 stands for a non-default gw)\n") { int lifetime; struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; VTY_GET_INTEGER_RANGE ("router lifetime", lifetime, argv[0], 0, 9000); /* The value to be placed in the Router Lifetime field * of Router Advertisements sent from the interface, * in seconds. MUST be either zero or between * MaxRtrAdvInterval and 9000 seconds. -- RFC4861, 6.2.1 */ if ((lifetime != 0 && lifetime * 1000 < zif->rtadv.MaxRtrAdvInterval)) { vty_out (vty, "This ra-lifetime would conflict with configured ra-interval%s", VTY_NEWLINE); return CMD_WARNING; } zif->rtadv.AdvDefaultLifetime = lifetime; return CMD_SUCCESS; } DEFUN (no_ipv6_nd_ra_lifetime, no_ipv6_nd_ra_lifetime_cmd, "no ipv6 nd ra-lifetime", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router lifetime\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvDefaultLifetime = -1; return CMD_SUCCESS; } ALIAS (no_ipv6_nd_ra_lifetime, no_ipv6_nd_ra_lifetime_val_cmd, "no ipv6 nd ra-lifetime <0-9000>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Router lifetime\n" "Router lifetime in seconds (0 stands for a non-default gw)\n") DEFUN (ipv6_nd_reachable_time, ipv6_nd_reachable_time_cmd, "ipv6 nd reachable-time <1-3600000>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Reachable time\n" "Reachable time in milliseconds\n") { struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; VTY_GET_INTEGER_RANGE ("reachable time", zif->rtadv.AdvReachableTime, argv[0], 1, RTADV_MAX_REACHABLE_TIME); return CMD_SUCCESS; } DEFUN (no_ipv6_nd_reachable_time, no_ipv6_nd_reachable_time_cmd, "no ipv6 nd reachable-time", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Reachable time\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvReachableTime = 0; return CMD_SUCCESS; } ALIAS (no_ipv6_nd_reachable_time, no_ipv6_nd_reachable_time_val_cmd, "no ipv6 nd reachable-time <1-3600000>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Reachable time\n" "Reachable time in milliseconds\n") DEFUN (ipv6_nd_homeagent_preference, ipv6_nd_homeagent_preference_cmd, "ipv6 nd home-agent-preference <0-65535>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent preference\n" "preference value (default is 0, least preferred)\n") { struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; VTY_GET_INTEGER_RANGE ("home agent preference", zif->rtadv.HomeAgentPreference, argv[0], 0, 65535); return CMD_SUCCESS; } DEFUN (no_ipv6_nd_homeagent_preference, no_ipv6_nd_homeagent_preference_cmd, "no ipv6 nd home-agent-preference", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent preference\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.HomeAgentPreference = 0; return CMD_SUCCESS; } ALIAS (no_ipv6_nd_homeagent_preference, no_ipv6_nd_homeagent_preference_val_cmd, "no ipv6 nd home-agent-preference <0-65535>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent preference\n" "preference value (default is 0, least preferred)\n") DEFUN (ipv6_nd_homeagent_lifetime, ipv6_nd_homeagent_lifetime_cmd, "ipv6 nd home-agent-lifetime <0-65520>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent lifetime\n" "Home Agent lifetime in seconds (0 to track ra-lifetime)\n") { struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; VTY_GET_INTEGER_RANGE ("home agent lifetime", zif->rtadv.HomeAgentLifetime, argv[0], 0, RTADV_MAX_HALIFETIME); return CMD_SUCCESS; } DEFUN (no_ipv6_nd_homeagent_lifetime, no_ipv6_nd_homeagent_lifetime_cmd, "no ipv6 nd home-agent-lifetime", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent lifetime\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.HomeAgentLifetime = -1; return CMD_SUCCESS; } ALIAS (no_ipv6_nd_homeagent_lifetime, no_ipv6_nd_homeagent_lifetime_val_cmd, "no ipv6 nd home-agent-lifetime <0-65520>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent lifetime\n" "Home Agent lifetime in seconds (0 to track ra-lifetime)\n") DEFUN (ipv6_nd_managed_config_flag, ipv6_nd_managed_config_flag_cmd, "ipv6 nd managed-config-flag", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Managed address configuration flag\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvManagedFlag = 1; return CMD_SUCCESS; } DEFUN (no_ipv6_nd_managed_config_flag, no_ipv6_nd_managed_config_flag_cmd, "no ipv6 nd managed-config-flag", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Managed address configuration flag\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvManagedFlag = 0; return CMD_SUCCESS; } DEFUN (ipv6_nd_homeagent_config_flag, ipv6_nd_homeagent_config_flag_cmd, "ipv6 nd home-agent-config-flag", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent configuration flag\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvHomeAgentFlag = 1; return CMD_SUCCESS; } DEFUN (no_ipv6_nd_homeagent_config_flag, no_ipv6_nd_homeagent_config_flag_cmd, "no ipv6 nd home-agent-config-flag", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Home Agent configuration flag\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvHomeAgentFlag = 0; return CMD_SUCCESS; } DEFUN (ipv6_nd_adv_interval_config_option, ipv6_nd_adv_interval_config_option_cmd, "ipv6 nd adv-interval-option", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Advertisement Interval Option\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvIntervalOption = 1; return CMD_SUCCESS; } DEFUN (no_ipv6_nd_adv_interval_config_option, no_ipv6_nd_adv_interval_config_option_cmd, "no ipv6 nd adv-interval-option", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Advertisement Interval Option\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvIntervalOption = 0; return CMD_SUCCESS; } DEFUN (ipv6_nd_other_config_flag, ipv6_nd_other_config_flag_cmd, "ipv6 nd other-config-flag", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Other statefull configuration flag\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvOtherConfigFlag = 1; return CMD_SUCCESS; } DEFUN (no_ipv6_nd_other_config_flag, no_ipv6_nd_other_config_flag_cmd, "no ipv6 nd other-config-flag", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Other statefull configuration flag\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.AdvOtherConfigFlag = 0; return CMD_SUCCESS; } DEFUN (ipv6_nd_prefix, ipv6_nd_prefix_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (off-link|) (no-autoconfig|) (router-address|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Do not use prefix for onlink determination\n" "Do not use prefix for autoconfiguration\n" "Set Router Address flag\n") { int i; int ret; int cursor = 1; struct interface *ifp; struct zebra_if *zebra_if; struct rtadv_prefix rp; ifp = (struct interface *) vty->index; zebra_if = ifp->info; ret = str2prefix_ipv6 (argv[0], &rp.prefix); if (!ret) { vty_out (vty, "Malformed IPv6 prefix%s", VTY_NEWLINE); return CMD_WARNING; } apply_mask_ipv6 (&rp.prefix); /* RFC4861 4.6.2 */ rp.AdvOnLinkFlag = 1; rp.AdvAutonomousFlag = 1; rp.AdvRouterAddressFlag = 0; rp.AdvValidLifetime = RTADV_VALID_LIFETIME; rp.AdvPreferredLifetime = RTADV_PREFERRED_LIFETIME; if (argc > 1) { if ((isdigit((unsigned char)argv[1][0])) || strncmp (argv[1], "i", 1) == 0) { if ( strncmp (argv[1], "i", 1) == 0) rp.AdvValidLifetime = UINT32_MAX; else rp.AdvValidLifetime = (u_int32_t) strtoll (argv[1], (char **)NULL, 10); if ( strncmp (argv[2], "i", 1) == 0) rp.AdvPreferredLifetime = UINT32_MAX; else rp.AdvPreferredLifetime = (u_int32_t) strtoll (argv[2], (char **)NULL, 10); if (rp.AdvPreferredLifetime > rp.AdvValidLifetime) { vty_out (vty, "Invalid preferred lifetime%s", VTY_NEWLINE); return CMD_WARNING; } cursor = cursor + 2; } if (argc > cursor) { for (i = cursor; i < argc; i++) { if (strncmp (argv[i], "of", 2) == 0) rp.AdvOnLinkFlag = 0; if (strncmp (argv[i], "no", 2) == 0) rp.AdvAutonomousFlag = 0; if (strncmp (argv[i], "ro", 2) == 0) rp.AdvRouterAddressFlag = 1; } } } rtadv_prefix_set (zebra_if, &rp); return CMD_SUCCESS; } ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_nortaddr_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (off-link|) (no-autoconfig|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Do not use prefix for onlink determination\n" "Do not use prefix for autoconfiguration\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_rev_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (no-autoconfig|) (off-link|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Do not use prefix for autoconfiguration\n" "Do not use prefix for onlink determination\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_rev_rtaddr_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (no-autoconfig|) (off-link|) (router-address|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Do not use prefix for autoconfiguration\n" "Do not use prefix for onlink determination\n" "Set Router Address flag\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_noauto_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (no-autoconfig|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Do not use prefix for autoconfiguration") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_offlink_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (off-link|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Do not use prefix for onlink determination\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_rtaddr_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite) (router-address|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n" "Set Router Address flag\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_val_cmd, "ipv6 nd prefix X:X::X:X/M (<0-4294967295>|infinite) " "(<0-4294967295>|infinite)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Valid lifetime in seconds\n" "Infinite valid lifetime\n" "Preferred lifetime in seconds\n" "Infinite preferred lifetime\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_noval_cmd, "ipv6 nd prefix X:X::X:X/M (no-autoconfig|) (off-link|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Do not use prefix for autoconfiguration\n" "Do not use prefix for onlink determination\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_noval_rev_cmd, "ipv6 nd prefix X:X::X:X/M (off-link|) (no-autoconfig|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Do not use prefix for onlink determination\n" "Do not use prefix for autoconfiguration\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_noval_noauto_cmd, "ipv6 nd prefix X:X::X:X/M (no-autoconfig|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Do not use prefix for autoconfiguration\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_noval_offlink_cmd, "ipv6 nd prefix X:X::X:X/M (off-link|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Do not use prefix for onlink determination\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_noval_rtaddr_cmd, "ipv6 nd prefix X:X::X:X/M (router-address|)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n" "Set Router Address flag\n") ALIAS (ipv6_nd_prefix, ipv6_nd_prefix_prefix_cmd, "ipv6 nd prefix X:X::X:X/M", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n") DEFUN (no_ipv6_nd_prefix, no_ipv6_nd_prefix_cmd, "no ipv6 nd prefix IPV6PREFIX", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Prefix information\n" "IPv6 prefix\n") { int ret; struct interface *ifp; struct zebra_if *zebra_if; struct rtadv_prefix rp; ifp = (struct interface *) vty->index; zebra_if = ifp->info; ret = str2prefix_ipv6 (argv[0], &rp.prefix); if (!ret) { vty_out (vty, "Malformed IPv6 prefix%s", VTY_NEWLINE); return CMD_WARNING; } apply_mask_ipv6 (&rp.prefix); /* RFC4861 4.6.2 */ ret = rtadv_prefix_reset (zebra_if, &rp); if (!ret) { vty_out (vty, "Non-exist IPv6 prefix%s", VTY_NEWLINE); return CMD_WARNING; } return CMD_SUCCESS; } DEFUN (ipv6_nd_router_preference, ipv6_nd_router_preference_cmd, "ipv6 nd router-preference (high|medium|low)", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Default router preference\n" "High default router preference\n" "Low default router preference\n" "Medium default router preference (default)\n") { struct interface *ifp; struct zebra_if *zif; int i = 0; ifp = (struct interface *) vty->index; zif = ifp->info; while (0 != rtadv_pref_strs[i]) { if (strncmp (argv[0], rtadv_pref_strs[i], 1) == 0) { zif->rtadv.DefaultPreference = i; return CMD_SUCCESS; } i++; } return CMD_ERR_NO_MATCH; } DEFUN (no_ipv6_nd_router_preference, no_ipv6_nd_router_preference_cmd, "no ipv6 nd router-preference", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Default router preference\n") { struct interface *ifp; struct zebra_if *zif; ifp = (struct interface *) vty->index; zif = ifp->info; zif->rtadv.DefaultPreference = RTADV_PREF_MEDIUM; /* Default per RFC4191. */ return CMD_SUCCESS; } ALIAS (no_ipv6_nd_router_preference, no_ipv6_nd_router_preference_val_cmd, "no ipv6 nd router-preference (high|medium|low)", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Default router preference\n" "High default router preference\n" "Low default router preference\n" "Medium default router preference (default)\n") DEFUN (ipv6_nd_mtu, ipv6_nd_mtu_cmd, "ipv6 nd mtu <1-65535>", "Interface IPv6 config commands\n" "Neighbor discovery\n" "Advertised MTU\n" "MTU in bytes\n") { struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; VTY_GET_INTEGER_RANGE ("MTU", zif->rtadv.AdvLinkMTU, argv[0], 1, 65535); return CMD_SUCCESS; } DEFUN (no_ipv6_nd_mtu, no_ipv6_nd_mtu_cmd, "no ipv6 nd mtu", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Advertised MTU\n") { struct interface *ifp = (struct interface *) vty->index; struct zebra_if *zif = ifp->info; zif->rtadv.AdvLinkMTU = 0; return CMD_SUCCESS; } ALIAS (no_ipv6_nd_mtu, no_ipv6_nd_mtu_val_cmd, "no ipv6 nd mtu <1-65535>", NO_STR "Interface IPv6 config commands\n" "Neighbor discovery\n" "Advertised MTU\n" "MTU in bytes\n") /* Write configuration about router advertisement. */ void rtadv_config_write (struct vty *vty, struct interface *ifp) { struct zebra_if *zif; struct listnode *node; struct rtadv_prefix *rprefix; char buf[PREFIX_STRLEN]; int interval; zif = ifp->info; if (! if_is_loopback (ifp)) { if (zif->rtadv.AdvSendAdvertisements) vty_out (vty, " no ipv6 nd suppress-ra%s", VTY_NEWLINE); } interval = zif->rtadv.MaxRtrAdvInterval; if (interval % 1000) vty_out (vty, " ipv6 nd ra-interval msec %d%s", interval, VTY_NEWLINE); else if (interval != RTADV_MAX_RTR_ADV_INTERVAL) vty_out (vty, " ipv6 nd ra-interval %d%s", interval / 1000, VTY_NEWLINE); if (zif->rtadv.AdvIntervalOption) vty_out (vty, " ipv6 nd adv-interval-option%s", VTY_NEWLINE); if (zif->rtadv.AdvDefaultLifetime != -1) vty_out (vty, " ipv6 nd ra-lifetime %d%s", zif->rtadv.AdvDefaultLifetime, VTY_NEWLINE); if (zif->rtadv.HomeAgentPreference) vty_out (vty, " ipv6 nd home-agent-preference %u%s", zif->rtadv.HomeAgentPreference, VTY_NEWLINE); if (zif->rtadv.HomeAgentLifetime != -1) vty_out (vty, " ipv6 nd home-agent-lifetime %u%s", zif->rtadv.HomeAgentLifetime, VTY_NEWLINE); if (zif->rtadv.AdvHomeAgentFlag) vty_out (vty, " ipv6 nd home-agent-config-flag%s", VTY_NEWLINE); if (zif->rtadv.AdvReachableTime) vty_out (vty, " ipv6 nd reachable-time %d%s", zif->rtadv.AdvReachableTime, VTY_NEWLINE); if (zif->rtadv.AdvManagedFlag) vty_out (vty, " ipv6 nd managed-config-flag%s", VTY_NEWLINE); if (zif->rtadv.AdvOtherConfigFlag) vty_out (vty, " ipv6 nd other-config-flag%s", VTY_NEWLINE); if (zif->rtadv.DefaultPreference != RTADV_PREF_MEDIUM) vty_out (vty, " ipv6 nd router-preference %s%s", rtadv_pref_strs[zif->rtadv.DefaultPreference], VTY_NEWLINE); if (zif->rtadv.AdvLinkMTU) vty_out (vty, " ipv6 nd mtu %d%s", zif->rtadv.AdvLinkMTU, VTY_NEWLINE); for (ALL_LIST_ELEMENTS_RO (zif->rtadv.AdvPrefixList, node, rprefix)) { vty_out (vty, " ipv6 nd prefix %s", prefix2str (&rprefix->prefix, buf, sizeof(buf))); if ((rprefix->AdvValidLifetime != RTADV_VALID_LIFETIME) || (rprefix->AdvPreferredLifetime != RTADV_PREFERRED_LIFETIME)) { if (rprefix->AdvValidLifetime == UINT32_MAX) vty_out (vty, " infinite"); else vty_out (vty, " %u", rprefix->AdvValidLifetime); if (rprefix->AdvPreferredLifetime == UINT32_MAX) vty_out (vty, " infinite"); else vty_out (vty, " %u", rprefix->AdvPreferredLifetime); } if (!rprefix->AdvOnLinkFlag) vty_out (vty, " off-link"); if (!rprefix->AdvAutonomousFlag) vty_out (vty, " no-autoconfig"); if (rprefix->AdvRouterAddressFlag) vty_out (vty, " router-address"); vty_out (vty, "%s", VTY_NEWLINE); } } static void rtadv_event (struct zebra_vrf *zvrf, enum rtadv_event event, int val) { struct rtadv *rtadv = &zvrf->rtadv; switch (event) { case RTADV_START: if (! rtadv->ra_read) rtadv->ra_read = thread_add_read (zebrad.master, rtadv_read, zvrf, val); if (! rtadv->ra_timer) rtadv->ra_timer = thread_add_event (zebrad.master, rtadv_timer, zvrf, 0); break; case RTADV_STOP: if (rtadv->ra_timer) { thread_cancel (rtadv->ra_timer); rtadv->ra_timer = NULL; } if (rtadv->ra_read) { thread_cancel (rtadv->ra_read); rtadv->ra_read = NULL; } break; case RTADV_TIMER: if (! rtadv->ra_timer) rtadv->ra_timer = thread_add_timer (zebrad.master, rtadv_timer, zvrf, val); break; case RTADV_TIMER_MSEC: if (! rtadv->ra_timer) rtadv->ra_timer = thread_add_timer_msec (zebrad.master, rtadv_timer, zvrf, val); break; case RTADV_READ: if (! rtadv->ra_read) rtadv->ra_read = thread_add_read (zebrad.master, rtadv_read, zvrf, val); break; default: break; } return; } void rtadv_init (struct zebra_vrf *zvrf) { zvrf->rtadv.sock = rtadv_make_socket (zvrf->vrf_id); } void rtadv_terminate (struct zebra_vrf *zvrf) { rtadv_event (zvrf, RTADV_STOP, 0); if (zvrf->rtadv.sock >= 0) { close (zvrf->rtadv.sock); zvrf->rtadv.sock = -1; } zvrf->rtadv.adv_if_count = 0; zvrf->rtadv.adv_msec_if_count = 0; } void rtadv_cmd_init (void) { install_element (INTERFACE_NODE, &ipv6_nd_suppress_ra_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_suppress_ra_cmd); install_element (INTERFACE_NODE, &ipv6_nd_ra_interval_cmd); install_element (INTERFACE_NODE, &ipv6_nd_ra_interval_msec_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_ra_interval_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_ra_interval_val_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_ra_interval_msec_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_ra_lifetime_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_ra_lifetime_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_ra_lifetime_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_reachable_time_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_reachable_time_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_reachable_time_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_managed_config_flag_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_managed_config_flag_cmd); install_element (INTERFACE_NODE, &ipv6_nd_other_config_flag_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_other_config_flag_cmd); install_element (INTERFACE_NODE, &ipv6_nd_homeagent_config_flag_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_config_flag_cmd); install_element (INTERFACE_NODE, &ipv6_nd_homeagent_preference_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_preference_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_preference_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_homeagent_lifetime_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_lifetime_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_homeagent_lifetime_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_adv_interval_config_option_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_adv_interval_config_option_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_rev_rtaddr_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_nortaddr_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_rev_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_noauto_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_offlink_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_rtaddr_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_rev_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_noauto_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_offlink_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_noval_rtaddr_cmd); install_element (INTERFACE_NODE, &ipv6_nd_prefix_prefix_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_prefix_cmd); install_element (INTERFACE_NODE, &ipv6_nd_router_preference_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_router_preference_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_router_preference_val_cmd); install_element (INTERFACE_NODE, &ipv6_nd_mtu_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_mtu_cmd); install_element (INTERFACE_NODE, &no_ipv6_nd_mtu_val_cmd); } static int if_join_all_router (int sock, struct interface *ifp) { int ret; struct ipv6_mreq mreq; memset (&mreq, 0, sizeof (struct ipv6_mreq)); inet_pton (AF_INET6, ALLROUTER, &mreq.ipv6mr_multiaddr); mreq.ipv6mr_interface = ifp->ifindex; ret = setsockopt (sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char *) &mreq, sizeof mreq); if (ret < 0) zlog_warn ("can't setsockopt IPV6_JOIN_GROUP: %s", safe_strerror (errno)); zlog_info ("rtadv: %s join to all-routers multicast group", ifp->name); return 0; } static int if_leave_all_router (int sock, struct interface *ifp) { int ret; struct ipv6_mreq mreq; memset (&mreq, 0, sizeof (struct ipv6_mreq)); inet_pton (AF_INET6, ALLROUTER, &mreq.ipv6mr_multiaddr); mreq.ipv6mr_interface = ifp->ifindex; ret = setsockopt (sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP, (char *) &mreq, sizeof mreq); if (ret < 0) zlog_warn ("can't setsockopt IPV6_LEAVE_GROUP: %s", safe_strerror (errno)); zlog_info ("rtadv: %s leave from all-routers multicast group", ifp->name); return 0; } #else void rtadv_init (struct zebra_vrf *zvrf) { /* Empty.*/; } void rtadv_terminate (struct zebra_vrf *zvrf) { /* Empty.*/; } void rtadv_cmd_init (void) { /* Empty.*/; } #endif /* HAVE_RTADV && HAVE_IPV6 */
./CrossVul/dataset_final_sorted/CWE-119/c/good_4897_0
crossvul-cpp_data_good_3616_0
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.49 2012/02/20 20:04:37 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifndef EFTYPE #define EFTYPE EINVAL #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == (uint32_t)0x01020304) #define CDF_TOLE8(x) ((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x))) #define CDF_TOLE4(x) ((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x))) #define CDF_TOLE2(x) ((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]); } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child); d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child); d->d_storage = CDF_TOLE4((uint32_t)d->d_storage); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8((uint64_t)d->d_created); d->d_modified = CDF_TOLE8((uint64_t)d->d_modified); d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; (void)&line; if (e >= b && (size_t)(e - b) < CDF_SEC_SIZE(h) * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p end %p %" SIZE_T_FORMAT "u" " >= %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = (size_t)off + len; if ((off_t)(off + len) != (off_t)siz) { errno = EINVAL; return -1; } if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return (ssize_t)len; } if (info->i_fd == -1) return -1; if (lseek(info->i_fd, off, SEEK_SET) == (off_t)-1) return -1; if (read(info->i_fd, buf, len) != (ssize_t)len) return -1; return (ssize_t)len; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic 0x%" INT64_T_FORMAT "x != 0x%" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size 0x%u\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size 0x%u\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos, CDF_SEC_SIZE(h) * sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (4 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, calloc(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != (ssize_t)ss) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, calloc(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); errno = EFTYPE; goto out2; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4((uint32_t)msa[k]); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); errno = EFTYPE; goto out2; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != (ssize_t)ss) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4((uint32_t)msa[nsatpersec]); } out: sat->sat_len = i; free(msa); return 0; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size); DPRINTF(("Chain:")); for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); errno = EFTYPE; return (size_t)-1; } if (sid > maxsector) { DPRINTF(("Sector %d > %d\n", sid, maxsector)); errno = EFTYPE; return (size_t)-1; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } DPRINTF(("\n")); return i; } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = len; if (scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != (ssize_t)ss) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == (size_t)-1) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, calloc(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, malloc(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); errno = EFTYPE; goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h)); if (ssat->sat_len == (size_t)-1) return -1; ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); errno = EFTYPE; goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); errno = EFTYPE; goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sat sector %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } return 0; out: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn) { size_t i; const cdf_directory_t *d; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) goto out; d = &dir->dir_tab[i]; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) goto out; return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; scn->sst_len = 0; scn->sst_dirlen = 0; return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return (unsigned char)*d - CDF_TOLE2(*s); return 0; } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { size_t i; const cdf_directory_t *d; static const char name[] = "\05SummaryInformation"; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == CDF_DIR_TYPE_USER_STREAM && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, sizeof(name)) == 0) break; if (i == 0) { DPRINTF(("Cannot find summary information section\n")); errno = ESRCH; return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t i, maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, (const void *) ((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE2(si->si_count); *count = 0; maxcount = 0; *info = NULL; for (i = 0; i < CDF_TOLE4(si->si_count); i++) { if (i >= CDF_LOOP_LIMIT) { DPRINTF(("Unpack summary info loop limit")); errno = EFTYPE; return -1; } if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) { return -1; } } return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "0x%x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = (int)(ts % 60); ts /= 60; mins = (int)(ts % 60); ts /= 60; hours = (int)(ts % 24); ts /= 24; days = (int)ts; if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if ((size_t)len >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if ((size_t)len >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if ((size_t)len >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("0x%x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3zu] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(void *v, size_t len) { size_t i, j; unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_header_t *h, const cdf_stream_t *sst) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: 0x%x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(h, &scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(1, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(1, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(1, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(1, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(1, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst) == -1) err(1, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&h, &sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) err(1, "Cannot read summary info"); #ifdef CDF_DEBUG cdf_dump_summary_info(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_3616_0
crossvul-cpp_data_good_3426_0
/* * Network Block Device - server * * Copyright 1996-1998 Pavel Machek, distribute under GPL * <pavel@atrey.karlin.mff.cuni.cz> * Copyright 2001-2004 Wouter Verhelst <wouter@debian.org> * Copyright 2002 Anton Altaparmakov <aia21@cam.ac.uk> * * Version 1.0 - hopefully 64-bit-clean * Version 1.1 - merging enhancements from Josh Parsons, <josh@coombs.anu.edu.au> * Version 1.2 - autodetect size of block devices, thanx to Peter T. Breuer" <ptb@it.uc3m.es> * Version 1.5 - can compile on Unix systems that don't have 64 bit integer * type, or don't have 64 bit file offsets by defining FS_32BIT * in compile options for nbd-server *only*. This can be done * with make FSCHOICE=-DFS_32BIT nbd-server. (I don't have the * original autoconf input file, or I would make it a configure * option.) Ken Yap <ken@nlc.net.au>. * Version 1.6 - fix autodetection of block device size and really make 64 bit * clean on 32 bit machines. Anton Altaparmakov <aia21@cam.ac.uk> * Version 2.0 - Version synchronised with client * Version 2.1 - Reap zombie client processes when they exit. Removed * (uncommented) the _IO magic, it's no longer necessary. Wouter * Verhelst <wouter@debian.org> * Version 2.2 - Auto switch to read-only mode (usefull for floppies). * Version 2.3 - Fixed code so that Large File Support works. This * removes the FS_32BIT compile-time directive; define * _FILE_OFFSET_BITS=64 and _LARGEFILE_SOURCE if you used to be * using FS_32BIT. This will allow you to use files >2GB instead of * having to use the -m option. Wouter Verhelst <wouter@debian.org> * Version 2.4 - Added code to keep track of children, so that we can * properly kill them from initscripts. Add a call to daemon(), * so that processes don't think they have to wait for us, which is * interesting for initscripts as well. Wouter Verhelst * <wouter@debian.org> * Version 2.5 - Bugfix release: forgot to reset child_arraysize to * zero after fork()ing, resulting in nbd-server going berserk * when it receives a signal with at least one child open. Wouter * Verhelst <wouter@debian.org> * 10/10/2003 - Added socket option SO_KEEPALIVE (sf.net bug 819235); * rectified type of mainloop::size_host (sf.net bugs 814435 and * 817385); close the PID file after writing to it, so that the * daemon can actually be found. Wouter Verhelst * <wouter@debian.org> * 10/10/2003 - Size of the data "size_host" was wrong and so was not * correctly put in network endianness. Many types were corrected * (size_t and off_t instead of int). <vspaceg@sourceforge.net> * Version 2.6 - Some code cleanup. * Version 2.7 - Better build system. * 11/02/2004 - Doxygenified the source, modularized it a bit. Needs a * lot more work, but this is a start. Wouter Verhelst * <wouter@debian.org> * 16/03/2010 - Add IPv6 support. * Kitt Tientanopajai <kitt@kitty.in.th> * Neutron Soutmun <neo.neutron@gmail.com> * Suriya Soutmun <darksolar@gmail.com> */ /* Includes LFS defines, which defines behaviours of some of the following * headers, so must come before those */ #include "lfs.h" #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/select.h> /* select */ #include <sys/wait.h> /* wait */ #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #include <sys/param.h> #ifdef HAVE_SYS_MOUNT_H #include <sys/mount.h> /* For BLKGETSIZE */ #endif #include <signal.h> /* sigaction */ #include <errno.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <netdb.h> #include <syslog.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <arpa/inet.h> #include <strings.h> #include <dirent.h> #include <unistd.h> #include <getopt.h> #include <pwd.h> #include <grp.h> #include <glib.h> /* used in cliserv.h, so must come first */ #define MY_NAME "nbd_server" #include "cliserv.h" #ifdef WITH_SDP #include <sdp_inet.h> #endif /** Default position of the config file */ #ifndef SYSCONFDIR #define SYSCONFDIR "/etc" #endif #define CFILE SYSCONFDIR "/nbd-server/config" /** Where our config file actually is */ gchar* config_file_pos; /** What user we're running as */ gchar* runuser=NULL; /** What group we're running as */ gchar* rungroup=NULL; /** whether to export using the old negotiation protocol (port-based) */ gboolean do_oldstyle=FALSE; /** Logging macros, now nothing goes to syslog unless you say ISSERVER */ #ifdef ISSERVER #define msg2(a,b) syslog(a,b) #define msg3(a,b,c) syslog(a,b,c) #define msg4(a,b,c,d) syslog(a,b,c,d) #else #define msg2(a,b) g_message(b) #define msg3(a,b,c) g_message(b,c) #define msg4(a,b,c,d) g_message(b,c,d) #endif /* Debugging macros */ //#define DODBG #ifdef DODBG #define DEBUG( a ) printf( a ) #define DEBUG2( a,b ) printf( a,b ) #define DEBUG3( a,b,c ) printf( a,b,c ) #define DEBUG4( a,b,c,d ) printf( a,b,c,d ) #else #define DEBUG( a ) #define DEBUG2( a,b ) #define DEBUG3( a,b,c ) #define DEBUG4( a,b,c,d ) #endif #ifndef PACKAGE_VERSION #define PACKAGE_VERSION "" #endif /** * The highest value a variable of type off_t can reach. This is a signed * integer, so set all bits except for the leftmost one. **/ #define OFFT_MAX ~((off_t)1<<(sizeof(off_t)*8-1)) #define LINELEN 256 /**< Size of static buffer used to read the authorization file (yuck) */ #define BUFSIZE ((1024*1024)+sizeof(struct nbd_reply)) /**< Size of buffer that can hold requests */ #define DIFFPAGESIZE 4096 /**< diff file uses those chunks */ #define F_READONLY 1 /**< flag to tell us a file is readonly */ #define F_MULTIFILE 2 /**< flag to tell us a file is exported using -m */ #define F_COPYONWRITE 4 /**< flag to tell us a file is exported using copyonwrite */ #define F_AUTOREADONLY 8 /**< flag to tell us a file is set to autoreadonly */ #define F_SPARSE 16 /**< flag to tell us copyronwrite should use a sparse file */ #define F_SDP 32 /**< flag to tell us the export should be done using the Socket Direct Protocol for RDMA */ #define F_SYNC 64 /**< Whether to fsync() after a write */ GHashTable *children; char pidfname[256]; /**< name of our PID file */ char pidftemplate[256]; /**< template to be used for the filename of the PID file */ char default_authname[] = SYSCONFDIR "/nbd-server/allow"; /**< default name of allow file */ int modernsock=0; /**< Socket for the modern handler. Not used if a client was only specified on the command line; only port used if oldstyle is set to false (and then the command-line client isn't used, gna gna) */ char* modern_listen; /**< listenaddr value for modernsock */ /** * Types of virtuatlization **/ typedef enum { VIRT_NONE=0, /**< No virtualization */ VIRT_IPLIT, /**< Literal IP address as part of the filename */ VIRT_IPHASH, /**< Replacing all dots in an ip address by a / before doing the same as in IPLIT */ VIRT_CIDR, /**< Every subnet in its own directory */ } VIRT_STYLE; /** * Variables associated with a server. **/ typedef struct { gchar* exportname; /**< (unprocessed) filename of the file we're exporting */ off_t expected_size; /**< size of the exported file as it was told to us through configuration */ gchar* listenaddr; /**< The IP address we're listening on */ unsigned int port; /**< port we're exporting this file at */ char* authname; /**< filename of the authorization file */ int flags; /**< flags associated with this exported file */ int socket; /**< The socket of this server. */ int socket_family; /**< family of the socket */ VIRT_STYLE virtstyle;/**< The style of virtualization, if any */ uint8_t cidrlen; /**< The length of the mask when we use CIDR-style virtualization */ gchar* prerun; /**< command to be ran after connecting a client, but before starting to serve */ gchar* postrun; /**< command that will be ran after the client disconnects */ gchar* servename; /**< name of the export as selected by nbd-client */ int max_connections; /**< maximum number of opened connections */ } SERVER; /** * Variables associated with a client socket. **/ typedef struct { int fhandle; /**< file descriptor */ off_t startoff; /**< starting offset of this file */ } FILE_INFO; typedef struct { off_t exportsize; /**< size of the file we're exporting */ char *clientname; /**< peer */ char *exportname; /**< (processed) filename of the file we're exporting */ GArray *export; /**< array of FILE_INFO of exported files; array size is always 1 unless we're doing the multiple file option */ int net; /**< The actual client socket */ SERVER *server; /**< The server this client is getting data from */ char* difffilename; /**< filename of the copy-on-write file, if any */ int difffile; /**< filedescriptor of copyonwrite file. @todo shouldn't this be an array too? (cfr export) Or make -m and -c mutually exclusive */ u32 difffilelen; /**< number of pages in difffile */ u32 *difmap; /**< see comment on the global difmap for this one */ gboolean modern; /**< client was negotiated using modern negotiation protocol */ } CLIENT; /** * Type of configuration file values **/ typedef enum { PARAM_INT, /**< This parameter is an integer */ PARAM_STRING, /**< This parameter is a string */ PARAM_BOOL, /**< This parameter is a boolean */ } PARAM_TYPE; /** * Configuration file values **/ typedef struct { gchar *paramname; /**< Name of the parameter, as it appears in the config file */ gboolean required; /**< Whether this is a required (as opposed to optional) parameter */ PARAM_TYPE ptype; /**< Type of the parameter. */ gpointer target; /**< Pointer to where the data of this parameter should be written. If ptype is PARAM_BOOL, the data is or'ed rather than overwritten. */ gint flagval; /**< Flag mask for this parameter in case ptype is PARAM_BOOL. */ } PARAM; /** * Check whether a client is allowed to connect. Works with an authorization * file which contains one line per machine, no wildcards. * * @param opts The client who's trying to connect. * @return 0 - authorization refused, 1 - OK **/ int authorized_client(CLIENT *opts) { const char *ERRMSG="Invalid entry '%s' in authfile '%s', so, refusing all connections."; FILE *f ; char line[LINELEN]; char *tmp; struct in_addr addr; struct in_addr client; struct in_addr cltemp; int len; if ((f=fopen(opts->server->authname,"r"))==NULL) { msg4(LOG_INFO,"Can't open authorization file %s (%s).", opts->server->authname,strerror(errno)) ; return 1 ; } inet_aton(opts->clientname, &client); while (fgets(line,LINELEN,f)!=NULL) { if((tmp=index(line, '/'))) { if(strlen(line)<=tmp-line) { msg4(LOG_CRIT, ERRMSG, line, opts->server->authname); return 0; } *(tmp++)=0; if(!inet_aton(line,&addr)) { msg4(LOG_CRIT, ERRMSG, line, opts->server->authname); return 0; } len=strtol(tmp, NULL, 0); addr.s_addr>>=32-len; addr.s_addr<<=32-len; memcpy(&cltemp,&client,sizeof(client)); cltemp.s_addr>>=32-len; cltemp.s_addr<<=32-len; if(addr.s_addr == cltemp.s_addr) { return 1; } } if (strncmp(line,opts->clientname,strlen(opts->clientname))==0) { fclose(f); return 1; } } fclose(f); return 0; } /** * Read data from a file descriptor into a buffer * * @param f a file descriptor * @param buf a buffer * @param len the number of bytes to be read **/ inline void readit(int f, void *buf, size_t len) { ssize_t res; while (len > 0) { DEBUG("*"); if ((res = read(f, buf, len)) <= 0) { if(errno != EAGAIN) { err("Read failed: %m"); } } else { len -= res; buf += res; } } } /** * Write data from a buffer into a filedescriptor * * @param f a file descriptor * @param buf a buffer containing data * @param len the number of bytes to be written **/ inline void writeit(int f, void *buf, size_t len) { ssize_t res; while (len > 0) { DEBUG("+"); if ((res = write(f, buf, len)) <= 0) err("Send failed: %m"); len -= res; buf += res; } } /** * Print out a message about how to use nbd-server. Split out to a separate * function so that we can call it from multiple places */ void usage() { printf("This is nbd-server version " VERSION "\n"); printf("Usage: [ip:|ip6@]port file_to_export [size][kKmM] [-l authorize_file] [-r] [-m] [-c] [-C configuration file] [-p PID file name] [-o section name] [-M max connections]\n" "\t-r|--read-only\t\tread only\n" "\t-m|--multi-file\t\tmultiple file\n" "\t-c|--copy-on-write\tcopy on write\n" "\t-C|--config-file\tspecify an alternate configuration file\n" "\t-l|--authorize-file\tfile with list of hosts that are allowed to\n\t\t\t\tconnect.\n" "\t-p|--pid-file\t\tspecify a filename to write our PID to\n" "\t-o|--output-config\toutput a config file section for what you\n\t\t\t\tspecified on the command line, with the\n\t\t\t\tspecified section name\n" "\t-M|--max-connections\tspecify the maximum number of opened connections\n\n" "\tif port is set to 0, stdin is used (for running from inetd)\n" "\tif file_to_export contains '%%s', it is substituted with the IP\n" "\t\taddress of the machine trying to connect\n" "\tif ip is set, it contains the local IP address on which we're listening.\n\tif not, the server will listen on all local IP addresses\n"); printf("Using configuration file %s\n", CFILE); } /* Dumps a config file section of the given SERVER*, and exits. */ void dump_section(SERVER* serve, gchar* section_header) { printf("[%s]\n", section_header); printf("\texportname = %s\n", serve->exportname); printf("\tlistenaddr = %s\n", serve->listenaddr); printf("\tport = %d\n", serve->port); if(serve->flags & F_READONLY) { printf("\treadonly = true\n"); } if(serve->flags & F_MULTIFILE) { printf("\tmultifile = true\n"); } if(serve->flags & F_COPYONWRITE) { printf("\tcopyonwrite = true\n"); } if(serve->expected_size) { printf("\tfilesize = %lld\n", (long long int)serve->expected_size); } if(serve->authname) { printf("\tauthfile = %s\n", serve->authname); } exit(EXIT_SUCCESS); } /** * Parse the command line. * * @param argc the argc argument to main() * @param argv the argv argument to main() **/ SERVER* cmdline(int argc, char *argv[]) { int i=0; int nonspecial=0; int c; struct option long_options[] = { {"read-only", no_argument, NULL, 'r'}, {"multi-file", no_argument, NULL, 'm'}, {"copy-on-write", no_argument, NULL, 'c'}, {"authorize-file", required_argument, NULL, 'l'}, {"config-file", required_argument, NULL, 'C'}, {"pid-file", required_argument, NULL, 'p'}, {"output-config", required_argument, NULL, 'o'}, {"max-connection", required_argument, NULL, 'M'}, {0,0,0,0} }; SERVER *serve; off_t es; size_t last; char suffix; gboolean do_output=FALSE; gchar* section_header=""; gchar** addr_port; if(argc==1) { return NULL; } serve=g_new0(SERVER, 1); serve->authname = g_strdup(default_authname); serve->virtstyle=VIRT_IPLIT; while((c=getopt_long(argc, argv, "-C:cl:mo:rp:M:", long_options, &i))>=0) { switch (c) { case 1: /* non-option argument */ switch(nonspecial++) { case 0: if(strchr(optarg, ':') == strrchr(optarg, ':')) { addr_port=g_strsplit(optarg, ":", 2); /* Check for "@" - maybe user using this separator for IPv4 address */ if(!addr_port[1]) { g_strfreev(addr_port); addr_port=g_strsplit(optarg, "@", 2); } } else { addr_port=g_strsplit(optarg, "@", 2); } if(addr_port[1]) { serve->port=strtol(addr_port[1], NULL, 0); serve->listenaddr=g_strdup(addr_port[0]); } else { serve->listenaddr=NULL; serve->port=strtol(addr_port[0], NULL, 0); } g_strfreev(addr_port); break; case 1: serve->exportname = g_strdup(optarg); if(serve->exportname[0] != '/') { fprintf(stderr, "E: The to be exported file needs to be an absolute filename!\n"); exit(EXIT_FAILURE); } break; case 2: last=strlen(optarg)-1; suffix=optarg[last]; if (suffix == 'k' || suffix == 'K' || suffix == 'm' || suffix == 'M') optarg[last] = '\0'; es = (off_t)atoll(optarg); switch (suffix) { case 'm': case 'M': es <<= 10; case 'k': case 'K': es <<= 10; default : break; } serve->expected_size = es; break; } break; case 'r': serve->flags |= F_READONLY; break; case 'm': serve->flags |= F_MULTIFILE; break; case 'o': do_output = TRUE; section_header = g_strdup(optarg); break; case 'p': strncpy(pidftemplate, optarg, 256); break; case 'c': serve->flags |=F_COPYONWRITE; break; case 'C': g_free(config_file_pos); config_file_pos=g_strdup(optarg); break; case 'l': g_free(serve->authname); serve->authname=g_strdup(optarg); break; case 'M': serve->max_connections = strtol(optarg, NULL, 0); break; default: usage(); exit(EXIT_FAILURE); break; } } /* What's left: the port to export, the name of the to be exported * file, and, optionally, the size of the file, in that order. */ if(nonspecial<2) { g_free(serve); serve=NULL; } else { do_oldstyle = TRUE; } if(do_output) { if(!serve) { g_critical("Need a complete configuration on the command line to output a config file section!"); exit(EXIT_FAILURE); } dump_section(serve, section_header); } return serve; } /** * Error codes for config file parsing **/ typedef enum { CFILE_NOTFOUND, /**< The configuration file is not found */ CFILE_MISSING_GENERIC, /**< The (required) group "generic" is missing */ CFILE_KEY_MISSING, /**< A (required) key is missing */ CFILE_VALUE_INVALID, /**< A value is syntactically invalid */ CFILE_VALUE_UNSUPPORTED,/**< A value is not supported in this build */ CFILE_PROGERR, /**< Programmer error */ CFILE_NO_EXPORTS, /**< A config file was specified that does not define any exports */ CFILE_INCORRECT_PORT, /**< The reserved port was specified for an old-style export. */ } CFILE_ERRORS; /** * Remove a SERVER from memory. Used from the hash table **/ void remove_server(gpointer s) { SERVER *server; server=(SERVER*)s; g_free(server->exportname); if(server->authname) g_free(server->authname); if(server->listenaddr) g_free(server->listenaddr); if(server->prerun) g_free(server->prerun); if(server->postrun) g_free(server->postrun); g_free(server); } /** * duplicate server * @param s the old server we want to duplicate * @return new duplicated server **/ SERVER* dup_serve(SERVER *s) { SERVER *serve = NULL; serve=g_new0(SERVER, 1); if(serve == NULL) return NULL; if(s->exportname) serve->exportname = g_strdup(s->exportname); serve->expected_size = s->expected_size; if(s->listenaddr) serve->listenaddr = g_strdup(s->listenaddr); serve->port = s->port; if(s->authname) serve->authname = strdup(s->authname); serve->flags = s->flags; serve->socket = serve->socket; serve->socket_family = serve->socket_family; serve->cidrlen = s->cidrlen; if(s->prerun) serve->prerun = g_strdup(s->prerun); if(s->postrun) serve->postrun = g_strdup(s->postrun); if(s->servename) serve->servename = g_strdup(s->servename); serve->max_connections = s->max_connections; return serve; } /** * append new server to array * @param s server * @param a server array * @return 0 success, -1 error */ int append_serve(SERVER *s, GArray *a) { SERVER *ns = NULL; struct addrinfo hints; struct addrinfo *ai = NULL; struct addrinfo *rp = NULL; char host[NI_MAXHOST]; gchar *port = NULL; int e; int ret; if(!s) { err("Invalid parsing server"); return -1; } port = g_strdup_printf("%d", s->port); memset(&hints,'\0',sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE; hints.ai_protocol = IPPROTO_TCP; e = getaddrinfo(s->listenaddr, port, &hints, &ai); if (port) g_free(port); if(e == 0) { for (rp = ai; rp != NULL; rp = rp->ai_next) { e = getnameinfo(rp->ai_addr, rp->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST); if (e != 0) { // error fprintf(stderr, "getnameinfo: %s\n", gai_strerror(e)); continue; } // duplicate server and set listenaddr to resolved IP address ns = dup_serve (s); if (ns) { ns->listenaddr = g_strdup(host); ns->socket_family = rp->ai_family; g_array_append_val(a, *ns); free(ns); ns = NULL; } } ret = 0; } else { fprintf(stderr, "getaddrinfo failed on listen host/address: %s (%s)\n", s->listenaddr ? s->listenaddr : "any", gai_strerror(e)); ret = -1; } if (ai) freeaddrinfo(ai); return ret; } /** * Parse the config file. * * @param f the name of the config file * @param e a GError. @see CFILE_ERRORS for what error values this function can * return. * @return a Array of SERVER* pointers, If the config file is empty or does not * exist, returns an empty GHashTable; if the config file contains an * error, returns NULL, and e is set appropriately **/ GArray* parse_cfile(gchar* f, GError** e) { const char* DEFAULT_ERROR = "Could not parse %s in group %s: %s"; const char* MISSING_REQUIRED_ERROR = "Could not find required value %s in group %s: %s"; SERVER s; gchar *virtstyle=NULL; PARAM lp[] = { { "exportname", TRUE, PARAM_STRING, NULL, 0 }, { "port", TRUE, PARAM_INT, NULL, 0 }, { "authfile", FALSE, PARAM_STRING, NULL, 0 }, { "filesize", FALSE, PARAM_INT, NULL, 0 }, { "virtstyle", FALSE, PARAM_STRING, NULL, 0 }, { "prerun", FALSE, PARAM_STRING, NULL, 0 }, { "postrun", FALSE, PARAM_STRING, NULL, 0 }, { "readonly", FALSE, PARAM_BOOL, NULL, F_READONLY }, { "multifile", FALSE, PARAM_BOOL, NULL, F_MULTIFILE }, { "copyonwrite", FALSE, PARAM_BOOL, NULL, F_COPYONWRITE }, { "sparse_cow", FALSE, PARAM_BOOL, NULL, F_SPARSE }, { "sdp", FALSE, PARAM_BOOL, NULL, F_SDP }, { "sync", FALSE, PARAM_BOOL, NULL, F_SYNC }, { "listenaddr", FALSE, PARAM_STRING, NULL, 0 }, { "maxconnections", FALSE, PARAM_INT, NULL, 0 }, }; const int lp_size=sizeof(lp)/sizeof(PARAM); PARAM gp[] = { { "user", FALSE, PARAM_STRING, &runuser, 0 }, { "group", FALSE, PARAM_STRING, &rungroup, 0 }, { "oldstyle", FALSE, PARAM_BOOL, &do_oldstyle, 1 }, { "listenaddr", FALSE, PARAM_STRING, &modern_listen, 0 }, }; PARAM* p=gp; int p_size=sizeof(gp)/sizeof(PARAM); GKeyFile *cfile; GError *err = NULL; const char *err_msg=NULL; GQuark errdomain; GArray *retval=NULL; gchar **groups; gboolean value; gchar* startgroup; gint i; gint j; errdomain = g_quark_from_string("parse_cfile"); cfile = g_key_file_new(); retval = g_array_new(FALSE, TRUE, sizeof(SERVER)); if(!g_key_file_load_from_file(cfile, f, G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, &err)) { g_set_error(e, errdomain, CFILE_NOTFOUND, "Could not open config file %s.", f); g_key_file_free(cfile); return retval; } startgroup = g_key_file_get_start_group(cfile); if(!startgroup || strcmp(startgroup, "generic")) { g_set_error(e, errdomain, CFILE_MISSING_GENERIC, "Config file does not contain the [generic] group!"); g_key_file_free(cfile); return NULL; } groups = g_key_file_get_groups(cfile, NULL); for(i=0;groups[i];i++) { memset(&s, '\0', sizeof(SERVER)); lp[0].target=&(s.exportname); lp[1].target=&(s.port); lp[2].target=&(s.authname); lp[3].target=&(s.expected_size); lp[4].target=&(virtstyle); lp[5].target=&(s.prerun); lp[6].target=&(s.postrun); lp[7].target=lp[8].target=lp[9].target= lp[10].target=lp[11].target= lp[12].target=&(s.flags); lp[13].target=&(s.listenaddr); lp[14].target=&(s.max_connections); /* After the [generic] group, start parsing exports */ if(i==1) { p=lp; p_size=lp_size; } for(j=0;j<p_size;j++) { g_assert(p[j].target != NULL); g_assert(p[j].ptype==PARAM_INT||p[j].ptype==PARAM_STRING||p[j].ptype==PARAM_BOOL); switch(p[j].ptype) { case PARAM_INT: *((gint*)p[j].target) = g_key_file_get_integer(cfile, groups[i], p[j].paramname, &err); break; case PARAM_STRING: *((gchar**)p[j].target) = g_key_file_get_string(cfile, groups[i], p[j].paramname, &err); break; case PARAM_BOOL: value = g_key_file_get_boolean(cfile, groups[i], p[j].paramname, &err); if(!err) { if(value) { *((gint*)p[j].target) |= p[j].flagval; } else { *((gint*)p[j].target) &= ~(p[j].flagval); } } break; } if(!strcmp(p[j].paramname, "port") && !strcmp(p[j].target, NBD_DEFAULT_PORT)) { g_set_error(e, errdomain, CFILE_INCORRECT_PORT, "Config file specifies default port for oldstyle export"); g_key_file_free(cfile); return NULL; } if(err) { if(err->code == G_KEY_FILE_ERROR_KEY_NOT_FOUND) { if(!p[j].required) { /* Ignore not-found error for optional values */ g_clear_error(&err); continue; } else { err_msg = MISSING_REQUIRED_ERROR; } } else { err_msg = DEFAULT_ERROR; } g_set_error(e, errdomain, CFILE_VALUE_INVALID, err_msg, p[j].paramname, groups[i], err->message); g_array_free(retval, TRUE); g_error_free(err); g_key_file_free(cfile); return NULL; } } if(virtstyle) { if(!strncmp(virtstyle, "none", 4)) { s.virtstyle=VIRT_NONE; } else if(!strncmp(virtstyle, "ipliteral", 9)) { s.virtstyle=VIRT_IPLIT; } else if(!strncmp(virtstyle, "iphash", 6)) { s.virtstyle=VIRT_IPHASH; } else if(!strncmp(virtstyle, "cidrhash", 8)) { s.virtstyle=VIRT_CIDR; if(strlen(virtstyle)<10) { g_set_error(e, errdomain, CFILE_VALUE_INVALID, "Invalid value %s for parameter virtstyle in group %s: missing length", virtstyle, groups[i]); g_array_free(retval, TRUE); g_key_file_free(cfile); return NULL; } s.cidrlen=strtol(virtstyle+8, NULL, 0); } else { g_set_error(e, errdomain, CFILE_VALUE_INVALID, "Invalid value %s for parameter virtstyle in group %s", virtstyle, groups[i]); g_array_free(retval, TRUE); g_key_file_free(cfile); return NULL; } if(s.port && !do_oldstyle) { g_warning("A port was specified, but oldstyle exports were not requested. This may not do what you expect."); g_warning("Please read 'man 5 nbd-server' and search for oldstyle for more info"); } } else { s.virtstyle=VIRT_IPLIT; } /* Don't need to free this, it's not our string */ virtstyle=NULL; /* Don't append values for the [generic] group */ if(i>0) { s.socket_family = AF_UNSPEC; s.servename = groups[i]; append_serve(&s, retval); } else { if(!do_oldstyle) { lp[1].required = 0; } } #ifndef WITH_SDP if(s.flags & F_SDP) { g_set_error(e, errdomain, CFILE_VALUE_UNSUPPORTED, "This nbd-server was built without support for SDP, yet group %s uses it", groups[i]); g_array_free(retval, TRUE); g_key_file_free(cfile); return NULL; } #endif } if(i==1) { g_set_error(e, errdomain, CFILE_NO_EXPORTS, "The config file does not specify any exports"); } g_key_file_free(cfile); return retval; } /** * Signal handler for SIGCHLD * @param s the signal we're handling (must be SIGCHLD, or something * is severely wrong) **/ void sigchld_handler(int s) { int status; int* i; pid_t pid; while((pid=waitpid(-1, &status, WNOHANG)) > 0) { if(WIFEXITED(status)) { msg3(LOG_INFO, "Child exited with %d", WEXITSTATUS(status)); } i=g_hash_table_lookup(children, &pid); if(!i) { msg3(LOG_INFO, "SIGCHLD received for an unknown child with PID %ld", (long)pid); } else { DEBUG2("Removing %d from the list of children", pid); g_hash_table_remove(children, &pid); } } } /** * Kill a child. Called from sigterm_handler::g_hash_table_foreach. * * @param key the key * @param value the value corresponding to the above key * @param user_data a pointer which we always set to 1, so that we know what * will happen next. **/ void killchild(gpointer key, gpointer value, gpointer user_data) { pid_t *pid=value; int *parent=user_data; kill(*pid, SIGTERM); *parent=1; } /** * Handle SIGTERM and dispatch it to our children * @param s the signal we're handling (must be SIGTERM, or something * is severely wrong). **/ void sigterm_handler(int s) { int parent=0; g_hash_table_foreach(children, killchild, &parent); if(parent) { unlink(pidfname); } exit(EXIT_SUCCESS); } /** * Detect the size of a file. * * @param fhandle An open filedescriptor * @return the size of the file, or OFFT_MAX if detection was * impossible. **/ off_t size_autodetect(int fhandle) { off_t es; u64 bytes; struct stat stat_buf; int error; #ifdef HAVE_SYS_MOUNT_H #ifdef HAVE_SYS_IOCTL_H #ifdef BLKGETSIZE64 DEBUG("looking for export size with ioctl BLKGETSIZE64\n"); if (!ioctl(fhandle, BLKGETSIZE64, &bytes) && bytes) { return (off_t)bytes; } #endif /* BLKGETSIZE64 */ #endif /* HAVE_SYS_IOCTL_H */ #endif /* HAVE_SYS_MOUNT_H */ DEBUG("looking for fhandle size with fstat\n"); stat_buf.st_size = 0; error = fstat(fhandle, &stat_buf); if (!error) { if(stat_buf.st_size > 0) return (off_t)stat_buf.st_size; } else { err("fstat failed: %m"); } DEBUG("looking for fhandle size with lseek SEEK_END\n"); es = lseek(fhandle, (off_t)0, SEEK_END); if (es > ((off_t)0)) { return es; } else { DEBUG2("lseek failed: %d", errno==EBADF?1:(errno==ESPIPE?2:(errno==EINVAL?3:4))); } err("Could not find size of exported block device: %m"); return OFFT_MAX; } /** * Get the file handle and offset, given an export offset. * * @param export An array of export files * @param a The offset to get corresponding file/offset for * @param fhandle [out] File descriptor * @param foffset [out] Offset into fhandle * @param maxbytes [out] Tells how many bytes can be read/written * from fhandle starting at foffset (0 if there is no limit) * @return 0 on success, -1 on failure **/ int get_filepos(GArray* export, off_t a, int* fhandle, off_t* foffset, size_t* maxbytes ) { /* Negative offset not allowed */ if(a < 0) return -1; /* Binary search for last file with starting offset <= a */ FILE_INFO fi; int start = 0; int end = export->len - 1; while( start <= end ) { int mid = (start + end) / 2; fi = g_array_index(export, FILE_INFO, mid); if( fi.startoff < a ) { start = mid + 1; } else if( fi.startoff > a ) { end = mid - 1; } else { start = end = mid; break; } } /* end should never go negative, since first startoff is 0 and a >= 0 */ g_assert(end >= 0); fi = g_array_index(export, FILE_INFO, end); *fhandle = fi.fhandle; *foffset = a - fi.startoff; *maxbytes = 0; if( end+1 < export->len ) { FILE_INFO fi_next = g_array_index(export, FILE_INFO, end+1); *maxbytes = fi_next.startoff - a; } return 0; } /** * seek to a position in a file, with error handling. * @param handle a filedescriptor * @param a position to seek to * @todo get rid of this; lastpoint is a global variable right now, but it * shouldn't be. If we pass it on as a parameter, that makes things a *lot* * easier. **/ void myseek(int handle,off_t a) { if (lseek(handle, a, SEEK_SET) < 0) { err("Can not seek locally!\n"); } } /** * Write an amount of bytes at a given offset to the right file. This * abstracts the write-side of the multiple file option. * * @param a The offset where the write should start * @param buf The buffer to write from * @param len The length of buf * @param client The client we're serving for * @return The number of bytes actually written, or -1 in case of an error **/ ssize_t rawexpwrite(off_t a, char *buf, size_t len, CLIENT *client) { int fhandle; off_t foffset; size_t maxbytes; ssize_t retval; if(get_filepos(client->export, a, &fhandle, &foffset, &maxbytes)) return -1; if(maxbytes && len > maxbytes) len = maxbytes; DEBUG4("(WRITE to fd %d offset %llu len %u), ", fhandle, foffset, len); myseek(fhandle, foffset); retval = write(fhandle, buf, len); if(client->server->flags & F_SYNC) { fsync(fhandle); } return retval; } /** * Call rawexpwrite repeatedly until all data has been written. * @return 0 on success, nonzero on failure **/ int rawexpwrite_fully(off_t a, char *buf, size_t len, CLIENT *client) { ssize_t ret=0; while(len > 0 && (ret=rawexpwrite(a, buf, len, client)) > 0 ) { a += ret; buf += ret; len -= ret; } return (ret < 0 || len != 0); } /** * Read an amount of bytes at a given offset from the right file. This * abstracts the read-side of the multiple files option. * * @param a The offset where the read should start * @param buf A buffer to read into * @param len The size of buf * @param client The client we're serving for * @return The number of bytes actually read, or -1 in case of an * error. **/ ssize_t rawexpread(off_t a, char *buf, size_t len, CLIENT *client) { int fhandle; off_t foffset; size_t maxbytes; if(get_filepos(client->export, a, &fhandle, &foffset, &maxbytes)) return -1; if(maxbytes && len > maxbytes) len = maxbytes; DEBUG4("(READ from fd %d offset %llu len %u), ", fhandle, foffset, len); myseek(fhandle, foffset); return read(fhandle, buf, len); } /** * Call rawexpread repeatedly until all data has been read. * @return 0 on success, nonzero on failure **/ int rawexpread_fully(off_t a, char *buf, size_t len, CLIENT *client) { ssize_t ret=0; while(len > 0 && (ret=rawexpread(a, buf, len, client)) > 0 ) { a += ret; buf += ret; len -= ret; } return (ret < 0 || len != 0); } /** * Read an amount of bytes at a given offset from the right file. This * abstracts the read-side of the copyonwrite stuff, and calls * rawexpread() with the right parameters to do the actual work. * @param a The offset where the read should start * @param buf A buffer to read into * @param len The size of buf * @param client The client we're going to read for * @return 0 on success, nonzero on failure **/ int expread(off_t a, char *buf, size_t len, CLIENT *client) { off_t rdlen, offset; off_t mapcnt, mapl, maph, pagestart; if (!(client->server->flags & F_COPYONWRITE)) return(rawexpread_fully(a, buf, len, client)); DEBUG3("Asked to read %d bytes at %llu.\n", len, (unsigned long long)a); mapl=a/DIFFPAGESIZE; maph=(a+len-1)/DIFFPAGESIZE; for (mapcnt=mapl;mapcnt<=maph;mapcnt++) { pagestart=mapcnt*DIFFPAGESIZE; offset=a-pagestart; rdlen=(0<DIFFPAGESIZE-offset && len<(size_t)(DIFFPAGESIZE-offset)) ? len : (size_t)DIFFPAGESIZE-offset; if (client->difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */ DEBUG3("Page %llu is at %lu\n", (unsigned long long)mapcnt, (unsigned long)(client->difmap[mapcnt])); myseek(client->difffile, client->difmap[mapcnt]*DIFFPAGESIZE+offset); if (read(client->difffile, buf, rdlen) != rdlen) return -1; } else { /* the block is not there */ DEBUG2("Page %llu is not here, we read the original one\n", (unsigned long long)mapcnt); if(rawexpread_fully(a, buf, rdlen, client)) return -1; } len-=rdlen; a+=rdlen; buf+=rdlen; } return 0; } /** * Write an amount of bytes at a given offset to the right file. This * abstracts the write-side of the copyonwrite option, and calls * rawexpwrite() with the right parameters to do the actual work. * * @param a The offset where the write should start * @param buf The buffer to write from * @param len The length of buf * @param client The client we're going to write for. * @return 0 on success, nonzero on failure **/ int expwrite(off_t a, char *buf, size_t len, CLIENT *client) { char pagebuf[DIFFPAGESIZE]; off_t mapcnt,mapl,maph; off_t wrlen,rdlen; off_t pagestart; off_t offset; if (!(client->server->flags & F_COPYONWRITE)) return(rawexpwrite_fully(a, buf, len, client)); DEBUG3("Asked to write %d bytes at %llu.\n", len, (unsigned long long)a); mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ; for (mapcnt=mapl;mapcnt<=maph;mapcnt++) { pagestart=mapcnt*DIFFPAGESIZE ; offset=a-pagestart ; wrlen=(0<DIFFPAGESIZE-offset && len<(size_t)(DIFFPAGESIZE-offset)) ? len : (size_t)DIFFPAGESIZE-offset; if (client->difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */ DEBUG3("Page %llu is at %lu\n", (unsigned long long)mapcnt, (unsigned long)(client->difmap[mapcnt])) ; myseek(client->difffile, client->difmap[mapcnt]*DIFFPAGESIZE+offset); if (write(client->difffile, buf, wrlen) != wrlen) return -1 ; } else { /* the block is not there */ myseek(client->difffile,client->difffilelen*DIFFPAGESIZE) ; client->difmap[mapcnt]=(client->server->flags&F_SPARSE)?mapcnt:client->difffilelen++; DEBUG3("Page %llu is not here, we put it at %lu\n", (unsigned long long)mapcnt, (unsigned long)(client->difmap[mapcnt])); rdlen=DIFFPAGESIZE ; if (rawexpread_fully(pagestart, pagebuf, rdlen, client)) return -1; memcpy(pagebuf+offset,buf,wrlen) ; if (write(client->difffile, pagebuf, DIFFPAGESIZE) != DIFFPAGESIZE) return -1; } len-=wrlen ; a+=wrlen ; buf+=wrlen ; } return 0; } /** * Do the initial negotiation. * * @param client The client we're negotiating with. **/ CLIENT* negotiate(int net, CLIENT *client, GArray* servers) { char zeros[128]; uint64_t size_host; uint32_t flags = NBD_FLAG_HAS_FLAGS; uint16_t smallflags = 0; uint64_t magic; memset(zeros, '\0', sizeof(zeros)); if(!client || !client->modern) { /* common */ if (write(net, INIT_PASSWD, 8) < 0) { err_nonfatal("Negotiation failed: %m"); if(client) exit(EXIT_FAILURE); } if(!client || client->modern) { /* modern */ magic = htonll(opts_magic); } else { /* oldstyle */ magic = htonll(cliserv_magic); } if (write(net, &magic, sizeof(magic)) < 0) { err_nonfatal("Negotiation failed: %m"); if(client) exit(EXIT_FAILURE); } } if(!client) { /* modern */ uint32_t reserved; uint32_t opt; uint32_t namelen; char* name; int i; if(!servers) err("programmer error"); if (write(net, &smallflags, sizeof(uint16_t)) < 0) err("Negotiation failed: %m"); if (read(net, &reserved, sizeof(reserved)) < 0) err("Negotiation failed: %m"); if (read(net, &magic, sizeof(magic)) < 0) err("Negotiation failed: %m"); magic = ntohll(magic); if(magic != opts_magic) { close(net); return NULL; } if (read(net, &opt, sizeof(opt)) < 0) err("Negotiation failed: %m"); opt = ntohl(opt); if(opt != NBD_OPT_EXPORT_NAME) { close(net); return NULL; } if (read(net, &namelen, sizeof(namelen)) < 0) err("Negotiation failed: %m"); namelen = ntohl(namelen); name = malloc(namelen+1); name[namelen]=0; if (read(net, name, namelen) < 0) err("Negotiation failed: %m"); for(i=0; i<servers->len; i++) { SERVER* serve = &(g_array_index(servers, SERVER, i)); if(!strcmp(serve->servename, name)) { CLIENT* client = g_new0(CLIENT, 1); client->server = serve; client->exportsize = OFFT_MAX; client->net = net; client->modern = TRUE; return client; } } return NULL; } /* common */ size_host = htonll((u64)(client->exportsize)); if (write(net, &size_host, 8) < 0) err("Negotiation failed: %m"); if (client->server->flags & F_READONLY) flags |= NBD_FLAG_READ_ONLY; if (!client->modern) { /* oldstyle */ flags = htonl(flags); if (write(client->net, &flags, 4) < 0) err("Negotiation failed: %m"); } else { /* modern */ smallflags = (uint16_t)(flags & ~((uint16_t)0)); smallflags = htons(smallflags); if (write(client->net, &smallflags, sizeof(smallflags)) < 0) { err("Negotiation failed: %m"); } } /* common */ if (write(client->net, zeros, 124) < 0) err("Negotiation failed: %m"); return NULL; } /** sending macro. */ #define SEND(net,reply) writeit( net, &reply, sizeof( reply )); /** error macro. */ #define ERROR(client,reply,errcode) { reply.error = htonl(errcode); SEND(client->net,reply); reply.error = 0; } /** * Serve a file to a single client. * * @todo This beast needs to be split up in many tiny little manageable * pieces. Preferably with a chainsaw. * * @param client The client we're going to serve to. * @return when the client disconnects **/ int mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE - sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; } /** * Set up client export array, which is an array of FILE_INFO. * Also, split a single exportfile into multiple ones, if that was asked. * @param client information on the client which we want to setup export for **/ void setupexport(CLIENT* client) { int i; off_t laststartoff = 0, lastsize = 0; int multifile = (client->server->flags & F_MULTIFILE); client->export = g_array_new(TRUE, TRUE, sizeof(FILE_INFO)); /* If multi-file, open as many files as we can. * If not, open exactly one file. * Calculate file sizes as we go to get total size. */ for(i=0; ; i++) { FILE_INFO fi; gchar *tmpname; gchar* error_string; mode_t mode = (client->server->flags & F_READONLY) ? O_RDONLY : O_RDWR; if(multifile) { tmpname=g_strdup_printf("%s.%d", client->exportname, i); } else { tmpname=g_strdup(client->exportname); } DEBUG2( "Opening %s\n", tmpname ); fi.fhandle = open(tmpname, mode); if(fi.fhandle == -1 && mode == O_RDWR) { /* Try again because maybe media was read-only */ fi.fhandle = open(tmpname, O_RDONLY); if(fi.fhandle != -1) { /* Opening the base file in copyonwrite mode is * okay */ if(!(client->server->flags & F_COPYONWRITE)) { client->server->flags |= F_AUTOREADONLY; client->server->flags |= F_READONLY; } } } if(fi.fhandle == -1) { if(multifile && i>0) break; error_string=g_strdup_printf( "Could not open exported file %s: %%m", tmpname); err(error_string); } fi.startoff = laststartoff + lastsize; g_array_append_val(client->export, fi); g_free(tmpname); /* Starting offset and size of this file will be used to * calculate starting offset of next file */ laststartoff = fi.startoff; lastsize = size_autodetect(fi.fhandle); if(!multifile) break; } /* Set export size to total calculated size */ client->exportsize = laststartoff + lastsize; /* Export size may be overridden */ if(client->server->expected_size) { /* desired size must be <= total calculated size */ if(client->server->expected_size > client->exportsize) { err("Size of exported file is too big\n"); } client->exportsize = client->server->expected_size; } msg3(LOG_INFO, "Size of exported file/device is %llu", (unsigned long long)client->exportsize); if(multifile) { msg3(LOG_INFO, "Total number of files: %d", i); } } int copyonwrite_prepare(CLIENT* client) { off_t i; if ((client->difffilename = malloc(1024))==NULL) err("Failed to allocate string for diff file name"); snprintf(client->difffilename, 1024, "%s-%s-%d.diff",client->exportname,client->clientname, (int)getpid()) ; client->difffilename[1023]='\0'; msg3(LOG_INFO,"About to create map and diff file %s",client->difffilename) ; client->difffile=open(client->difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ; if (client->difffile<0) err("Could not create diff file (%m)") ; if ((client->difmap=calloc(client->exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL) err("Could not allocate memory") ; for (i=0;i<client->exportsize/DIFFPAGESIZE;i++) client->difmap[i]=(u32)-1 ; return 0; } /** * Run a command. This is used for the ``prerun'' and ``postrun'' config file * options * * @param command the command to be ran. Read from the config file * @param file the file name we're about to export **/ int do_run(gchar* command, gchar* file) { gchar* cmd; int retval=0; if(command && *command) { cmd = g_strdup_printf(command, file); retval=system(cmd); g_free(cmd); } return retval; } /** * Serve a connection. * * @todo allow for multithreading, perhaps use libevent. Not just yet, though; * follow the road map. * * @param client a connected client **/ void serveconnection(CLIENT *client) { if(do_run(client->server->prerun, client->exportname)) { exit(EXIT_FAILURE); } setupexport(client); if (client->server->flags & F_COPYONWRITE) { copyonwrite_prepare(client); } setmysockopt(client->net); mainloop(client); do_run(client->server->postrun, client->exportname); } /** * Find the name of the file we have to serve. This will use g_strdup_printf * to put the IP address of the client inside a filename containing * "%s" (in the form as specified by the "virtstyle" option). That name * is then written to client->exportname. * * @param net A socket connected to an nbd client * @param client information about the client. The IP address in human-readable * format will be written to a new char* buffer, the address of which will be * stored in client->clientname. **/ void set_peername(int net, CLIENT *client) { struct sockaddr_storage addrin; struct sockaddr_storage netaddr; struct sockaddr_in *netaddr4 = NULL; struct sockaddr_in6 *netaddr6 = NULL; size_t addrinlen = sizeof( addrin ); struct addrinfo hints; struct addrinfo *ai = NULL; char peername[NI_MAXHOST]; char netname[NI_MAXHOST]; char *tmp = NULL; int i; int e; int shift; if (getpeername(net, (struct sockaddr *) &addrin, (socklen_t *)&addrinlen) < 0) err("getsockname failed: %m"); getnameinfo((struct sockaddr *)&addrin, (socklen_t)addrinlen, peername, sizeof (peername), NULL, 0, NI_NUMERICHOST); memset(&hints, '\0', sizeof (hints)); hints.ai_flags = AI_ADDRCONFIG; e = getaddrinfo(peername, NULL, &hints, &ai); if(e != 0) { fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e)); freeaddrinfo(ai); return; } switch(client->server->virtstyle) { case VIRT_NONE: client->exportname=g_strdup(client->server->exportname); break; case VIRT_IPHASH: for(i=0;i<strlen(peername);i++) { if(peername[i]=='.') { peername[i]='/'; } } case VIRT_IPLIT: client->exportname=g_strdup_printf(client->server->exportname, peername); break; case VIRT_CIDR: memcpy(&netaddr, &addrin, addrinlen); if(ai->ai_family == AF_INET) { netaddr4 = (struct sockaddr_in *)&netaddr; (netaddr4->sin_addr).s_addr>>=32-(client->server->cidrlen); (netaddr4->sin_addr).s_addr<<=32-(client->server->cidrlen); getnameinfo((struct sockaddr *) netaddr4, (socklen_t) addrinlen, netname, sizeof (netname), NULL, 0, NI_NUMERICHOST); tmp=g_strdup_printf("%s/%s", netname, peername); }else if(ai->ai_family == AF_INET6) { netaddr6 = (struct sockaddr_in6 *)&netaddr; shift = 128-(client->server->cidrlen); i = 3; while(shift >= 32) { ((netaddr6->sin6_addr).s6_addr32[i])=0; shift-=32; i--; } (netaddr6->sin6_addr).s6_addr32[i]>>=shift; (netaddr6->sin6_addr).s6_addr32[i]<<=shift; getnameinfo((struct sockaddr *)netaddr6, (socklen_t)addrinlen, netname, sizeof(netname), NULL, 0, NI_NUMERICHOST); tmp=g_strdup_printf("%s/%s", netname, peername); } if(tmp != NULL) client->exportname=g_strdup_printf(client->server->exportname, tmp); break; } freeaddrinfo(ai); msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, client->exportname); client->clientname=g_strdup(peername); } /** * Destroy a pid_t* * @param data a pointer to pid_t which should be freed **/ void destroy_pid_t(gpointer data) { g_free(data); } /** * Loop through the available servers, and serve them. Never returns. **/ int serveloop(GArray* servers) { struct sockaddr_storage addrin; socklen_t addrinlen=sizeof(addrin); int i; int max; int sock; fd_set mset; fd_set rset; /* * Set up the master fd_set. The set of descriptors we need * to select() for never changes anyway and it buys us a *lot* * of time to only build this once. However, if we ever choose * to not fork() for clients anymore, we may have to revisit * this. */ max=0; FD_ZERO(&mset); for(i=0;i<servers->len;i++) { if((sock=(g_array_index(servers, SERVER, i)).socket)) { FD_SET(sock, &mset); max=sock>max?sock:max; } } if(modernsock) { FD_SET(modernsock, &mset); max=modernsock>max?modernsock:max; } for(;;) { CLIENT *client = NULL; pid_t *pid; memcpy(&rset, &mset, sizeof(fd_set)); if(select(max+1, &rset, NULL, NULL, NULL)>0) { int net = 0; SERVER* serve; DEBUG("accept, "); if(FD_ISSET(modernsock, &rset)) { if((net=accept(modernsock, (struct sockaddr *) &addrin, &addrinlen)) < 0) err("accept: %m"); client = negotiate(net, NULL, servers); if(!client) { err_nonfatal("negotiation failed"); close(net); net=0; } } for(i=0;i<servers->len && !net;i++) { serve=&(g_array_index(servers, SERVER, i)); if(FD_ISSET(serve->socket, &rset)) { if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) err("accept: %m"); } } if(net) { int sock_flags; if(serve->max_connections > 0 && g_hash_table_size(children) >= serve->max_connections) { msg2(LOG_INFO, "Max connections reached"); close(net); continue; } if((sock_flags = fcntl(net, F_GETFL, 0))==-1) { err("fcntl F_GETFL"); } if(fcntl(net, F_SETFL, sock_flags &~O_NONBLOCK)==-1) { err("fcntl F_SETFL ~O_NONBLOCK"); } if(!client) { client = g_new0(CLIENT, 1); client->server=serve; client->exportsize=OFFT_MAX; client->net=net; } set_peername(net, client); if (!authorized_client(client)) { msg2(LOG_INFO,"Unauthorized client") ; close(net); continue; } msg2(LOG_INFO,"Authorized client") ; pid=g_malloc(sizeof(pid_t)); #ifndef NOFORK if ((*pid=fork())<0) { msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ; close(net); continue; } if (*pid>0) { /* parent */ close(net); g_hash_table_insert(children, pid, pid); continue; } /* child */ g_hash_table_destroy(children); for(i=0;i<servers->len;i++) { serve=&g_array_index(servers, SERVER, i); close(serve->socket); } /* FALSE does not free the actual data. This is required, because the client has a direct reference into that data, and otherwise we get a segfault... */ g_array_free(servers, FALSE); #endif // NOFORK msg2(LOG_INFO,"Starting to serve"); serveconnection(client); exit(EXIT_SUCCESS); } } } } void dosockopts(int socket) { #ifndef sun int yes=1; #else char yes='1'; #endif /* sun */ int sock_flags; /* lose the pesky "Address already in use" error message */ if (setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) { err("setsockopt SO_REUSEADDR"); } if (setsockopt(socket,SOL_SOCKET,SO_KEEPALIVE,&yes,sizeof(int)) == -1) { err("setsockopt SO_KEEPALIVE"); } /* make the listening socket non-blocking */ if ((sock_flags = fcntl(socket, F_GETFL, 0)) == -1) { err("fcntl F_GETFL"); } if (fcntl(socket, F_SETFL, sock_flags | O_NONBLOCK) == -1) { err("fcntl F_SETFL O_NONBLOCK"); } } /** * Connect a server's socket. * * @param serve the server we want to connect. **/ int setup_serve(SERVER *serve) { struct addrinfo hints; struct addrinfo *ai = NULL; gchar *port = NULL; int e; if(!do_oldstyle) { return serve->servename ? 1 : 0; } memset(&hints,'\0',sizeof(hints)); hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG | AI_NUMERICSERV; hints.ai_socktype = SOCK_STREAM; hints.ai_family = serve->socket_family; port = g_strdup_printf ("%d", serve->port); if (port == NULL) return 0; e = getaddrinfo(serve->listenaddr,port,&hints,&ai); g_free(port); if(e != 0) { fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e)); serve->socket = -1; freeaddrinfo(ai); exit(EXIT_FAILURE); } if(serve->socket_family == AF_UNSPEC) serve->socket_family = ai->ai_family; #ifdef WITH_SDP if ((serve->flags) && F_SDP) { if (ai->ai_family == AF_INET) ai->ai_family = AF_INET_SDP; else (ai->ai_family == AF_INET6) ai->ai_family = AF_INET6_SDP; } #endif if ((serve->socket = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) err("socket: %m"); dosockopts(serve->socket); DEBUG("Waiting for connections... bind, "); e = bind(serve->socket, ai->ai_addr, ai->ai_addrlen); if (e != 0 && errno != EADDRINUSE) err("bind: %m"); DEBUG("listen, "); if (listen(serve->socket, 1) < 0) err("listen: %m"); freeaddrinfo (ai); if(serve->servename) { return 1; } else { return 0; } } void open_modern(void) { struct addrinfo hints; struct addrinfo* ai = NULL; struct sock_flags; int e; memset(&hints, '\0', sizeof(hints)); hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_UNSPEC; hints.ai_protocol = IPPROTO_TCP; e = getaddrinfo(modern_listen, NBD_DEFAULT_PORT, &hints, &ai); if(e != 0) { fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e)); exit(EXIT_FAILURE); } if((modernsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))<0) { err("socket: %m"); } dosockopts(modernsock); if(bind(modernsock, ai->ai_addr, ai->ai_addrlen)) { err("bind: %m"); } if(listen(modernsock, 10) <0) { err("listen: %m"); } freeaddrinfo(ai); } /** * Connect our servers. **/ void setup_servers(GArray* servers) { int i; struct sigaction sa; int want_modern=0; for(i=0;i<servers->len;i++) { want_modern |= setup_serve(&(g_array_index(servers, SERVER, i))); } if(want_modern) { open_modern(); } children=g_hash_table_new_full(g_int_hash, g_int_equal, NULL, destroy_pid_t); sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if(sigaction(SIGCHLD, &sa, NULL) == -1) err("sigaction: %m"); sa.sa_handler = sigterm_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if(sigaction(SIGTERM, &sa, NULL) == -1) err("sigaction: %m"); } /** * Go daemon (unless we specified at compile time that we didn't want this) * @param serve the first server of our configuration. If its port is zero, * then do not daemonize, because we're doing inetd then. This parameter * is only used to create a PID file of the form * /var/run/nbd-server.&lt;port&gt;.pid; it's not modified in any way. **/ #if !defined(NODAEMON) && !defined(NOFORK) void daemonize(SERVER* serve) { FILE*pidf; if(serve && !(serve->port)) { return; } if(daemon(0,0)<0) { err("daemon"); } if(!*pidftemplate) { if(serve) { strncpy(pidftemplate, "/var/run/nbd-server.%d.pid", 255); } else { strncpy(pidftemplate, "/var/run/nbd-server.pid", 255); } } snprintf(pidfname, 255, pidftemplate, serve ? serve->port : 0); pidf=fopen(pidfname, "w"); if(pidf) { fprintf(pidf,"%d\n", (int)getpid()); fclose(pidf); } else { perror("fopen"); fprintf(stderr, "Not fatal; continuing"); } } #else #define daemonize(serve) #endif /* !defined(NODAEMON) && !defined(NOFORK) */ /* * Everything beyond this point (in the file) is run in non-daemon mode. * The stuff above daemonize() isn't. */ void serve_err(SERVER* serve, const char* msg) G_GNUC_NORETURN; void serve_err(SERVER* serve, const char* msg) { g_message("Export of %s on port %d failed:", serve->exportname, serve->port); err(msg); } /** * Set up user-ID and/or group-ID **/ void dousers(void) { struct passwd *pw; struct group *gr; gchar* str; if(rungroup) { gr=getgrnam(rungroup); if(!gr) { str = g_strdup_printf("Invalid group name: %s", rungroup); err(str); } if(setgid(gr->gr_gid)<0) { err("Could not set GID: %m"); } } if(runuser) { pw=getpwnam(runuser); if(!pw) { str = g_strdup_printf("Invalid user name: %s", runuser); err(str); } if(setuid(pw->pw_uid)<0) { err("Could not set UID: %m"); } } } #ifndef ISSERVER void glib_message_syslog_redirect(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { int level=LOG_DEBUG; switch( log_level ) { case G_LOG_FLAG_FATAL: case G_LOG_LEVEL_CRITICAL: case G_LOG_LEVEL_ERROR: level=LOG_ERR; break; case G_LOG_LEVEL_WARNING: level=LOG_WARNING; break; case G_LOG_LEVEL_MESSAGE: case G_LOG_LEVEL_INFO: level=LOG_INFO; break; case G_LOG_LEVEL_DEBUG: level=LOG_DEBUG; default: level=LOG_ERR; } syslog(level, "%s", message); } #endif /** * Main entry point... **/ int main(int argc, char *argv[]) { SERVER *serve; GArray *servers; GError *err=NULL; if (sizeof( struct nbd_request )!=28) { fprintf(stderr,"Bad size of structure. Alignment problems?\n"); exit(EXIT_FAILURE) ; } memset(pidftemplate, '\0', 256); logging(); config_file_pos = g_strdup(CFILE); serve=cmdline(argc, argv); servers = parse_cfile(config_file_pos, &err); if(serve) { serve->socket_family = AF_UNSPEC; append_serve(serve, servers); if (!(serve->port)) { CLIENT *client; #ifndef ISSERVER /* You really should define ISSERVER if you're going to use * inetd mode, but if you don't, closing stdout and stderr * (which inetd had connected to the client socket) will let it * work. */ close(1); close(2); open("/dev/null", O_WRONLY); open("/dev/null", O_WRONLY); g_log_set_default_handler( glib_message_syslog_redirect, NULL ); #endif client=g_malloc(sizeof(CLIENT)); client->server=serve; client->net=0; client->exportsize=OFFT_MAX; set_peername(0,client); serveconnection(client); return 0; } } if(!servers || !servers->len) { if(err && !(err->domain == g_quark_from_string("parse_cfile") && err->code == CFILE_NOTFOUND)) { g_warning("Could not parse config file: %s", err ? err->message : "Unknown error"); } } if(serve) { g_warning("Specifying an export on the command line is deprecated."); g_warning("Please use a configuration file instead."); } if((!serve) && (!servers||!servers->len)) { g_message("No configured exports; quitting."); exit(EXIT_FAILURE); } daemonize(serve); setup_servers(servers); dousers(); serveloop(servers); return 0 ; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3426_0
crossvul-cpp_data_good_896_1
/* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_MQTT #include <string.h> #include "mg_internal.h" #include "mg_mqtt.h" static uint16_t getu16(const char *p) { const uint8_t *up = (const uint8_t *) p; return (up[0] << 8) + up[1]; } static const char *scanto(const char *p, struct mg_str *s) { s->len = getu16(p); s->p = p + 2; return s->p + s->len; } MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { uint8_t header; size_t len = 0, len_len = 0; const char *p, *end, *eop = &io->buf[io->len]; unsigned char lc = 0; int cmd; if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG; header = io->buf[0]; cmd = header >> 4; /* decode mqtt variable length */ len = len_len = 0; p = io->buf + 1; while (p < eop) { lc = *((const unsigned char *) p++); len += (lc & 0x7f) << 7 * len_len; len_len++; if (!(lc & 0x80)) break; if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG; } end = p + len; if (lc & 0x80 || end > eop) return MG_MQTT_ERROR_INCOMPLETE_MSG; mm->cmd = cmd; mm->qos = MG_MQTT_GET_QOS(header); switch (cmd) { case MG_MQTT_CMD_CONNECT: { p = scanto(p, &mm->protocol_name); if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG; mm->protocol_version = *(uint8_t *) p++; mm->connect_flags = *(uint8_t *) p++; mm->keep_alive_timer = getu16(p); p += 2; if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->client_id); if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; if (mm->connect_flags & MG_MQTT_HAS_WILL) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->will_topic); } if (mm->connect_flags & MG_MQTT_HAS_WILL) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->will_message); } if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->user_name); } if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->password); } if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG; LOG(LL_DEBUG, ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] " "will_msg [%.*s] user_name [%.*s] password [%.*s]", (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer, (int) mm->protocol_name.len, mm->protocol_name.p, (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len, mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p, (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len, mm->password.p)); break; } case MG_MQTT_CMD_CONNACK: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->connack_ret_code = p[1]; break; case MG_MQTT_CMD_PUBACK: case MG_MQTT_CMD_PUBREC: case MG_MQTT_CMD_PUBREL: case MG_MQTT_CMD_PUBCOMP: case MG_MQTT_CMD_SUBACK: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; break; case MG_MQTT_CMD_PUBLISH: { p = scanto(p, &mm->topic); if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; if (mm->qos > 0) { if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; } mm->payload.p = p; mm->payload.len = end - p; break; } case MG_MQTT_CMD_SUBSCRIBE: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; /* * topic expressions are left in the payload and can be parsed with * `mg_mqtt_next_subscribe_topic` */ mm->payload.p = p; mm->payload.len = end - p; break; default: /* Unhandled command */ break; } mm->len = end - io->buf; return mm->len; } static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_mqtt_message mm; memset(&mm, 0, sizeof(mm)); nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_ACCEPT: if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); break; case MG_EV_RECV: { /* There can be multiple messages in the buffer, process them all. */ while (1) { int len = parse_mqtt(io, &mm); if (len < 0) { if (len == MG_MQTT_ERROR_MALFORMED_MSG) { /* Protocol error. */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) { /* Not fully buffered, let's check if we have a chance to get more * data later */ if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " "%lu bytes, and not drained, closing", nc, (unsigned long) nc->recv_mbuf.len, (unsigned long) nc->recv_mbuf_limit)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { /* Should never be here */ LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; } nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data)); mbuf_remove(io, len); } break; } case MG_EV_POLL: { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; double now = mg_time(); if (pd->keep_alive > 0 && pd->last_control_time > 0 && (now - pd->last_control_time) > pd->keep_alive) { LOG(LL_DEBUG, ("Send PINGREQ")); mg_mqtt_ping(nc); } break; } } } static void mg_mqtt_proto_data_destructor(void *proto_data) { MG_FREE(proto_data); } static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) { struct mg_str res = *topic; const char *c = mg_strchr(*topic, '/'); if (c != NULL) { res.len = (c - topic->p); topic->len -= (res.len + 1); topic->p += (res.len + 1); } else { topic->len = 0; } return res; } /* Refernce: https://mosquitto.org/man/mqtt-7.html */ int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) { struct mg_str ec, tc; if (exp.len == 0) return 0; while (1) { ec = mg_mqtt_next_topic_component(&exp); tc = mg_mqtt_next_topic_component(&topic); if (ec.len == 0) { if (tc.len != 0) return 0; if (exp.len == 0) break; continue; } if (mg_vcmp(&ec, "+") == 0) { if (tc.len == 0 && topic.len == 0) return 0; continue; } if (mg_vcmp(&ec, "#") == 0) { /* Must be the last component in the expression or it's invalid. */ return (exp.len == 0); } if (mg_strcmp(ec, tc) != 0) { return 0; } } return (tc.len == 0 && topic.len == 0); } int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) { return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic); } void mg_set_protocol_mqtt(struct mg_connection *nc) { nc->proto_handler = mqtt_handler; nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data)); nc->proto_data_destructor = mg_mqtt_proto_data_destructor; } static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd, uint8_t flags, size_t len) { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; uint8_t buf[1 + sizeof(size_t)]; uint8_t *vlen = &buf[1]; buf[0] = (cmd << 4) | flags; /* mqtt variable length encoding */ do { *vlen = len % 0x80; len /= 0x80; if (len > 0) *vlen |= 0x80; vlen++; } while (len > 0); mg_send(nc, buf, vlen - buf); pd->last_control_time = mg_time(); } void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { static struct mg_send_mqtt_handshake_opts opts; mg_send_mqtt_handshake_opt(nc, client_id, opts); } void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, struct mg_send_mqtt_handshake_opts opts) { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0; uint16_t netbytes; size_t total_len; if (client_id != NULL) { id_len = strlen(client_id); } total_len = 7 + 1 + 2 + 2 + id_len; if (opts.user_name != NULL) { opts.flags |= MG_MQTT_HAS_USER_NAME; } if (opts.password != NULL) { opts.flags |= MG_MQTT_HAS_PASSWORD; } if (opts.will_topic != NULL && opts.will_message != NULL) { wt_len = strlen(opts.will_topic); wm_len = strlen(opts.will_message); opts.flags |= MG_MQTT_HAS_WILL; } if (opts.keep_alive == 0) { opts.keep_alive = 60; } if (opts.flags & MG_MQTT_HAS_WILL) { total_len += 2 + wt_len + 2 + wm_len; } if (opts.flags & MG_MQTT_HAS_USER_NAME) { user_len = strlen(opts.user_name); total_len += 2 + user_len; } if (opts.flags & MG_MQTT_HAS_PASSWORD) { pw_len = strlen(opts.password); total_len += 2 + pw_len; } mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len); mg_send(nc, "\00\04MQTT\04", 7); mg_send(nc, &opts.flags, 1); netbytes = htons(opts.keep_alive); mg_send(nc, &netbytes, 2); netbytes = htons(id_len); mg_send(nc, &netbytes, 2); mg_send(nc, client_id, id_len); if (opts.flags & MG_MQTT_HAS_WILL) { netbytes = htons(wt_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.will_topic, wt_len); netbytes = htons(wm_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.will_message, wm_len); } if (opts.flags & MG_MQTT_HAS_USER_NAME) { netbytes = htons(user_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.user_name, user_len); } if (opts.flags & MG_MQTT_HAS_PASSWORD) { netbytes = htons(pw_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.password, pw_len); } if (pd != NULL) { pd->keep_alive = opts.keep_alive; } } void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len) { uint16_t netbytes; uint16_t topic_len = strlen(topic); size_t total_len = 2 + topic_len + len; if (MG_MQTT_GET_QOS(flags) > 0) { total_len += 2; } mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topic, topic_len); if (MG_MQTT_GET_QOS(flags) > 0) { netbytes = htons(message_id); mg_send(nc, &netbytes, 2); } mg_send(nc, data, len); } void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id) { uint16_t netbytes; size_t i; uint16_t topic_len; size_t total_len = 2; for (i = 0; i < topics_len; i++) { total_len += 2 + strlen(topics[i].topic) + 1; } mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len); netbytes = htons(message_id); mg_send(nc, (char *) &netbytes, 2); for (i = 0; i < topics_len; i++) { topic_len = strlen(topics[i].topic); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topics[i].topic, topic_len); mg_send(nc, &topics[i].qos, 1); } } int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos) { unsigned char *buf = (unsigned char *) msg->payload.p + pos; int new_pos; if ((size_t) pos >= msg->payload.len) return -1; topic->len = buf[0] << 8 | buf[1]; topic->p = (char *) buf + 2; new_pos = pos + 2 + topic->len + 1; if ((size_t) new_pos > msg->payload.len) return -1; *qos = buf[2 + topic->len]; return new_pos; } void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id) { uint16_t netbytes; size_t i; uint16_t topic_len; size_t total_len = 2; for (i = 0; i < topics_len; i++) { total_len += 2 + strlen(topics[i]); } mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len); netbytes = htons(message_id); mg_send(nc, (char *) &netbytes, 2); for (i = 0; i < topics_len; i++) { topic_len = strlen(topics[i]); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topics[i], topic_len); } } void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { uint8_t unused = 0; mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); mg_send(nc, &unused, 1); mg_send(nc, &return_code, 1); } /* * Sends a command which contains only a `message_id` and a QoS level of 1. * * Helper function. */ static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, uint16_t message_id) { uint16_t netbytes; uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0); mg_send_mqtt_header(nc, cmd, flags, 2 /* len */); netbytes = htons(message_id); mg_send(nc, &netbytes, 2); } void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); } void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); } void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); } void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); } void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, uint16_t message_id) { size_t i; uint16_t netbytes; mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); netbytes = htons(message_id); mg_send(nc, &netbytes, 2); for (i = 0; i < qoss_len; i++) { mg_send(nc, &qoss[i], 1); } } void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); } void mg_mqtt_ping(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); } void mg_mqtt_pong(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); } void mg_mqtt_disconnect(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); } #endif /* MG_ENABLE_MQTT */
./CrossVul/dataset_final_sorted/CWE-119/c/good_896_1
crossvul-cpp_data_bad_5733_8
/* * Copyright (c) 2008 vmrsss * Copyright (c) 2009 Stefano Sabatini * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * video padding filter */ #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" #include "libavutil/avstring.h" #include "libavutil/common.h" #include "libavutil/eval.h" #include "libavutil/pixdesc.h" #include "libavutil/colorspace.h" #include "libavutil/avassert.h" #include "libavutil/imgutils.h" #include "libavutil/opt.h" #include "libavutil/parseutils.h" #include "libavutil/mathematics.h" #include "libavutil/opt.h" #include "drawutils.h" static const char *const var_names[] = { "in_w", "iw", "in_h", "ih", "out_w", "ow", "out_h", "oh", "x", "y", "a", "sar", "dar", "hsub", "vsub", NULL }; enum var_name { VAR_IN_W, VAR_IW, VAR_IN_H, VAR_IH, VAR_OUT_W, VAR_OW, VAR_OUT_H, VAR_OH, VAR_X, VAR_Y, VAR_A, VAR_SAR, VAR_DAR, VAR_HSUB, VAR_VSUB, VARS_NB }; static int query_formats(AVFilterContext *ctx) { ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0)); return 0; } typedef struct { const AVClass *class; int w, h; ///< output dimensions, a value of 0 will result in the input size int x, y; ///< offsets of the input area with respect to the padded area int in_w, in_h; ///< width and height for the padded input video, which has to be aligned to the chroma values in order to avoid chroma issues char *w_expr; ///< width expression string char *h_expr; ///< height expression string char *x_expr; ///< width expression string char *y_expr; ///< height expression string uint8_t rgba_color[4]; ///< color for the padding area FFDrawContext draw; FFDrawColor color; } PadContext; static int config_input(AVFilterLink *inlink) { AVFilterContext *ctx = inlink->dst; PadContext *s = ctx->priv; int ret; double var_values[VARS_NB], res; char *expr; ff_draw_init(&s->draw, inlink->format, 0); ff_draw_color(&s->draw, &s->color, s->rgba_color); var_values[VAR_IN_W] = var_values[VAR_IW] = inlink->w; var_values[VAR_IN_H] = var_values[VAR_IH] = inlink->h; var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN; var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN; var_values[VAR_A] = (double) inlink->w / inlink->h; var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1; var_values[VAR_DAR] = var_values[VAR_A] * var_values[VAR_SAR]; var_values[VAR_HSUB] = 1 << s->draw.hsub_max; var_values[VAR_VSUB] = 1 << s->draw.vsub_max; /* evaluate width and height */ av_expr_parse_and_eval(&res, (expr = s->w_expr), var_names, var_values, NULL, NULL, NULL, NULL, NULL, 0, ctx); s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res; if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr), var_names, var_values, NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto eval_fail; s->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res; /* evaluate the width again, as it may depend on the evaluated output height */ if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr), var_names, var_values, NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto eval_fail; s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res; /* evaluate x and y */ av_expr_parse_and_eval(&res, (expr = s->x_expr), var_names, var_values, NULL, NULL, NULL, NULL, NULL, 0, ctx); s->x = var_values[VAR_X] = res; if ((ret = av_expr_parse_and_eval(&res, (expr = s->y_expr), var_names, var_values, NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto eval_fail; s->y = var_values[VAR_Y] = res; /* evaluate x again, as it may depend on the evaluated y value */ if ((ret = av_expr_parse_and_eval(&res, (expr = s->x_expr), var_names, var_values, NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0) goto eval_fail; s->x = var_values[VAR_X] = res; /* sanity check params */ if (s->w < 0 || s->h < 0 || s->x < 0 || s->y < 0) { av_log(ctx, AV_LOG_ERROR, "Negative values are not acceptable.\n"); return AVERROR(EINVAL); } if (!s->w) s->w = inlink->w; if (!s->h) s->h = inlink->h; s->w = ff_draw_round_to_sub(&s->draw, 0, -1, s->w); s->h = ff_draw_round_to_sub(&s->draw, 1, -1, s->h); s->x = ff_draw_round_to_sub(&s->draw, 0, -1, s->x); s->y = ff_draw_round_to_sub(&s->draw, 1, -1, s->y); s->in_w = ff_draw_round_to_sub(&s->draw, 0, -1, inlink->w); s->in_h = ff_draw_round_to_sub(&s->draw, 1, -1, inlink->h); av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d x:%d y:%d color:0x%02X%02X%02X%02X\n", inlink->w, inlink->h, s->w, s->h, s->x, s->y, s->rgba_color[0], s->rgba_color[1], s->rgba_color[2], s->rgba_color[3]); if (s->x < 0 || s->y < 0 || s->w <= 0 || s->h <= 0 || (unsigned)s->x + (unsigned)inlink->w > s->w || (unsigned)s->y + (unsigned)inlink->h > s->h) { av_log(ctx, AV_LOG_ERROR, "Input area %d:%d:%d:%d not within the padded area 0:0:%d:%d or zero-sized\n", s->x, s->y, s->x + inlink->w, s->y + inlink->h, s->w, s->h); return AVERROR(EINVAL); } return 0; eval_fail: av_log(NULL, AV_LOG_ERROR, "Error when evaluating the expression '%s'\n", expr); return ret; } static int config_output(AVFilterLink *outlink) { PadContext *s = outlink->src->priv; outlink->w = s->w; outlink->h = s->h; return 0; } static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { PadContext *s = inlink->dst->priv; AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0], w + (s->w - s->in_w), h + (s->h - s->in_h)); int plane; if (!frame) return NULL; frame->width = w; frame->height = h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int hsub = s->draw.hsub[plane]; int vsub = s->draw.vsub[plane]; frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] + (s->y >> vsub) * frame->linesize[plane]; } return frame; } /* check whether each plane in this buffer can be padded without copying */ static int buffer_needs_copy(PadContext *s, AVFrame *frame, AVBufferRef *buf) { int planes[4] = { -1, -1, -1, -1}, *p = planes; int i, j; /* get all planes in this buffer */ for (i = 0; i < FF_ARRAY_ELEMS(planes) && frame->data[i]; i++) { if (av_frame_get_plane_buffer(frame, i) == buf) *p++ = i; } /* for each plane in this buffer, check that it can be padded without * going over buffer bounds or other planes */ for (i = 0; i < FF_ARRAY_ELEMS(planes) && planes[i] >= 0; i++) { int hsub = s->draw.hsub[planes[i]]; int vsub = s->draw.vsub[planes[i]]; uint8_t *start = frame->data[planes[i]]; uint8_t *end = start + (frame->height >> vsub) * frame->linesize[planes[i]]; /* amount of free space needed before the start and after the end * of the plane */ ptrdiff_t req_start = (s->x >> hsub) * s->draw.pixelstep[planes[i]] + (s->y >> vsub) * frame->linesize[planes[i]]; ptrdiff_t req_end = ((s->w - s->x - frame->width) >> hsub) * s->draw.pixelstep[planes[i]] + (s->y >> vsub) * frame->linesize[planes[i]]; if (frame->linesize[planes[i]] < (s->w >> hsub) * s->draw.pixelstep[planes[i]]) return 1; if (start - buf->data < req_start || (buf->data + buf->size) - end < req_end) return 1; for (j = 0; j < FF_ARRAY_ELEMS(planes) && planes[j] >= 0; j++) { int vsub1 = s->draw.vsub[planes[j]]; uint8_t *start1 = frame->data[planes[j]]; uint8_t *end1 = start1 + (frame->height >> vsub1) * frame->linesize[planes[j]]; if (i == j) continue; if (FFSIGN(start - end1) != FFSIGN(start - end1 - req_start) || FFSIGN(end - start1) != FFSIGN(end - start1 + req_end)) return 1; } } return 0; } static int frame_needs_copy(PadContext *s, AVFrame *frame) { int i; if (!av_frame_is_writable(frame)) return 1; for (i = 0; i < 4 && frame->buf[i]; i++) if (buffer_needs_copy(s, frame, frame->buf[i])) return 1; return 0; } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { PadContext *s = inlink->dst->priv; AVFrame *out; int needs_copy = frame_needs_copy(s, in); if (needs_copy) { av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n"); out = ff_get_video_buffer(inlink->dst->outputs[0], FFMAX(inlink->w, s->w), FFMAX(inlink->h, s->h)); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } else { int i; out = in; for (i = 0; i < 4 && out->data[i]; i++) { int hsub = s->draw.hsub[i]; int vsub = s->draw.vsub[i]; out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] + (s->y >> vsub) * out->linesize[i]; } } /* top bar */ if (s->y) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, 0, s->w, s->y); } /* bottom bar */ if (s->h > s->y + s->in_h) { ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y + s->in_h, s->w, s->h - s->y - s->in_h); } /* left border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, 0, s->y, s->x, in->height); if (needs_copy) { ff_copy_rectangle2(&s->draw, out->data, out->linesize, in->data, in->linesize, s->x, s->y, 0, 0, in->width, in->height); } /* right border */ ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize, s->x + s->in_w, s->y, s->w - s->x - s->in_w, in->height); out->width = s->w; out->height = s->h; if (in != out) av_frame_free(&in); return ff_filter_frame(inlink->dst->outputs[0], out); } #define OFFSET(x) offsetof(PadContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption pad_options[] = { { "width", "set the pad area width expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS }, { "w", "set the pad area width expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS }, { "height", "set the pad area height expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS }, { "h", "set the pad area height expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS }, { "x", "set the x offset expression for the input image position", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS }, { "y", "set the y offset expression for the input image position", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS }, { "color", "set the color of the padded area border", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str = "black"}, .flags = FLAGS }, { NULL }, }; AVFILTER_DEFINE_CLASS(pad); static const AVFilterPad avfilter_vf_pad_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_input, .get_video_buffer = get_video_buffer, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad avfilter_vf_pad_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_output, }, { NULL } }; AVFilter avfilter_vf_pad = { .name = "pad", .description = NULL_IF_CONFIG_SMALL("Pad input image to width:height[:x:y[:color]] (default x and y: 0, default color: black)."), .priv_size = sizeof(PadContext), .priv_class = &pad_class, .query_formats = query_formats, .inputs = avfilter_vf_pad_inputs, .outputs = avfilter_vf_pad_outputs, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5733_8
crossvul-cpp_data_good_2607_0
/* * Copyright (c) 1990 - 1994, Julianne Frances Haugh * Copyright (c) 1996 - 2001, Marek Michałkiewicz * Copyright (c) 2001 - 2006, Tomasz Kłoczko * Copyright (c) 2007 - 2011, Nicolas François * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the copyright holders or contributors may not be used to * endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #ident "$Id$" #include "defines.h" #include <assert.h> #include <sys/stat.h> #include <stdlib.h> #include <limits.h> #include <utime.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <signal.h> #include "nscd.h" #ifdef WITH_TCB #include <tcb.h> #endif /* WITH_TCB */ #include "prototypes.h" #include "commonio.h" /* local function prototypes */ static int lrename (const char *, const char *); static int check_link_count (const char *file); static int do_lock_file (const char *file, const char *lock, bool log); static /*@null@*/ /*@dependent@*/FILE *fopen_set_perms ( const char *name, const char *mode, const struct stat *sb); static int create_backup (const char *, FILE *); static void free_linked_list (struct commonio_db *); static void add_one_entry ( struct commonio_db *db, /*@owned@*/struct commonio_entry *p); static bool name_is_nis (const char *name); static int write_all (const struct commonio_db *); static /*@dependent@*/ /*@null@*/struct commonio_entry *find_entry_by_name ( struct commonio_db *, const char *); static /*@dependent@*/ /*@null@*/struct commonio_entry *next_entry_by_name ( struct commonio_db *, /*@null@*/struct commonio_entry *pos, const char *); static int lock_count = 0; static bool nscd_need_reload = false; /* * Simple rename(P) alternative that attempts to rename to symlink * target. */ int lrename (const char *old, const char *new) { int res; char *r = NULL; #if defined(S_ISLNK) #ifndef __GLIBC__ char resolved_path[PATH_MAX]; #endif /* !__GLIBC__ */ struct stat sb; if (lstat (new, &sb) == 0 && S_ISLNK (sb.st_mode)) { #ifdef __GLIBC__ /* now a POSIX.1-2008 feature */ r = realpath (new, NULL); #else /* !__GLIBC__ */ r = realpath (new, resolved_path); #endif /* !__GLIBC__ */ if (NULL == r) { perror ("realpath in lrename()"); } else { new = r; } } #endif /* S_ISLNK */ res = rename (old, new); #ifdef __GLIBC__ if (NULL != r) { free (r); } #endif /* __GLIBC__ */ return res; } static int check_link_count (const char *file) { struct stat sb; if (stat (file, &sb) != 0) { return 0; } if (sb.st_nlink != 2) { return 0; } return 1; } static int do_lock_file (const char *file, const char *lock, bool log) { int fd; pid_t pid; ssize_t len; int retval; char buf[32]; fd = open (file, O_CREAT | O_EXCL | O_WRONLY, 0600); if (-1 == fd) { if (log) { (void) fprintf (stderr, "%s: %s: %s\n", Prog, file, strerror (errno)); } return 0; } pid = getpid (); snprintf (buf, sizeof buf, "%lu", (unsigned long) pid); len = (ssize_t) strlen (buf) + 1; if (write (fd, buf, (size_t) len) != len) { if (log) { (void) fprintf (stderr, "%s: %s: %s\n", Prog, file, strerror (errno)); } (void) close (fd); unlink (file); return 0; } close (fd); if (link (file, lock) == 0) { retval = check_link_count (file); if ((0==retval) && log) { (void) fprintf (stderr, "%s: %s: lock file already used\n", Prog, file); } unlink (file); return retval; } fd = open (lock, O_RDWR); if (-1 == fd) { if (log) { (void) fprintf (stderr, "%s: %s: %s\n", Prog, lock, strerror (errno)); } unlink (file); errno = EINVAL; return 0; } len = read (fd, buf, sizeof (buf) - 1); close (fd); if (len <= 0) { if (log) { (void) fprintf (stderr, "%s: existing lock file %s without a PID\n", Prog, lock); } unlink (file); errno = EINVAL; return 0; } buf[len] = '\0'; if (get_pid (buf, &pid) == 0) { if (log) { (void) fprintf (stderr, "%s: existing lock file %s with an invalid PID '%s'\n", Prog, lock, buf); } unlink (file); errno = EINVAL; return 0; } if (kill (pid, 0) == 0) { if (log) { (void) fprintf (stderr, "%s: lock %s already used by PID %lu\n", Prog, lock, (unsigned long) pid); } unlink (file); errno = EEXIST; return 0; } if (unlink (lock) != 0) { if (log) { (void) fprintf (stderr, "%s: cannot get lock %s: %s\n", Prog, lock, strerror (errno)); } unlink (file); return 0; } retval = 0; if (link (file, lock) == 0) { retval = check_link_count (file); if ((0==retval) && log) { (void) fprintf (stderr, "%s: %s: lock file already used\n", Prog, file); } } else { if (log) { (void) fprintf (stderr, "%s: cannot get lock %s: %s\n", Prog, lock, strerror (errno)); } } unlink (file); return retval; } static /*@null@*/ /*@dependent@*/FILE *fopen_set_perms ( const char *name, const char *mode, const struct stat *sb) { FILE *fp; mode_t mask; mask = umask (0777); fp = fopen (name, mode); (void) umask (mask); if (NULL == fp) { return NULL; } #ifdef HAVE_FCHOWN if (fchown (fileno (fp), sb->st_uid, sb->st_gid) != 0) { goto fail; } #else /* !HAVE_FCHOWN */ if (chown (name, sb->st_mode) != 0) { goto fail; } #endif /* !HAVE_FCHOWN */ #ifdef HAVE_FCHMOD if (fchmod (fileno (fp), sb->st_mode & 0664) != 0) { goto fail; } #else /* !HAVE_FCHMOD */ if (chmod (name, sb->st_mode & 0664) != 0) { goto fail; } #endif /* !HAVE_FCHMOD */ return fp; fail: (void) fclose (fp); /* fopen_set_perms is used for intermediate files */ (void) unlink (name); return NULL; } static int create_backup (const char *backup, FILE * fp) { struct stat sb; struct utimbuf ub; FILE *bkfp; int c; if (fstat (fileno (fp), &sb) != 0) { return -1; } bkfp = fopen_set_perms (backup, "w", &sb); if (NULL == bkfp) { return -1; } /* TODO: faster copy, not one-char-at-a-time. --marekm */ c = 0; if (fseek (fp, 0, SEEK_SET) == 0) { while ((c = getc (fp)) != EOF) { if (putc (c, bkfp) == EOF) { break; } } } if ((c != EOF) || (ferror (fp) != 0) || (fflush (bkfp) != 0)) { (void) fclose (bkfp); /* FIXME: unlink the backup file? */ return -1; } if ( (fsync (fileno (bkfp)) != 0) || (fclose (bkfp) != 0)) { /* FIXME: unlink the backup file? */ return -1; } ub.actime = sb.st_atime; ub.modtime = sb.st_mtime; (void) utime (backup, &ub); return 0; } static void free_linked_list (struct commonio_db *db) { struct commonio_entry *p; while (NULL != db->head) { p = db->head; db->head = p->next; if (NULL != p->line) { free (p->line); } if (NULL != p->eptr) { db->ops->free (p->eptr); } free (p); } db->tail = NULL; } int commonio_setname (struct commonio_db *db, const char *name) { snprintf (db->filename, sizeof (db->filename), "%s", name); return 1; } bool commonio_present (const struct commonio_db *db) { return (access (db->filename, F_OK) == 0); } int commonio_lock_nowait (struct commonio_db *db, bool log) { char file[1024]; char lock[1024]; if (db->locked) { return 1; } snprintf (file, sizeof file, "%s.%lu", db->filename, (unsigned long) getpid ()); snprintf (lock, sizeof lock, "%s.lock", db->filename); if (do_lock_file (file, lock, log) != 0) { db->locked = true; lock_count++; return 1; } return 0; } int commonio_lock (struct commonio_db *db) { #ifdef HAVE_LCKPWDF /* * only if the system libc has a real lckpwdf() - the one from * lockpw.c calls us and would cause infinite recursion! */ /* * Call lckpwdf() on the first lock. * If it succeeds, call *_lock() only once * (no retries, it should always succeed). */ if (0 == lock_count) { if (lckpwdf () == -1) { if (geteuid () != 0) { (void) fprintf (stderr, "%s: Permission denied.\n", Prog); } return 0; /* failure */ } } if (commonio_lock_nowait (db, true) != 0) { return 1; /* success */ } ulckpwdf (); return 0; /* failure */ #else /* !HAVE_LCKPWDF */ int i; /* * lckpwdf() not used - do it the old way. */ #ifndef LOCK_TRIES #define LOCK_TRIES 15 #endif #ifndef LOCK_SLEEP #define LOCK_SLEEP 1 #endif for (i = 0; i < LOCK_TRIES; i++) { if (i > 0) { sleep (LOCK_SLEEP); /* delay between retries */ } if (commonio_lock_nowait (db, i==LOCK_TRIES-1) != 0) { return 1; /* success */ } /* no unnecessary retries on "permission denied" errors */ if (geteuid () != 0) { (void) fprintf (stderr, "%s: Permission denied.\n", Prog); return 0; } } return 0; /* failure */ #endif /* !HAVE_LCKPWDF */ } static void dec_lock_count (void) { if (lock_count > 0) { lock_count--; if (lock_count == 0) { /* Tell nscd when lock count goes to zero, if any of the files were changed. */ if (nscd_need_reload) { nscd_flush_cache ("passwd"); nscd_flush_cache ("group"); nscd_need_reload = false; } #ifdef HAVE_LCKPWDF ulckpwdf (); #endif /* HAVE_LCKPWDF */ } } } int commonio_unlock (struct commonio_db *db) { char lock[1024]; if (db->isopen) { db->readonly = true; if (commonio_close (db) == 0) { if (db->locked) { dec_lock_count (); } return 0; } } if (db->locked) { /* * Unlock in reverse order: remove the lock file, * then call ulckpwdf() (if used) on last unlock. */ db->locked = false; snprintf (lock, sizeof lock, "%s.lock", db->filename); unlink (lock); dec_lock_count (); return 1; } return 0; } /* * Add an entry at the end. * * defines p->next, p->prev * (unfortunately, owned special are not supported) */ static void add_one_entry (struct commonio_db *db, /*@owned@*/struct commonio_entry *p) { /*@-mustfreeonly@*/ p->next = NULL; p->prev = db->tail; /*@=mustfreeonly@*/ if (NULL == db->head) { db->head = p; } if (NULL != db->tail) { db->tail->next = p; } db->tail = p; } static bool name_is_nis (const char *name) { return (('+' == name[0]) || ('-' == name[0])); } /* * New entries are inserted before the first NIS entry. Order is preserved * when db is written out. */ #ifndef KEEP_NIS_AT_END #define KEEP_NIS_AT_END 1 #endif #if KEEP_NIS_AT_END static void add_one_entry_nis (struct commonio_db *db, /*@owned@*/struct commonio_entry *newp); /* * Insert an entry between the regular entries, and the NIS entries. * * defines newp->next, newp->prev * (unfortunately, owned special are not supported) */ static void add_one_entry_nis (struct commonio_db *db, /*@owned@*/struct commonio_entry *newp) { struct commonio_entry *p; for (p = db->head; NULL != p; p = p->next) { if (name_is_nis (p->eptr ? db->ops->getname (p->eptr) : p->line)) { /*@-mustfreeonly@*/ newp->next = p; newp->prev = p->prev; /*@=mustfreeonly@*/ if (NULL != p->prev) { p->prev->next = newp; } else { db->head = newp; } p->prev = newp; return; } } add_one_entry (db, newp); } #endif /* KEEP_NIS_AT_END */ /* Initial buffer size, as well as increment if not sufficient (for reading very long lines in group files). */ #define BUFLEN 4096 int commonio_open (struct commonio_db *db, int mode) { char *buf; char *cp; char *line; struct commonio_entry *p; void *eptr = NULL; int flags = mode; size_t buflen; int fd; int saved_errno; mode &= ~O_CREAT; if ( db->isopen || ( (O_RDONLY != mode) && (O_RDWR != mode))) { errno = EINVAL; return 0; } db->readonly = (mode == O_RDONLY); if (!db->readonly && !db->locked) { errno = EACCES; return 0; } db->head = NULL; db->tail = NULL; db->cursor = NULL; db->changed = false; fd = open (db->filename, (db->readonly ? O_RDONLY : O_RDWR) | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW); saved_errno = errno; db->fp = NULL; if (fd >= 0) { #ifdef WITH_TCB if (tcb_is_suspect (fd) != 0) { (void) close (fd); errno = EINVAL; return 0; } #endif /* WITH_TCB */ db->fp = fdopen (fd, db->readonly ? "r" : "r+"); saved_errno = errno; if (NULL == db->fp) { (void) close (fd); } } errno = saved_errno; /* * If O_CREAT was specified and the file didn't exist, it will be * created by commonio_close(). We have no entries to read yet. --marekm */ if (NULL == db->fp) { if (((flags & O_CREAT) != 0) && (ENOENT == errno)) { db->isopen = true; return 1; } return 0; } /* Do not inherit fd in spawned processes (e.g. nscd) */ fcntl (fileno (db->fp), F_SETFD, FD_CLOEXEC); buflen = BUFLEN; buf = (char *) malloc (buflen); if (NULL == buf) { goto cleanup_ENOMEM; } while (db->ops->fgets (buf, (int) buflen, db->fp) == buf) { while ( ((cp = strrchr (buf, '\n')) == NULL) && (feof (db->fp) == 0)) { size_t len; buflen += BUFLEN; cp = (char *) realloc (buf, buflen); if (NULL == cp) { goto cleanup_buf; } buf = cp; len = strlen (buf); if (db->ops->fgets (buf + len, (int) (buflen - len), db->fp) == NULL) { goto cleanup_buf; } } cp = strrchr (buf, '\n'); if (NULL != cp) { *cp = '\0'; } line = strdup (buf); if (NULL == line) { goto cleanup_buf; } if (name_is_nis (line)) { eptr = NULL; } else { eptr = db->ops->parse (line); if (NULL != eptr) { eptr = db->ops->dup (eptr); if (NULL == eptr) { goto cleanup_line; } } } p = (struct commonio_entry *) malloc (sizeof *p); if (NULL == p) { goto cleanup_entry; } p->eptr = eptr; p->line = line; p->changed = false; add_one_entry (db, p); } free (buf); if (ferror (db->fp) != 0) { goto cleanup_errno; } if ((NULL != db->ops->open_hook) && (db->ops->open_hook () == 0)) { goto cleanup_errno; } db->isopen = true; return 1; cleanup_entry: if (NULL != eptr) { db->ops->free (eptr); } cleanup_line: free (line); cleanup_buf: free (buf); cleanup_ENOMEM: errno = ENOMEM; cleanup_errno: saved_errno = errno; free_linked_list (db); fclose (db->fp); db->fp = NULL; errno = saved_errno; return 0; } /* * Sort given db according to cmp function (usually compares uids) */ int commonio_sort (struct commonio_db *db, int (*cmp) (const void *, const void *)) { struct commonio_entry **entries, *ptr; size_t n = 0, i; #if KEEP_NIS_AT_END struct commonio_entry *nis = NULL; #endif for (ptr = db->head; (NULL != ptr) #if KEEP_NIS_AT_END && ((NULL == ptr->line) || (('+' != ptr->line[0]) && ('-' != ptr->line[0]))) #endif ; ptr = ptr->next) { n++; } #if KEEP_NIS_AT_END if (NULL != ptr) { nis = ptr; } #endif if (n <= 1) { return 0; } entries = malloc (n * sizeof (struct commonio_entry *)); if (entries == NULL) { return -1; } n = 0; for (ptr = db->head; #if KEEP_NIS_AT_END nis != ptr; #else NULL != ptr; #endif /*@ -nullderef @*/ ptr = ptr->next /*@ +nullderef @*/ ) { entries[n] = ptr; n++; } qsort (entries, n, sizeof (struct commonio_entry *), cmp); /* Take care of the head and tail separately */ db->head = entries[0]; n--; #if KEEP_NIS_AT_END if (NULL == nis) #endif { db->tail = entries[n]; } db->head->prev = NULL; db->head->next = entries[1]; entries[n]->prev = entries[n - 1]; #if KEEP_NIS_AT_END entries[n]->next = nis; #else entries[n]->next = NULL; #endif /* Now other elements have prev and next entries */ for (i = 1; i < n; i++) { entries[i]->prev = entries[i - 1]; entries[i]->next = entries[i + 1]; } free (entries); db->changed = true; return 0; } /* * Sort entries in db according to order in another. */ int commonio_sort_wrt (struct commonio_db *shadow, const struct commonio_db *passwd) { struct commonio_entry *head = NULL, *pw_ptr, *spw_ptr; const char *name; if ((NULL == shadow) || (NULL == shadow->head)) { return 0; } for (pw_ptr = passwd->head; NULL != pw_ptr; pw_ptr = pw_ptr->next) { if (NULL == pw_ptr->eptr) { continue; } name = passwd->ops->getname (pw_ptr->eptr); for (spw_ptr = shadow->head; NULL != spw_ptr; spw_ptr = spw_ptr->next) { if (NULL == spw_ptr->eptr) { continue; } if (strcmp (name, shadow->ops->getname (spw_ptr->eptr)) == 0) { break; } } if (NULL == spw_ptr) { continue; } commonio_del_entry (shadow, spw_ptr); spw_ptr->next = head; head = spw_ptr; } for (spw_ptr = head; NULL != spw_ptr; spw_ptr = head) { head = head->next; if (NULL != shadow->head) { shadow->head->prev = spw_ptr; } spw_ptr->next = shadow->head; shadow->head = spw_ptr; } shadow->head->prev = NULL; shadow->changed = true; return 0; } /* * write_all - Write the database to its file. * * It returns 0 if all the entries could be written correctly. */ static int write_all (const struct commonio_db *db) /*@requires notnull db->fp@*/ { const struct commonio_entry *p; void *eptr; for (p = db->head; NULL != p; p = p->next) { if (p->changed) { eptr = p->eptr; assert (NULL != eptr); if (db->ops->put (eptr, db->fp) != 0) { return -1; } } else if (NULL != p->line) { if (db->ops->fputs (p->line, db->fp) == EOF) { return -1; } if (putc ('\n', db->fp) == EOF) { return -1; } } } return 0; } int commonio_close (struct commonio_db *db) /*@requires notnull db->fp@*/ { char buf[1024]; int errors = 0; struct stat sb; if (!db->isopen) { errno = EINVAL; return 0; } db->isopen = false; if (!db->changed || db->readonly) { (void) fclose (db->fp); db->fp = NULL; goto success; } if ((NULL != db->ops->close_hook) && (db->ops->close_hook () == 0)) { goto fail; } memzero (&sb, sizeof sb); if (NULL != db->fp) { if (fstat (fileno (db->fp), &sb) != 0) { (void) fclose (db->fp); db->fp = NULL; goto fail; } /* * Create backup file. */ snprintf (buf, sizeof buf, "%s-", db->filename); #ifdef WITH_SELINUX if (set_selinux_file_context (buf) != 0) { errors++; } #endif if (create_backup (buf, db->fp) != 0) { errors++; } if (fclose (db->fp) != 0) { errors++; } #ifdef WITH_SELINUX if (reset_selinux_file_context () != 0) { errors++; } #endif if (errors != 0) { db->fp = NULL; goto fail; } } else { /* * Default permissions for new [g]shadow files. */ sb.st_mode = db->st_mode; sb.st_uid = db->st_uid; sb.st_gid = db->st_gid; } snprintf (buf, sizeof buf, "%s+", db->filename); #ifdef WITH_SELINUX if (set_selinux_file_context (buf) != 0) { errors++; } #endif db->fp = fopen_set_perms (buf, "w", &sb); if (NULL == db->fp) { goto fail; } if (write_all (db) != 0) { errors++; } if (fflush (db->fp) != 0) { errors++; } #ifdef HAVE_FSYNC if (fsync (fileno (db->fp)) != 0) { errors++; } #else /* !HAVE_FSYNC */ sync (); #endif /* !HAVE_FSYNC */ if (fclose (db->fp) != 0) { errors++; } db->fp = NULL; if (errors != 0) { unlink (buf); goto fail; } if (lrename (buf, db->filename) != 0) { goto fail; } #ifdef WITH_SELINUX if (reset_selinux_file_context () != 0) { goto fail; } #endif nscd_need_reload = true; goto success; fail: errors++; success: free_linked_list (db); return errors == 0; } static /*@dependent@*/ /*@null@*/struct commonio_entry *next_entry_by_name ( struct commonio_db *db, /*@null@*/struct commonio_entry *pos, const char *name) { struct commonio_entry *p; void *ep; if (NULL == pos) { return NULL; } for (p = pos; NULL != p; p = p->next) { ep = p->eptr; if ( (NULL != ep) && (strcmp (db->ops->getname (ep), name) == 0)) { break; } } return p; } static /*@dependent@*/ /*@null@*/struct commonio_entry *find_entry_by_name ( struct commonio_db *db, const char *name) { return next_entry_by_name (db, db->head, name); } int commonio_update (struct commonio_db *db, const void *eptr) { struct commonio_entry *p; void *nentry; if (!db->isopen || db->readonly) { errno = EINVAL; return 0; } nentry = db->ops->dup (eptr); if (NULL == nentry) { errno = ENOMEM; return 0; } p = find_entry_by_name (db, db->ops->getname (eptr)); if (NULL != p) { if (next_entry_by_name (db, p->next, db->ops->getname (eptr)) != NULL) { fprintf (stderr, _("Multiple entries named '%s' in %s. Please fix this with pwck or grpck.\n"), db->ops->getname (eptr), db->filename); db->ops->free (nentry); return 0; } db->ops->free (p->eptr); p->eptr = nentry; p->changed = true; db->cursor = p; db->changed = true; return 1; } /* not found, new entry */ p = (struct commonio_entry *) malloc (sizeof *p); if (NULL == p) { db->ops->free (nentry); errno = ENOMEM; return 0; } p->eptr = nentry; p->line = NULL; p->changed = true; #if KEEP_NIS_AT_END add_one_entry_nis (db, p); #else /* !KEEP_NIS_AT_END */ add_one_entry (db, p); #endif /* !KEEP_NIS_AT_END */ db->changed = true; return 1; } #ifdef ENABLE_SUBIDS int commonio_append (struct commonio_db *db, const void *eptr) { struct commonio_entry *p; void *nentry; if (!db->isopen || db->readonly) { errno = EINVAL; return 0; } nentry = db->ops->dup (eptr); if (NULL == nentry) { errno = ENOMEM; return 0; } /* new entry */ p = (struct commonio_entry *) malloc (sizeof *p); if (NULL == p) { db->ops->free (nentry); errno = ENOMEM; return 0; } p->eptr = nentry; p->line = NULL; p->changed = true; add_one_entry (db, p); db->changed = true; return 1; } #endif /* ENABLE_SUBIDS */ void commonio_del_entry (struct commonio_db *db, const struct commonio_entry *p) { if (p == db->cursor) { db->cursor = p->next; } if (NULL != p->prev) { p->prev->next = p->next; } else { db->head = p->next; } if (NULL != p->next) { p->next->prev = p->prev; } else { db->tail = p->prev; } db->changed = true; } /* * commonio_remove - Remove the entry of the given name from the database. */ int commonio_remove (struct commonio_db *db, const char *name) { struct commonio_entry *p; if (!db->isopen || db->readonly) { errno = EINVAL; return 0; } p = find_entry_by_name (db, name); if (NULL == p) { errno = ENOENT; return 0; } if (next_entry_by_name (db, p->next, name) != NULL) { fprintf (stderr, _("Multiple entries named '%s' in %s. Please fix this with pwck or grpck.\n"), name, db->filename); return 0; } commonio_del_entry (db, p); if (NULL != p->line) { free (p->line); } if (NULL != p->eptr) { db->ops->free (p->eptr); } return 1; } /* * commonio_locate - Find the first entry with the specified name in * the database. * * If found, it returns the entry and set the cursor of the database to * that entry. * * Otherwise, it returns NULL. */ /*@observer@*/ /*@null@*/const void *commonio_locate (struct commonio_db *db, const char *name) { struct commonio_entry *p; if (!db->isopen) { errno = EINVAL; return NULL; } p = find_entry_by_name (db, name); if (NULL == p) { errno = ENOENT; return NULL; } db->cursor = p; return p->eptr; } /* * commonio_rewind - Restore the database cursor to the first entry. * * It returns 0 on error, 1 on success. */ int commonio_rewind (struct commonio_db *db) { if (!db->isopen) { errno = EINVAL; return 0; } db->cursor = NULL; return 1; } /* * commonio_next - Return the next entry of the specified database * * It returns the next entry, or NULL if no other entries could be found. */ /*@observer@*/ /*@null@*/const void *commonio_next (struct commonio_db *db) { void *eptr; if (!db->isopen) { errno = EINVAL; return 0; } if (NULL == db->cursor) { db->cursor = db->head; } else { db->cursor = db->cursor->next; } while (NULL != db->cursor) { eptr = db->cursor->eptr; if (NULL != eptr) { return eptr; } db->cursor = db->cursor->next; } return NULL; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_2607_0
crossvul-cpp_data_good_4863_2
#include "queue.ih" void queue_push(register Queue *qp, size_t extra_length, char const *info) { register char *cp; size_t memory_length; size_t available_length; size_t begin_length; size_t n_begin; size_t q_length; if (!extra_length) return; memory_length = qp->d_memory_end - qp->d_memory; q_length = qp->d_read <= qp->d_write ? (size_t)(qp->d_write - qp->d_read) : memory_length - (qp->d_read - qp->d_write); available_length = memory_length - q_length - 1; /* -1, as the Q cannot completely fill up all */ /* available memory in the buffer */ if (message_show(MSG_INFO)) message("push_front %u bytes in `%s'", (unsigned)extra_length, info); if (extra_length > available_length) { size_t original_length = memory_length; /* enlarge the buffer: */ memory_length += extra_length - available_length + BLOCK_QUEUE; cp = new_memory(memory_length, sizeof(char)); if (message_show(MSG_INFO)) message("Reallocating queue at %p to %p", qp->d_memory, cp); if (qp->d_read > qp->d_write) /* q wraps around end */ { size_t tail_len = qp->d_memory_end - qp->d_read; memcpy(cp, qp->d_read, tail_len); /* first part -> begin */ /* 2nd part beyond */ memcpy(cp + tail_len, qp->d_memory, (size_t)(qp->d_write - qp->d_memory)); qp->d_write = cp + q_length; qp->d_read = cp; } else /* q as one block */ { memcpy(cp, qp->d_memory, original_length);/* cp existing buffer */ qp->d_read = cp + (qp->d_read - qp->d_memory); qp->d_write = cp + (qp->d_write - qp->d_memory); } free(qp->d_memory); /* free old memory */ qp->d_memory_end = cp + memory_length; /* update d_memory_end */ qp->d_memory = cp; /* update d_memory */ } /* Write as much as possible at the begin of the buffer, then write the remaining chars at the end. q_length is increased by the length of the info string The first chars to write are at the end of info, and the 2nd part to write are the initial chars of info, since the initial part of info is then read first. */ /* # chars available at the */ begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */ n_begin = extra_length <= begin_length ? /* determine # to write at */ extra_length /* the begin of the buffer */ : begin_length; memcpy /* write trailing part of */ ( /* info first */ qp->d_read -= n_begin, info + extra_length - n_begin, n_begin ); if (extra_length > begin_length) /* not yet all chars written*/ { /* continue with the remaining number of characters. Insert these at*/ /* the end of the buffer */ extra_length -= begin_length; /* reduce # to write */ memcpy /* d_read wraps to the end */ ( /* write info's rest */ qp->d_read = qp->d_memory_end - extra_length, info, extra_length ); } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_4863_2
crossvul-cpp_data_bad_5096_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /* ----------------------------------------------------------------------- */ /* TODO MSD: */ #ifdef TODO_MSD void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) { int tileno, compno, resno, bandno, precno;/*, cblkno;*/ fprintf(fd, "image {\n"); fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n", img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0, tcd->image->y1); for (tileno = 0; tileno < img->th * img->tw; tileno++) { opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno]; fprintf(fd, " tile {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n", tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps); for (compno = 0; compno < tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; fprintf(fd, " tilec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n", tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions); for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; fprintf(fd, "\n res {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n", res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands); for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; fprintf(fd, " band {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n", band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps); for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prec = &band->precincts[precno]; fprintf(fd, " prec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n", prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch); /* for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) { opj_tcd_cblk_t *cblk = &prec->cblks[cblkno]; fprintf(fd, " cblk {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d\n", cblk->x0, cblk->y0, cblk->x1, cblk->y1); fprintf(fd, " }\n"); } */ fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, "}\n"); } #endif /** * Initializes tile coding/decoding */ 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_event_mgr_t* manager); /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block); /** * Deallocates the decoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct); /** * Allocates memory for an encoding code block (but not data). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block); /** * Allocates data for an encoding code block */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block); /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct); /** Free the memory allocated for encoding @param tcd TCD handle */ static void opj_tcd_free_tile(opj_tcd_t *tcd); static OPJ_BOOL opj_tcd_t2_decode ( opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_t1_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dwt_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_mct_decode (opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_dc_level_shift_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_t2_encode ( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ); static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ); /* ----------------------------------------------------------------------- */ /** Create a new TCD handle */ opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder) { opj_tcd_t *l_tcd = 00; /* create the tcd structure */ l_tcd = (opj_tcd_t*) opj_calloc(1,sizeof(opj_tcd_t)); if (!l_tcd) { return 00; } l_tcd->m_is_decoder = p_is_decoder ? 1 : 0; l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1,sizeof(opj_tcd_image_t)); if (!l_tcd->tcd_image) { opj_free(l_tcd); return 00; } return l_tcd; } /* ----------------------------------------------------------------------- */ void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd) { OPJ_UINT32 layno; for (layno = 0; layno < tcd->tcp->numlayers; layno++) { opj_tcd_makelayer_fixed(tcd, layno, 1); } } void opj_tcd_makelayer( opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_FLOAT64 thresh, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_UINT32 passno; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; tcd_tile->distolayer[layno] = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) { OPJ_UINT32 dr; OPJ_FLOAT64 dd; opj_tcd_pass_t *pass = &cblk->passes[passno]; if (n == 0) { dr = pass->rate; dd = pass->distortiondec; } else { dr = pass->rate - cblk->passes[n - 1].rate; dd = pass->distortiondec - cblk->passes[n - 1].distortiondec; } if (!dr) { if (dd != 0) n = passno + 1; continue; } if (thresh - (dd / dr) < DBL_EPSILON) /* do not rely on float equality, check with DBL_EPSILON margin */ n = passno + 1; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) { layer->disto = 0; continue; } if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; layer->disto = cblk->passes[n - 1].distortiondec; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec; } tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */ if (final) cblk->numpassesinlayers = n; } } } } } } void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */ OPJ_INT32 matrice[10][10][3]; OPJ_UINT32 i, j, k; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (i = 0; i < tcd_tcp->numlayers; i++) { for (j = 0; j < tilec->numresolutions; j++) { for (k = 0; k < 3; k++) { matrice[i][j][k] = (OPJ_INT32) ((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i * tilec->numresolutions * 3 + j * 3 + k] * (OPJ_FLOAT32) (tcd->image->comps[compno].prec / 16.0)); } } } for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec - cblk->numbps); /* number of bit-plan equal to zero */ /* Correction of the matrix of coefficient to include the IMSB information */ if (layno == 0) { value = matrice[layno][resno][bandno]; if (imsb >= value) { value = 0; } else { value -= imsb; } } else { value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno]; if (imsb >= matrice[layno - 1][resno][bandno]) { value -= (imsb - matrice[layno - 1][resno][bandno]); if (value < 0) { value = 0; } } } if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; if (cblk->numpassesinlayers == 0) { if (value != 0) { n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers; } else { n = cblk->numpassesinlayers; } } else { n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) continue; if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; } if (final) cblk->numpassesinlayers = n; } } } } } } OPJ_BOOL opj_tcd_rateallocate( opj_tcd_t *tcd, OPJ_BYTE *dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 len, opj_codestream_info_t *cstr_info) { OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno; OPJ_UINT32 passno; OPJ_FLOAT64 min, max; OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */ const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */ OPJ_FLOAT64 maxSE = 0; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; min = DBL_MAX; max = 0; tcd_tile->numpix = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; tilec->numpix = 0; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; for (passno = 0; passno < cblk->totalpasses; passno++) { opj_tcd_pass_t *pass = &cblk->passes[passno]; OPJ_INT32 dr; OPJ_FLOAT64 dd, rdslope; if (passno == 0) { dr = (OPJ_INT32)pass->rate; dd = pass->distortiondec; } else { dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate); dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec; } if (dr == 0) { continue; } rdslope = dd / dr; if (rdslope < min) { min = rdslope; } if (rdslope > max) { max = rdslope; } } /* passno */ /* fixed_quality */ tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); } /* cbklno */ } /* precno */ } /* bandno */ } /* resno */ maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0) * ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) -1.0)) * ((OPJ_FLOAT64)(tilec->numpix)); } /* compno */ /* index file */ if(cstr_info) { opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno]; tile_info->numpix = tcd_tile->numpix; tile_info->distotile = tcd_tile->distotile; tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(OPJ_FLOAT64)); if (!tile_info->thresh) { /* FIXME event manager error callback */ return OPJ_FALSE; } } for (layno = 0; layno < tcd_tcp->numlayers; layno++) { OPJ_FLOAT64 lo = min; OPJ_FLOAT64 hi = max; OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min(((OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len; OPJ_FLOAT64 goodthresh = 0; OPJ_FLOAT64 stable_thresh = 0; OPJ_UINT32 i; OPJ_FLOAT64 distotarget; /* fixed_quality */ /* fixed_quality */ distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10, tcd_tcp->distoratio[layno] / 10)); /* Don't try to find an optimal threshold but rather take everything not included yet, if -r xx,yy,zz,0 (disto_alloc == 1 and rates == 0) -q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0) ==> possible to have some lossy layers and the last layer for sure lossless */ if ( ((cp->m_specific_param.m_enc.m_disto_alloc==1) && (tcd_tcp->rates[layno]>0.0f)) || ((cp->m_specific_param.m_enc.m_fixed_quality==1) && (tcd_tcp->distoratio[layno]>0.0))) { opj_t2_t*t2 = opj_t2_create(tcd->image, cp); OPJ_FLOAT64 thresh = 0; if (t2 == 00) { return OPJ_FALSE; } for (i = 0; i < 128; ++i) { OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */ thresh = (lo + hi) / 2; opj_tcd_makelayer(tcd, layno, thresh, 0); if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ if(OPJ_IS_CINEMA(cp->rsiz)){ if (! opj_t2_encode_packets(t2,tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) { lo = thresh; continue; } else { distoachieved = layno == 0 ? tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno]; if (distoachieved < distotarget) { hi=thresh; stable_thresh = thresh; continue; }else{ lo=thresh; } } }else{ distoachieved = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); if (distoachieved < distotarget) { hi = thresh; stable_thresh = thresh; continue; } lo = thresh; } } else { if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) { /* TODO: what to do with l ??? seek / tell ??? */ /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */ lo = thresh; continue; } hi = thresh; stable_thresh = thresh; } } goodthresh = stable_thresh == 0? thresh : stable_thresh; opj_t2_destroy(t2); } else { goodthresh = min; } if(cstr_info) { /* Threshold for Marcela Index */ cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh; } opj_tcd_makelayer(tcd, layno, goodthresh, 1); /* fixed_quality */ cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_init( opj_tcd_t *p_tcd, opj_image_t * p_image, opj_cp_t * p_cp ) { p_tcd->image = p_image; p_tcd->cp = p_cp; p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,sizeof(opj_tcd_tile_t)); if (! p_tcd->tcd_image->tiles) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(p_image->numcomps,sizeof(opj_tcd_tilecomp_t)); if (! p_tcd->tcd_image->tiles->comps ) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->numcomps = p_image->numcomps; p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos; return OPJ_TRUE; } /** Destroy a previously created TCD handle */ void opj_tcd_destroy(opj_tcd_t *tcd) { if (tcd) { opj_tcd_free_tile(tcd); if (tcd->tcd_image) { opj_free(tcd->tcd_image); tcd->tcd_image = 00; } opj_free(tcd); } } OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec) { if ((l_tilec->data == 00) || ((l_tilec->data_size_needed > l_tilec->data_size) && (l_tilec->ownsData == OPJ_FALSE))) { l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed); if (! l_tilec->data ) { return OPJ_FALSE; } /*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } else if (l_tilec->data_size_needed > l_tilec->data_size) { /* We don't need to keep old data */ opj_aligned_free(l_tilec->data); l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed); if (! l_tilec->data ) { l_tilec->data_size = 0; l_tilec->data_size_needed = 0; l_tilec->ownsData = OPJ_FALSE; return OPJ_FALSE; } /*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ 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_event_mgr_t* manager) { 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; OPJ_UINT32 l_tx0, l_ty0; /* 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_tx0 = l_cp->tx0 + p * l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */ l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0); l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx), l_image->x1); l_ty0 = l_cp->ty0 + q * l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */ l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0); l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy), l_image->y1); /* testcase 1888.pdf.asan.35.988 */ if (l_tccp->numresolutions == 0) { opj_event_msg(manager, EVT_ERROR, "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); /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */ if ((l_data_size > 0U) && ((((OPJ_UINT32)-1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0))) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); 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) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); 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)) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); 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(manager, EVT_ERROR, "Not enough memory for 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; 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; --l_level_no; /* 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) ? 0U : (OPJ_UINT32)((l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx); l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (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 );*/ if ((l_res->pw != 0U) && ((((OPJ_UINT32)-1) / l_res->pw) < l_res->ph)) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } l_nb_precincts = l_res->pw * l_res->ph; if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) < l_nb_precincts) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } 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_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b << l_level_no), (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_nb_precincts > 0U)) { l_band->precincts = (opj_tcd_precinct_t *) opj_malloc( /*3 * */ l_nb_precinct_size); if (! l_band->precincts) { opj_event_msg(manager, EVT_ERROR, "Not enough memory to handle band precints\n"); 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(manager, EVT_ERROR, "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_nb_code_blocks > 0U)) { 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(manager, EVT_ERROR, "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, manager); } else{ l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch, manager); } if (! l_current_precinct->incltree) { opj_event_msg(manager, EVT_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, manager); } else { l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch, manager); } if (! l_current_precinct->imsbtree) { opj_event_msg(manager, EVT_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; } /* resno */ ++l_tccp; ++l_tilec; ++l_image_comp; } /* compno */ return OPJ_TRUE; } OPJ_BOOL opj_tcd_init_encode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F, sizeof(opj_tcd_cblk_enc_t), p_manager); } OPJ_BOOL opj_tcd_init_decode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F, sizeof(opj_tcd_cblk_dec_t), p_manager); } /** * Allocates memory for an encoding code block (but not data memory). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block) { if (! p_code_block->layers) { /* no memset since data */ p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t)); if (! p_code_block->layers) { return OPJ_FALSE; } } if (! p_code_block->passes) { p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t)); if (! p_code_block->passes) { return OPJ_FALSE; } } return OPJ_TRUE; } /** * Allocates data memory for an encoding code block. */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { opj_free(p_code_block->data - 1); /* again, why -1 */ } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size+1); if(! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; p_code_block->data[0] = 0; p_code_block->data+=1; /*why +1 ?*/ } return OPJ_TRUE; } /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block) { if (! p_code_block->data) { p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE); if (! p_code_block->data) { return OPJ_FALSE; } p_code_block->data_max_size = OPJ_J2K_DEFAULT_CBLK_DATA_SIZE; /*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/ p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,sizeof(opj_tcd_seg_t)); if (! p_code_block->segs) { return OPJ_FALSE; } /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/ p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS; /*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/ } else { /* sanitize */ OPJ_BYTE* l_data = p_code_block->data; OPJ_UINT32 l_data_max_size = p_code_block->data_max_size; opj_tcd_seg_t * l_segs = p_code_block->segs; OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs; memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t)); p_code_block->data = l_data; p_code_block->data_max_size = l_data_max_size; p_code_block->segs = l_segs; p_code_block->m_current_max_segs = l_current_max_segs; } return OPJ_TRUE; } OPJ_UINT32 opj_tcd_get_decoded_tile_size ( opj_tcd_t *p_tcd ) { OPJ_UINT32 i; OPJ_UINT32 l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tcd_resolution_t * l_res = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tile_comp = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if(l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1; l_data_size += l_size_comp * (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 - l_res->y0)); ++l_img_comp; ++l_tile_comp; } return l_data_size; } OPJ_BOOL opj_tcd_encode_tile( opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BYTE *p_dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_length, opj_codestream_info_t *p_cstr_info) { if (p_tcd->cur_tp_num == 0) { p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no]; /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */ if(p_cstr_info) { OPJ_UINT32 l_num_packs = 0; OPJ_UINT32 i; opj_tcd_tilecomp_t *l_tilec_idx = &p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */ opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */ for (i = 0; i < l_tilec_idx->numresolutions; i++) { opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i]; p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw; p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph; l_num_packs += l_res_idx->pw * l_res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i]; p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i]; } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs, sizeof(opj_packet_info_t)); if (!p_cstr_info->tile[p_tile_no].packet) { /* FIXME event manager error callback */ return OPJ_FALSE; } } /* << INDEX */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ if (! opj_tcd_dc_level_shift_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /* FIXME _ProfStart(PGROUP_RATE); */ if (! opj_tcd_rate_allocate_encode(p_tcd,p_dest,p_max_length,p_cstr_info)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_RATE); */ } /*--------------TIER2------------------*/ /* INDEX */ if (p_cstr_info) { p_cstr_info->index_write = 1; } /* FIXME _ProfStart(PGROUP_T2); */ if (! opj_tcd_t2_encode(p_tcd,p_dest,p_data_written,p_max_length,p_cstr_info)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*---------------CLEAN-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_decode_tile( opj_tcd_t *p_tcd, OPJ_BYTE *p_src, OPJ_UINT32 p_max_length, OPJ_UINT32 p_tile_no, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager ) { OPJ_UINT32 l_data_read; p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]); #ifdef TODO_MSD /* FIXME */ /* INDEX >> */ if(p_cstr_info) { OPJ_UINT32 resno, compno, numprec = 0; for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) { opj_tcp_t *tcp = &p_tcd->cp->tcps[0]; opj_tccp_t *tccp = &tcp->tccps[compno]; opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno]; for (resno = 0; resno < tilec_idx->numresolutions; resno++) { opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno]; p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw; p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph; numprec += res_idx->pw * res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno]; p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno]; } } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t)); p_cstr_info->packno = 0; } /* << INDEX */ #endif /*--------------TIER2------------------*/ /* FIXME _ProfStart(PGROUP_T2); */ l_data_read = 0; if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*------------------TIER1-----------------*/ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /*----------------DWT---------------------*/ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /*----------------MCT-------------------*/ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_decode(p_tcd, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ if (! opj_tcd_dc_level_shift_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_update_tile_data ( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest, OPJ_UINT32 p_dest_length ) { OPJ_UINT32 i,j,k,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; opj_tcd_resolution_t * l_res; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_stride, l_width,l_height; l_data_size = opj_tcd_get_decoded_tile_size(p_tcd); if (l_data_size > p_dest_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_res = l_tilec->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width; if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest; const OPJ_INT32 * l_src_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_CHAR) (*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_CHAR) ((*(l_src_ptr++))&0xff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE *)l_dest_ptr; } break; case 2: { const OPJ_INT32 * l_src_ptr = l_tilec->data; OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest; if (l_img_comp->sgnd) { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_INT16) (*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_INT16) ((*(l_src_ptr++))&0xffff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; case 4: { OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest; OPJ_INT32 * l_src_ptr = l_tilec->data; for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (*(l_src_ptr++)); } l_src_ptr += l_stride; } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; } static void opj_tcd_free_tile(opj_tcd_t *p_tcd) { OPJ_UINT32 compno, resno, bandno, precno; opj_tcd_tile_t *l_tile = 00; opj_tcd_tilecomp_t *l_tile_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_tcd_precinct_t *l_precinct = 00; OPJ_UINT32 l_nb_resolutions, l_nb_precincts; void (* l_tcd_code_block_deallocate) (opj_tcd_precinct_t *) = 00; if (! p_tcd) { return; } if (! p_tcd->tcd_image) { return; } if (p_tcd->m_is_decoder) { l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate; } else { l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate; } l_tile = p_tcd->tcd_image->tiles; if (! l_tile) { return; } l_tile_comp = l_tile->comps; for (compno = 0; compno < l_tile->numcomps; ++compno) { l_res = l_tile_comp->resolutions; if (l_res) { l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t); for (resno = 0; resno < l_nb_resolutions; ++resno) { l_band = l_res->bands; for (bandno = 0; bandno < 3; ++bandno) { l_precinct = l_band->precincts; if (l_precinct) { l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t); for (precno = 0; precno < l_nb_precincts; ++precno) { opj_tgt_destroy(l_precinct->incltree); l_precinct->incltree = 00; opj_tgt_destroy(l_precinct->imsbtree); l_precinct->imsbtree = 00; (*l_tcd_code_block_deallocate) (l_precinct); ++l_precinct; } opj_free(l_band->precincts); l_band->precincts = 00; } ++l_band; } /* for (resno */ ++l_res; } opj_free(l_tile_comp->resolutions); l_tile_comp->resolutions = 00; } if (l_tile_comp->ownsData && l_tile_comp->data) { opj_aligned_free(l_tile_comp->data); l_tile_comp->data = 00; l_tile_comp->ownsData = 0; l_tile_comp->data_size = 0; l_tile_comp->data_size_needed = 0; } ++l_tile_comp; } opj_free(l_tile->comps); l_tile->comps = 00; opj_free(p_tcd->tcd_image->tiles); p_tcd->tcd_image->tiles = 00; } static OPJ_BOOL opj_tcd_t2_decode (opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_decode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_src_data, p_data_read, p_max_src_size, p_cstr_index, p_manager)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t1_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_t1_t * l_t1; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; l_t1 = opj_t1_create(OPJ_FALSE); if (l_t1 == 00) { return OPJ_FALSE; } for (compno = 0; compno < l_tile->numcomps; ++compno) { /* The +3 is headroom required by the vectorized DWT */ if (OPJ_FALSE == opj_t1_decode_cblks(l_t1, l_tile_comp, l_tccp)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } ++l_tile_comp; ++l_tccp; } opj_t1_destroy(l_t1); return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dwt_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; opj_image_comp_t * l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { /* if (tcd->cp->reduce != 0) { tcd->image->comps[compno].resno_decoded = tile->comps[compno].numresolutions - tcd->cp->reduce - 1; if (tcd->image->comps[compno].resno_decoded < 0) { return false; } } numres2decode = tcd->image->comps[compno].resno_decoded + 1; if(numres2decode > 0){ */ if (l_tccp->qmfbid == 1) { if (! opj_dwt_decode(l_tile_comp, l_img_comp->resno_decoded+1)) { return OPJ_FALSE; } } else { if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded+1)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_img_comp; ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_mct_decode ( opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcp_t * l_tcp = p_tcd->tcp; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; OPJ_UINT32 l_samples,i; if (! l_tcp->mct) { return OPJ_TRUE; } l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tile->numcomps >= 3 ){ /* testcase 1336.pdf.asan.47.376 */ if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples || (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples || (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) { opj_event_msg(p_manager, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n"); return OPJ_FALSE; } else if (l_tcp->mct == 2) { OPJ_BYTE ** l_data; if (! l_tcp->m_mct_decoding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i=0;i<l_tile->numcomps;++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_decode_custom(/* MCT data */ (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix, /* size of components */ l_samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd)) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else { if (l_tcp->tccps->qmfbid == 1) { opj_mct_decode( l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, l_samples); } else { opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data, (OPJ_FLOAT32*)l_tile->comps[1].data, (OPJ_FLOAT32*)l_tile->comps[2].data, l_samples); } } } else { opj_event_msg(p_manager, EVT_ERROR, "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",l_tile->numcomps); } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dc_level_shift_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_resolution_t* l_res = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_width,l_height,i,j; OPJ_INT32 * l_current_ptr; OPJ_INT32 l_min, l_max; OPJ_UINT32 l_stride; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width; assert(l_height == 0 || l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/ if (l_img_comp->sgnd) { l_min = -(1 << (l_img_comp->prec - 1)); l_max = (1 << (l_img_comp->prec - 1)) - 1; } else { l_min = 0; l_max = (1 << l_img_comp->prec) - 1; } l_current_ptr = l_tile_comp->data; if (l_tccp->qmfbid == 1) { for (j=0;j<l_height;++j) { for (i = 0; i < l_width; ++i) { *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min, l_max); ++l_current_ptr; } l_current_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (i = 0; i < l_width; ++i) { OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr); *l_current_ptr = opj_int_clamp((OPJ_INT32)opj_lrintf(l_value) + l_tccp->m_dc_level_shift, l_min, l_max); ; ++l_current_ptr; } l_current_ptr += l_stride; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno , l_nb_code_blocks; opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec; if (l_code_block) { /*fprintf(stderr,"deallocate codeblock:{\n");*/ /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/ /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ", l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/ l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t); /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/ for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data); l_code_block->data = 00; } if (l_code_block->segs) { opj_free(l_code_block->segs ); l_code_block->segs = 00; } ++l_code_block; } opj_free(p_precinct->cblks.dec); p_precinct->cblks.dec = 00; } } /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno , l_nb_code_blocks; opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc; if (l_code_block) { l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t); for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data - 1); l_code_block->data = 00; } if (l_code_block->layers) { opj_free(l_code_block->layers ); l_code_block->layers = 00; } if (l_code_block->passes) { opj_free(l_code_block->passes ); l_code_block->passes = 00; } ++l_code_block; } opj_free(p_precinct->cblks.enc); p_precinct->cblks.enc = 00; } } OPJ_UINT32 opj_tcd_get_encoded_tile_size ( opj_tcd_t *p_tcd ) { OPJ_UINT32 i,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); ++l_img_comp; ++l_tilec; } return l_data_size; } static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_nb_elem,i; OPJ_INT32 * l_current_ptr; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_current_ptr = l_tile_comp->data; l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tccp->qmfbid == 1) { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr -= l_tccp->m_dc_level_shift ; ++l_current_ptr; } } else { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11); ++l_current_ptr; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); OPJ_UINT32 i; OPJ_BYTE ** l_data = 00; opj_tcp_t * l_tcp = p_tcd->tcp; if(!p_tcd->tcp->mct) { return OPJ_TRUE; } if (p_tcd->tcp->mct == 2) { if (! p_tcd->tcp->m_mct_coding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i=0;i<l_tile->numcomps;++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_encode_custom(/* MCT data */ (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix, /* size of components */ samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd) ) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else if (l_tcp->tccps->qmfbid == 0) { opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } else { opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; OPJ_UINT32 compno; for (compno = 0; compno < l_tile->numcomps; ++compno) { if (l_tccp->qmfbid == 1) { if (! opj_dwt_encode(l_tile_comp)) { return OPJ_FALSE; } } else if (l_tccp->qmfbid == 0) { if (! opj_dwt_encode_real(l_tile_comp)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd ) { opj_t1_t * l_t1; const OPJ_FLOAT64 * l_mct_norms; OPJ_UINT32 l_mct_numcomps = 0U; opj_tcp_t * l_tcp = p_tcd->tcp; l_t1 = opj_t1_create(OPJ_TRUE); if (l_t1 == 00) { return OPJ_FALSE; } if (l_tcp->mct == 1) { l_mct_numcomps = 3U; /* irreversible encoding */ if (l_tcp->tccps->qmfbid == 0) { l_mct_norms = opj_mct_get_mct_norms_real(); } else { l_mct_norms = opj_mct_get_mct_norms(); } } else { l_mct_numcomps = p_tcd->image->numcomps; l_mct_norms = (const OPJ_FLOAT64 *) (l_tcp->mct_norms); } if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles , l_tcp, l_mct_norms, l_mct_numcomps)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } opj_t1_destroy(l_t1); return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t2_encode (opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_encode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_tcd->tcp->numlayers, p_dest_data, p_data_written, p_max_dest_size, p_cstr_info, p_tcd->tp_num, p_tcd->tp_pos, p_tcd->cur_pino, FINAL_PASS)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ) { opj_cp_t * l_cp = p_tcd->cp; OPJ_UINT32 l_nb_written = 0; if (p_cstr_info) { p_cstr_info->index_write = 0; } if (l_cp->m_specific_param.m_enc.m_disto_alloc|| l_cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ /* Normal Rate/distortion allocation */ if (! opj_tcd_rateallocate(p_tcd, p_dest_data,&l_nb_written, p_max_dest_size, p_cstr_info)) { return OPJ_FALSE; } } else { /* Fixed layer allocation */ opj_tcd_rateallocate_fixed(p_tcd); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_copy_tile_data ( opj_tcd_t *p_tcd, OPJ_BYTE * p_src, OPJ_UINT32 p_src_length ) { OPJ_UINT32 i,j,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_nb_elem; l_data_size = opj_tcd_get_encoded_tile_size(p_tcd); if (l_data_size != p_src_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } } else { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (*(l_src_ptr++))&0xff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 2: { OPJ_INT32 * l_dest_ptr = l_tilec->data; OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src; if (l_img_comp->sgnd) { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } } else { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (*(l_src_ptr++))&0xffff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 4: { OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } p_src = (OPJ_BYTE*) l_src_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5096_0
crossvul-cpp_data_bad_5127_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,NexusInfo *,ExceptionInfo *) magick_hot_spot; #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static volatile MagickBooleanType instantiate_cache = MagickFalse; static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *synchronize; cache_info=(CacheInfo *) AcquireQuantumMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { cache_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % const void *AcquirePixelCachePixels(const Image *image, % MagickSizeType *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate const void *AcquirePixelCachePixels(const Image *image, MagickSizeType *length,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((const void *) NULL); *length=cache_info->length; return((const void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); LockSemaphoreInfo(cache_semaphore); instantiate_cache=MagickFalse; UnlockSemaphoreInfo(cache_semaphore); RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); if (clone_info == (Cache) NULL) return((Cache) NULL); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identifcal morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads 2 #define cache_threads(source,destination) \ num_threads(((source)->type == DiskCache) || \ ((destination)->type == DiskCache) || (((source)->rows) < \ (16*GetMagickResourceLimit(ThreadResource))) ? 1 : \ GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \ GetMagickResourceLimit(ThreadResource) : MaxCacheThreads) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->columns*cache_info->number_channels*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); if ((cache_nexus == (NexusInfo **) NULL) || (clone_nexus == (NexusInfo **) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->columns*cache_info->number_channels, clone_info->columns*clone_info->number_channels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; register ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { register ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache == (void *) NULL) return; image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; } RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if (cache_info->mode != ReadMode) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if (cache_info->mode != ReadMode) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->read_mask != cache_info->read_mask) || (image->write_mask != cache_info->write_mask) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = 0, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=time((time_t *) NULL); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status != MagickFalse) { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status != MagickFalse) { if (cache_info->reference_count == 1) cache_info->nexus_info=(NexusInfo **) NULL; destroy=MagickTrue; image->cache=clone_image.cache; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->type == DiskCache) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image,const Quantum *source, Quantum *destination) { register ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum(image->background_color.green); destination[BluePixelChannel]=ClampToQuantum(image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum(image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum(image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y, pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) ResetMagickMemory(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=cache_info->length; return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimize cache tile width in pixels. % % o height: the optimize cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(cache_info->number_channels*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(cache_info->number_channels*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsFromNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelsFromNexus() method is: % % Quantum *GetVirtualPixelsFromNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; /* Compute the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ modulo.quotient=offset/(ssize_t) extent; if (offset < 0L) modulo.quotient--; modulo.remainder=offset-modulo.quotient*(ssize_t) extent; return(modulo); } MagickPrivate const Quantum *GetVirtualPixelsFromNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; RectangleInfo region; register const Quantum *magick_restrict p; register const void *magick_restrict r; register Quantum *magick_restrict q; register ssize_t i, u; register unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,nexus_info, exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ s=(unsigned char *) nexus_info->metacontent; virtual_nexus=AcquirePixelCacheNexus(1); if (virtual_nexus == (NexusInfo **) NULL) { if (virtual_nexus != (NexusInfo **) NULL) virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) ResetMagickMemory(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) ResetMagickMemory(virtual_metacontent,0, cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) length*cache_info->number_channels* sizeof(*p)); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) length*cache_info->number_channels*sizeof(*p)); q+=length*cache_info->number_channels; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if defined(SIGBUS) static void CacheSignalHandler(int status) { ThrowFatalException(CacheFatalError,"UnableToExtendPixelCache"); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) (void) posix_fallocate(cache_info->file,offset+1,extent-offset); #endif #if defined(SIGBUS) (void) signal(SIGBUS,CacheSignalHandler); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->read_mask=image->read_mask; cache_info->write_mask=image->write_mask; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ status=MagickTrue; cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; } else { /* Create file-backed memory-mapped pixel cache. */ status=MagickTrue; (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status); } } RelinquishMagickResource(MapResource,cache_info->length); } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; Image clone_image; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } if ((cache_info->mode != ReadMode) && ((cache_info->type == DiskCache) || (cache_info->type == MapCache)) && (cache_info->reference_count == 1)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->mode != ReadMode) && ((cache_info->type == DiskCache) || (cache_info->type == MapCache)) && (cache_info->reference_count == 1)) { /* Usurp existing persistent pixel cache. */ if (rename_utf8(cache_info->cache_filename, filename) == 0) { (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); *offset+=cache_info->length+page_size-(cache_info->length % page_size); UnlockSemaphoreInfo(cache_info->semaphore); cache_info=(CacheInfo *) ReferencePixelCache(cache_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "Usurp resident persistent cache"); return(MagickTrue); } } UnlockSemaphoreInfo(cache_info->semaphore); } /* Clone persistent pixel cache. */ clone_image=(*image); clone_info=(CacheInfo *) clone_image.cache; image->cache=ClonePixelCache(cache_info); cache_info=(CacheInfo *) ReferencePixelCache(image->cache); (void) CopyMagickString(cache_info->cache_filename,filename,MagickPathExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); cache_info=(CacheInfo *) image->cache; status=OpenPixelCache(image,IOMode,exception); if (status != MagickFalse) status=ClonePixelCacheRepository(cache_info,clone_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region,nexus_info, exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register ssize_t y; register unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register Quantum *magick_restrict q; register ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+offset*cache_info->number_channels; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,NexusInfo *nexus_info, ExceptionInfo *exception) { if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length)) return(MagickFalse); nexus_info->mapped=MagickFalse; nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) nexus_info->length)); if (nexus_info->cache == (Quantum *) NULL) { nexus_info->mapped=MagickTrue; nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) nexus_info->length); } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } return(MagickTrue); } static inline MagickBooleanType IsPixelCacheAuthentic( const CacheInfo *magick_restrict cache_info, const NexusInfo *magick_restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset* cache_info->number_channels) ? MagickTrue : MagickFalse; return(status); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1); } static Quantum *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); nexus_info->region=(*region); if ((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) { ssize_t x, y; x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1; y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1; if (((nexus_info->region.x >= 0) && (x < (ssize_t) cache_info->columns) && (nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) && ((nexus_info->region.height == 1UL) || ((nexus_info->region.x == 0) && ((nexus_info->region.width == cache_info->columns) || ((nexus_info->region.width % cache_info->columns) == 0))))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info, nexus_info); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; length=number_pixels*cache_info->number_channels*sizeof(Quantum); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; if (nexus_info->cache == (Quantum *) NULL) { nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((Quantum *) NULL); } } else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((Quantum *) NULL); } } nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+number_pixels* cache_info->number_channels); PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info, nexus_info); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) { image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (status != MagickFalse) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const unsigned char *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const Quantum *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+offset*cache_info->number_channels; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->columns*cache_info->number_channels; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5127_0
crossvul-cpp_data_good_4054_0
/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jcontext.h" #include "ecma-alloc.h" #include "ecma-array-object.h" #include "ecma-builtins.h" #include "ecma-builtin-helpers.h" #include "ecma-exceptions.h" #include "ecma-function-object.h" #include "ecma-gc.h" #include "ecma-helpers.h" #include "ecma-iterator-object.h" #include "ecma-container-object.h" #include "ecma-property-hashmap.h" #include "ecma-objects.h" #if ENABLED (JERRY_ES2015_BUILTIN_CONTAINER) /** \addtogroup ecma ECMA * @{ * * \addtogroup \addtogroup ecmamaphelpers ECMA builtin Map/Set helper functions * @{ */ /** * Create a new internal buffer. * * Note: * The first element of the collection tracks the size of the buffer. * ECMA_VALUE_EMPTY values are not calculated into the size. * * @return pointer to the internal buffer */ static inline ecma_collection_t * ecma_op_create_internal_buffer (void) { ecma_collection_t *collection_p = ecma_new_collection (); ecma_collection_push_back (collection_p, (ecma_value_t) 0); return collection_p; } /* ecma_op_create_internal_buffer */ /** * Append values to the internal buffer. */ static void ecma_op_internal_buffer_append (ecma_collection_t *container_p, /**< internal container pointer */ ecma_value_t key_arg, /**< key argument */ ecma_value_t value_arg, /**< value argument */ lit_magic_string_id_t lit_id) /**< class id */ { JERRY_ASSERT (container_p != NULL); if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL) { ecma_value_t values[] = { ecma_copy_value_if_not_object (key_arg), ecma_copy_value_if_not_object (value_arg) }; ecma_collection_append (container_p, values, 2); } else { ecma_collection_push_back (container_p, ecma_copy_value_if_not_object (key_arg)); } ECMA_CONTAINER_SET_SIZE (container_p, ECMA_CONTAINER_GET_SIZE (container_p) + 1); } /* ecma_op_internal_buffer_append */ /** * Update the value of a given entry. */ static inline void ecma_op_internal_buffer_update (ecma_value_t *entry_p, /**< entry pointer */ ecma_value_t value_arg, /**< value argument */ lit_magic_string_id_t lit_id) /**< class id */ { JERRY_ASSERT (entry_p != NULL); if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL) { ecma_free_value_if_not_object (((ecma_container_pair_t *) entry_p)->value); ((ecma_container_pair_t *) entry_p)->value = ecma_copy_value_if_not_object (value_arg); } } /* ecma_op_internal_buffer_update */ /** * Delete element from the internal buffer. */ static void ecma_op_internal_buffer_delete (ecma_collection_t *container_p, /**< internal container pointer */ ecma_container_pair_t *entry_p, /**< entry pointer */ lit_magic_string_id_t lit_id) /**< class id */ { JERRY_ASSERT (container_p != NULL); JERRY_ASSERT (entry_p != NULL); ecma_free_value_if_not_object (entry_p->key); entry_p->key = ECMA_VALUE_EMPTY; if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL) { ecma_free_value_if_not_object (entry_p->value); entry_p->value = ECMA_VALUE_EMPTY; } ECMA_CONTAINER_SET_SIZE (container_p, ECMA_CONTAINER_GET_SIZE (container_p) - 1); } /* ecma_op_internal_buffer_delete */ /** * Find an entry in the collection. * * @return pointer to the appropriate entry. */ static ecma_value_t * ecma_op_internal_buffer_find (ecma_collection_t *container_p, /**< internal container pointer */ ecma_value_t key_arg, /**< key argument */ lit_magic_string_id_t lit_id) /**< class id */ { JERRY_ASSERT (container_p != NULL); uint8_t entry_size = ecma_op_container_entry_size (lit_id); uint32_t entry_count = ECMA_CONTAINER_ENTRY_COUNT (container_p); ecma_value_t *start_p = ECMA_CONTAINER_START (container_p); for (uint32_t i = 0; i < entry_count; i += entry_size) { ecma_value_t *entry_p = start_p + i; if (ecma_op_same_value_zero (*entry_p, key_arg)) { return entry_p; } } return NULL; } /* ecma_op_internal_buffer_find */ /** * Get the value that belongs to the key. * * Note: in case of Set containers, the values are the same as the keys. * * @return ecma value */ static ecma_value_t ecma_op_container_get_value (ecma_value_t *entry_p, /**< entry (key) pointer */ lit_magic_string_id_t lit_id) /**< class id */ { JERRY_ASSERT (entry_p != NULL); if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL) { return ((ecma_container_pair_t *) entry_p)->value; } return *entry_p; } /* ecma_op_container_get_value */ /** * Get the size (in ecma_value_t) of the stored entries. * * @return size of the entries. */ uint8_t ecma_op_container_entry_size (lit_magic_string_id_t lit_id) /**< class id */ { if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_MAP_UL) { return ECMA_CONTAINER_PAIR_SIZE; } return ECMA_CONTAINER_VALUE_SIZE; } /* ecma_op_container_entry_size */ #if ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) /** * Release the entries in the WeakSet container. */ static void ecma_op_container_free_weakset_entries (ecma_object_t *object_p, /**< object pointer */ ecma_collection_t *container_p) /** internal buffer pointer */ { JERRY_ASSERT (object_p != NULL); JERRY_ASSERT (container_p != NULL); uint32_t entry_count = ECMA_CONTAINER_ENTRY_COUNT (container_p); ecma_value_t *start_p = ECMA_CONTAINER_START (container_p); for (uint32_t i = 0; i < entry_count; i += ECMA_CONTAINER_VALUE_SIZE) { ecma_value_t *entry_p = start_p + i; if (ecma_is_value_empty (*entry_p)) { continue; } ecma_op_container_unref_weak (ecma_get_object_from_value (*entry_p), ecma_make_object_value (object_p)); ecma_op_container_remove_weak_entry (object_p, *entry_p); *entry_p = ECMA_VALUE_EMPTY; } } /* ecma_op_container_free_weakset_entries */ #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) */ #if ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) /** * Release the entries in the WeakMap container. */ static void ecma_op_container_free_weakmap_entries (ecma_object_t *object_p, /**< object pointer */ ecma_collection_t *container_p) /**< internal buffer pointer */ { JERRY_ASSERT (object_p != NULL); JERRY_ASSERT (container_p != NULL); uint32_t entry_count = ECMA_CONTAINER_ENTRY_COUNT (container_p); ecma_value_t *start_p = ECMA_CONTAINER_START (container_p); for (uint32_t i = 0; i < entry_count; i += ECMA_CONTAINER_PAIR_SIZE) { ecma_container_pair_t *entry_p = (ecma_container_pair_t *) (start_p + i); if (ecma_is_value_empty (entry_p->key)) { continue; } ecma_op_container_unref_weak (ecma_get_object_from_value (entry_p->key), ecma_make_object_value (object_p)); ecma_op_container_remove_weak_entry (object_p, entry_p->key); ecma_free_value_if_not_object (entry_p->value); entry_p->key = ECMA_VALUE_EMPTY; entry_p->value = ECMA_VALUE_EMPTY; } } /* ecma_op_container_free_weakmap_entries */ #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) */ #if ENABLED (JERRY_ES2015_BUILTIN_SET) /** * Release the entries in the Set container. */ static void ecma_op_container_free_set_entries (ecma_collection_t *container_p) { JERRY_ASSERT (container_p != NULL); uint32_t entry_count = ECMA_CONTAINER_ENTRY_COUNT (container_p); ecma_value_t *start_p = ECMA_CONTAINER_START (container_p); for (uint32_t i = 0; i < entry_count; i += ECMA_CONTAINER_VALUE_SIZE) { ecma_value_t *entry_p = start_p + i; if (ecma_is_value_empty (*entry_p)) { continue; } ecma_free_value_if_not_object (*entry_p); *entry_p = ECMA_VALUE_EMPTY; } } /* ecma_op_container_free_set_entries */ #endif /* ENABLED (JERRY_ES2015_BUILTIN_SET) */ #if ENABLED (JERRY_ES2015_BUILTIN_MAP) /** * Release the entries in the Map container. */ static void ecma_op_container_free_map_entries (ecma_collection_t *container_p) { JERRY_ASSERT (container_p != NULL); uint32_t entry_count = ECMA_CONTAINER_ENTRY_COUNT (container_p); ecma_value_t *start_p = ECMA_CONTAINER_START (container_p); for (uint32_t i = 0; i < entry_count; i += ECMA_CONTAINER_PAIR_SIZE) { ecma_container_pair_t *entry_p = (ecma_container_pair_t *) (start_p + i); if (ecma_is_value_empty (entry_p->key)) { continue; } ecma_free_value_if_not_object (entry_p->key); ecma_free_value_if_not_object (entry_p->value); entry_p->key = ECMA_VALUE_EMPTY; entry_p->value = ECMA_VALUE_EMPTY; } } /* ecma_op_container_free_map_entries */ #endif /* ENABLED (JERRY_ES2015_BUILTIN_MAP) */ /** * Release the internal buffer and the stored entries. */ void ecma_op_container_free_entries (ecma_object_t *object_p) /**< collection object pointer */ { JERRY_ASSERT (object_p != NULL); ecma_extended_object_t *map_object_p = (ecma_extended_object_t *) object_p; ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); switch (map_object_p->u.class_prop.class_id) { #if ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) case LIT_MAGIC_STRING_WEAKSET_UL: { ecma_op_container_free_weakset_entries (object_p, container_p); break; } #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) */ #if ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) case LIT_MAGIC_STRING_WEAKMAP_UL: { ecma_op_container_free_weakmap_entries (object_p, container_p); break; } #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) */ #if ENABLED (JERRY_ES2015_BUILTIN_SET) case LIT_MAGIC_STRING_SET_UL: { ecma_op_container_free_set_entries (container_p); break; } #endif /* ENABLED (JERRY_ES2015_BUILTIN_SET) */ #if ENABLED (JERRY_ES2015_BUILTIN_MAP) case LIT_MAGIC_STRING_MAP_UL: { ecma_op_container_free_map_entries (container_p); break; } #endif /* ENABLED (JERRY_ES2015_BUILTIN_MAP) */ default: { break; } } ECMA_CONTAINER_SET_SIZE (container_p, 0); } /* ecma_op_container_free_entries */ /** * Handle calling [[Construct]] of built-in Map/Set like objects * * @return ecma value */ ecma_value_t ecma_op_container_create (const ecma_value_t *arguments_list_p, /**< arguments list */ ecma_length_t arguments_list_len, /**< number of arguments */ lit_magic_string_id_t lit_id, /**< internal class id */ ecma_builtin_id_t proto_id) /**< prototype builtin id */ { JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL); JERRY_ASSERT (lit_id == LIT_MAGIC_STRING_MAP_UL || lit_id == LIT_MAGIC_STRING_SET_UL || lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_WEAKSET_UL); JERRY_ASSERT (JERRY_CONTEXT (current_new_target) != NULL); ecma_object_t *proto_p = ecma_op_get_prototype_from_constructor (JERRY_CONTEXT (current_new_target), proto_id); if (JERRY_UNLIKELY (proto_p == NULL)) { return ECMA_VALUE_ERROR; } ecma_collection_t *container_p = ecma_op_create_internal_buffer (); ecma_object_t *object_p = ecma_create_object (proto_p, sizeof (ecma_extended_object_t), ECMA_OBJECT_TYPE_CLASS); ecma_deref_object (proto_p); ecma_extended_object_t *map_obj_p = (ecma_extended_object_t *) object_p; map_obj_p->u.class_prop.extra_info = ECMA_CONTAINER_FLAGS_EMPTY; map_obj_p->u.class_prop.class_id = (uint16_t) lit_id; if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL || lit_id == LIT_MAGIC_STRING_WEAKSET_UL) { map_obj_p->u.class_prop.extra_info |= ECMA_CONTAINER_FLAGS_WEAK; } ECMA_SET_INTERNAL_VALUE_POINTER (map_obj_p->u.class_prop.u.value, container_p); ecma_value_t set_value = ecma_make_object_value (object_p); ecma_value_t result = set_value; #if ENABLED (JERRY_ES2015) if (arguments_list_len == 0) { return result; } ecma_value_t iterable = arguments_list_p[0]; if (ecma_is_value_undefined (iterable) || ecma_is_value_null (iterable)) { return result; } lit_magic_string_id_t adder_string_id; if (lit_id == LIT_MAGIC_STRING_MAP_UL || lit_id == LIT_MAGIC_STRING_WEAKMAP_UL) { adder_string_id = LIT_MAGIC_STRING_SET; } else { adder_string_id = LIT_MAGIC_STRING_ADD; } result = ecma_op_object_get_by_magic_id (object_p, adder_string_id); if (ECMA_IS_VALUE_ERROR (result)) { goto cleanup_object; } if (!ecma_op_is_callable (result)) { ecma_free_value (result); result = ecma_raise_type_error (ECMA_ERR_MSG ("add/set function is not callable.")); goto cleanup_object; } ecma_object_t *adder_func_p = ecma_get_object_from_value (result); result = ecma_op_get_iterator (iterable, ECMA_VALUE_EMPTY); if (ECMA_IS_VALUE_ERROR (result)) { goto cleanup_adder; } const ecma_value_t iter = result; while (true) { result = ecma_op_iterator_step (iter); if (ECMA_IS_VALUE_ERROR (result)) { goto cleanup_iter; } if (ecma_is_value_false (result)) { break; } const ecma_value_t next = result; result = ecma_op_iterator_value (next); ecma_free_value (next); if (ECMA_IS_VALUE_ERROR (result)) { goto cleanup_iter; } if (lit_id == LIT_MAGIC_STRING_SET_UL || lit_id == LIT_MAGIC_STRING_WEAKSET_UL) { const ecma_value_t value = result; ecma_value_t arguments[] = { value }; result = ecma_op_function_call (adder_func_p, set_value, arguments, 1); ecma_free_value (value); } else { if (!ecma_is_value_object (result)) { ecma_free_value (result); ecma_raise_type_error (ECMA_ERR_MSG ("Iterator value is not an object.")); result = ecma_op_iterator_close (iter); JERRY_ASSERT (ECMA_IS_VALUE_ERROR (result)); goto cleanup_iter; } ecma_object_t *next_object_p = ecma_get_object_from_value (result); result = ecma_op_object_get_by_uint32_index (next_object_p, 0); if (ECMA_IS_VALUE_ERROR (result)) { ecma_deref_object (next_object_p); ecma_op_iterator_close (iter); goto cleanup_iter; } const ecma_value_t key = result; result = ecma_op_object_get_by_uint32_index (next_object_p, 1); if (ECMA_IS_VALUE_ERROR (result)) { ecma_deref_object (next_object_p); ecma_free_value (key); ecma_op_iterator_close (iter); goto cleanup_iter; } const ecma_value_t value = result; ecma_value_t arguments[] = { key, value }; result = ecma_op_function_call (adder_func_p, set_value, arguments, 2); ecma_free_value (key); ecma_free_value (value); ecma_deref_object (next_object_p); } if (ECMA_IS_VALUE_ERROR (result)) { ecma_op_iterator_close (iter); goto cleanup_iter; } ecma_free_value (result); } ecma_free_value (iter); ecma_deref_object (adder_func_p); return ecma_make_object_value (object_p); cleanup_iter: ecma_free_value (iter); cleanup_adder: ecma_deref_object (adder_func_p); cleanup_object: ecma_deref_object (object_p); #endif /* ENABLED (JERRY_ES2015) */ return result; } /* ecma_op_container_create */ /** * Get Map/Set object pointer * * Note: * If the function returns with NULL, the error object has * already set, and the caller must return with ECMA_VALUE_ERROR * * @return pointer to the Map/Set if this_arg is a valid Map/Set object * NULL otherwise */ static ecma_extended_object_t * ecma_op_container_get_object (ecma_value_t this_arg, /**< this argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { if (ecma_is_value_object (this_arg)) { ecma_extended_object_t *map_object_p = (ecma_extended_object_t *) ecma_get_object_from_value (this_arg); if (ecma_get_object_type ((ecma_object_t *) map_object_p) == ECMA_OBJECT_TYPE_CLASS && map_object_p->u.class_prop.class_id == lit_id) { return map_object_p; } } #if ENABLED (JERRY_ERROR_MESSAGES) ecma_raise_standard_error_with_format (ECMA_ERROR_TYPE, "Expected a % object.", ecma_make_string_value (ecma_get_magic_string (lit_id))); #else /* !ENABLED (JERRY_ERROR_MESSAGES) */ ecma_raise_type_error (NULL); #endif /* ENABLED (JERRY_ERROR_MESSAGES) */ return NULL; } /* ecma_op_container_get_object */ /** * Returns with the size of the Map/Set object. * * @return size of the Map/Set object as ecma-value. */ ecma_value_t ecma_op_container_size (ecma_value_t this_arg, /**< this argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); return ecma_make_uint32_value (ECMA_CONTAINER_GET_SIZE (container_p)); } /* ecma_op_container_size */ /** * The generic Map/WeakMap prototype object's 'get' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_get (ecma_value_t this_arg, /**< this argument */ ecma_value_t key_arg, /**< key argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } #if ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) if (lit_id == LIT_MAGIC_STRING_WEAKMAP_UL && !ecma_is_value_object (key_arg)) { return ECMA_VALUE_UNDEFINED; } #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) */ ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); if (ECMA_CONTAINER_GET_SIZE (container_p) == 0) { return ECMA_VALUE_UNDEFINED; } ecma_value_t *entry_p = ecma_op_internal_buffer_find (container_p, key_arg, lit_id); if (entry_p == NULL) { return ECMA_VALUE_UNDEFINED; } return ecma_copy_value (((ecma_container_pair_t *) entry_p)->value); } /* ecma_op_container_get */ /** * The generic Map/Set prototype object's 'has' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_has (ecma_value_t this_arg, /**< this argument */ ecma_value_t key_arg, /**< key argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); #if ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) || ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) if ((map_object_p->u.class_prop.extra_info & ECMA_CONTAINER_FLAGS_WEAK) != 0 && !ecma_is_value_object (key_arg)) { return ECMA_VALUE_FALSE; } #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) || ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) */ if (ECMA_CONTAINER_GET_SIZE (container_p) == 0) { return ECMA_VALUE_FALSE; } ecma_value_t *entry_p = ecma_op_internal_buffer_find (container_p, key_arg, lit_id); return ecma_make_boolean_value (entry_p != NULL); } /* ecma_op_container_has */ /** * Set a weak reference from a container to a key object */ static void ecma_op_container_set_weak (ecma_object_t *const key_p, /**< key object */ ecma_extended_object_t *const container_p) /**< container */ { if (JERRY_UNLIKELY (ecma_op_object_is_fast_array (key_p))) { ecma_fast_array_convert_to_normal (key_p); } ecma_string_t *weak_refs_string_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_WEAK_REFS); ecma_property_t *property_p = ecma_find_named_property (key_p, weak_refs_string_p); ecma_collection_t *refs_p; if (property_p == NULL) { ecma_property_value_t *value_p = ecma_create_named_data_property (key_p, weak_refs_string_p, ECMA_PROPERTY_CONFIGURABLE_WRITABLE, &property_p); ECMA_CONVERT_DATA_PROPERTY_TO_INTERNAL_PROPERTY (property_p); refs_p = ecma_new_collection (); ECMA_SET_INTERNAL_VALUE_POINTER (value_p->value, refs_p); } else { refs_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, (ECMA_PROPERTY_VALUE_PTR (property_p)->value)); } const ecma_value_t container_value = ecma_make_object_value ((ecma_object_t *) container_p); for (uint32_t i = 0; i < refs_p->item_count; i++) { if (ecma_is_value_empty (refs_p->buffer_p[i])) { refs_p->buffer_p[i] = container_value; return; } } ecma_collection_push_back (refs_p, container_value); } /* ecma_op_container_set_weak */ /** * Helper method for the Map.prototype.set and Set.prototype.add methods to swap the sign of the given value if needed * * See also: * ECMA-262 v6, 23.2.3.1 step 6 * ECMA-262 v6, 23.1.3.9 step 6 * * @return ecma value */ static ecma_value_t ecma_op_container_set_noramlize_zero (ecma_value_t this_arg) /*< this arg */ { if (ecma_is_value_number (this_arg)) { ecma_number_t number_value = ecma_get_number_from_value (this_arg); if (JERRY_UNLIKELY (ecma_number_is_zero (number_value) && ecma_number_is_negative (number_value))) { return ecma_make_integer_value (0); } } return this_arg; } /* ecma_op_container_set_noramlize_zero */ /** * The generic Map prototype object's 'set' and Set prototype object's 'add' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_set (ecma_value_t this_arg, /**< this argument */ ecma_value_t key_arg, /**< key argument */ ecma_value_t value_arg, /**< value argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); #if ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) || ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) if ((map_object_p->u.class_prop.extra_info & ECMA_CONTAINER_FLAGS_WEAK) != 0 && !ecma_is_value_object (key_arg)) { return ecma_raise_type_error (ECMA_ERR_MSG ("Key must be an object")); } #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) || ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) */ ecma_value_t *entry_p = ecma_op_internal_buffer_find (container_p, key_arg, lit_id); if (entry_p == NULL) { ecma_op_internal_buffer_append (container_p, ecma_op_container_set_noramlize_zero (key_arg), value_arg, lit_id); #if ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) || ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) if ((map_object_p->u.class_prop.extra_info & ECMA_CONTAINER_FLAGS_WEAK) != 0) { ecma_object_t *key_p = ecma_get_object_from_value (key_arg); ecma_op_container_set_weak (key_p, map_object_p); } #endif /* ENABLED (JERRY_ES2015_BUILTIN_WEAKMAP) || ENABLED (JERRY_ES2015_BUILTIN_WEAKSET) */ } else { ecma_op_internal_buffer_update (entry_p, ecma_op_container_set_noramlize_zero (value_arg), lit_id); } ecma_ref_object ((ecma_object_t *) map_object_p); return this_arg; } /* ecma_op_container_set */ /** * The generic Map/Set prototype object's 'forEach' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_foreach (ecma_value_t this_arg, /**< this argument */ ecma_value_t predicate, /**< callback function */ ecma_value_t predicate_this_arg, /**< this argument for * invoke predicate */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } if (!ecma_op_is_callable (predicate)) { return ecma_raise_type_error (ECMA_ERR_MSG ("Callback function is not callable.")); } JERRY_ASSERT (ecma_is_value_object (predicate)); ecma_object_t *func_object_p = ecma_get_object_from_value (predicate); ecma_value_t ret_value = ECMA_VALUE_UNDEFINED; ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); uint8_t entry_size = ecma_op_container_entry_size (lit_id); for (uint32_t i = 0; i < ECMA_CONTAINER_ENTRY_COUNT (container_p); i += entry_size) { ecma_value_t *entry_p = ECMA_CONTAINER_START (container_p) + i; if (ecma_is_value_empty (*entry_p)) { continue; } ecma_value_t key_arg = *entry_p; ecma_value_t value_arg = ecma_op_container_get_value (entry_p, lit_id); ecma_value_t call_args[] = { value_arg, key_arg, this_arg }; ecma_value_t call_value = ecma_op_function_call (func_object_p, predicate_this_arg, call_args, 3); if (ECMA_IS_VALUE_ERROR (call_value)) { ret_value = call_value; break; } ecma_free_value (call_value); } return ret_value; } /* ecma_op_container_foreach */ /** * The Map/Set prototype object's 'clear' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_clear (ecma_value_t this_arg, /**< this argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } ecma_op_container_free_entries ((ecma_object_t *) map_object_p); return ECMA_VALUE_UNDEFINED; } /* ecma_op_container_clear */ /** * The generic Map/Set prototype object's 'delete' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_delete (ecma_value_t this_arg, /**< this argument */ ecma_value_t key_arg, /**< key argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); ecma_value_t *entry_p = ecma_op_internal_buffer_find (container_p, key_arg, lit_id); if (entry_p == NULL) { return ECMA_VALUE_FALSE; } ecma_op_internal_buffer_delete (container_p, (ecma_container_pair_t *) entry_p, lit_id); return ECMA_VALUE_TRUE; } /* ecma_op_container_delete */ /** * The generic WeakMap/WeakSet prototype object's 'delete' routine * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_op_container_delete_weak (ecma_value_t this_arg, /**< this argument */ ecma_value_t key_arg, /**< key argument */ lit_magic_string_id_t lit_id) /**< internal class id */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } if (!ecma_is_value_object (key_arg)) { return ECMA_VALUE_FALSE; } ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); ecma_value_t *entry_p = ecma_op_internal_buffer_find (container_p, key_arg, lit_id); if (entry_p == NULL) { return ECMA_VALUE_FALSE; } ecma_op_internal_buffer_delete (container_p, (ecma_container_pair_t *) entry_p, lit_id); ecma_object_t *key_object_p = ecma_get_object_from_value (key_arg); ecma_op_container_unref_weak (key_object_p, ecma_make_object_value ((ecma_object_t *) map_object_p)); return ECMA_VALUE_TRUE; } /* ecma_op_container_delete_weak */ /** * Helper function to remove a weak reference to an object. * * @return ecma value * Returned value must be freed with ecma_free_value. */ void ecma_op_container_unref_weak (ecma_object_t *object_p, /**< this argument */ ecma_value_t ref_holder) /**< key argument */ { ecma_string_t *weak_refs_string_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_WEAK_REFS); ecma_property_t *property_p = ecma_find_named_property (object_p, weak_refs_string_p); JERRY_ASSERT (property_p != NULL); ecma_collection_t *refs_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, ECMA_PROPERTY_VALUE_PTR (property_p)->value); for (uint32_t i = 0; i < refs_p->item_count; i++) { if (refs_p->buffer_p[i] == ref_holder) { refs_p->buffer_p[i] = ECMA_VALUE_EMPTY; break; } } } /* ecma_op_container_unref_weak */ /** * Helper function to remove a key/value pair from a weak container object */ void ecma_op_container_remove_weak_entry (ecma_object_t *object_p, /**< internal container object */ ecma_value_t key_arg) /**< key */ { ecma_extended_object_t *map_object_p = (ecma_extended_object_t *) object_p; ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); ecma_value_t *entry_p = ecma_op_internal_buffer_find (container_p, key_arg, map_object_p->u.class_prop.class_id); JERRY_ASSERT (entry_p != NULL); ecma_op_internal_buffer_delete (container_p, (ecma_container_pair_t *) entry_p, map_object_p->u.class_prop.class_id); } /* ecma_op_container_remove_weak_entry */ #if ENABLED (JERRY_ES2015) /** * The Create{Set, Map}Iterator Abstract operation * * See also: * ECMA-262 v6, 23.1.5.1 * ECMA-262 v6, 23.2.5.1 * * Note: * Returned value must be freed with ecma_free_value. * * @return Map/Set iterator object, if success * error - otherwise */ ecma_value_t ecma_op_container_create_iterator (ecma_value_t this_arg, /**< this argument */ uint8_t type, /**< any combination of * ecma_iterator_type_t bits */ lit_magic_string_id_t lit_id, /**< internal class id */ ecma_builtin_id_t proto_id, /**< prototype builtin id */ ecma_pseudo_array_type_t iterator_type) /**< type of the iterator */ { ecma_extended_object_t *map_object_p = ecma_op_container_get_object (this_arg, lit_id); if (map_object_p == NULL) { return ECMA_VALUE_ERROR; } return ecma_op_create_iterator_object (this_arg, ecma_builtin_get (proto_id), (uint8_t) iterator_type, type); } /* ecma_op_container_create_iterator */ /** * Get the index of the iterator object. * * @return index of the iterator. */ static uint32_t ecma_op_iterator_get_index (ecma_object_t *iter_obj_p) /**< iterator object pointer */ { uint32_t index = ((ecma_extended_object_t *) iter_obj_p)->u.pseudo_array.u1.iterator_index; if (JERRY_UNLIKELY (index == ECMA_ITERATOR_INDEX_LIMIT)) { ecma_string_t *prop_name_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_ITERATOR_NEXT_INDEX); ecma_property_t *property_p = ecma_find_named_property (iter_obj_p, prop_name_p); ecma_property_value_t *value_p = ECMA_PROPERTY_VALUE_PTR (property_p); return (uint32_t) (ecma_get_number_from_value (value_p->value)); } return index; } /* ecma_op_iterator_get_index */ /** * Set the index of the iterator object. */ static void ecma_op_iterator_set_index (ecma_object_t *iter_obj_p, /**< iterator object pointer */ uint32_t index) /* iterator index to set */ { if (JERRY_UNLIKELY (index >= ECMA_ITERATOR_INDEX_LIMIT)) { /* After the ECMA_ITERATOR_INDEX_LIMIT limit is reached the [[%Iterator%NextIndex]] property is stored as an internal property */ ecma_string_t *prop_name_p = ecma_get_magic_string (LIT_INTERNAL_MAGIC_STRING_ITERATOR_NEXT_INDEX); ecma_property_t *property_p = ecma_find_named_property (iter_obj_p, prop_name_p); ecma_property_value_t *value_p; if (property_p == NULL) { value_p = ecma_create_named_data_property (iter_obj_p, prop_name_p, ECMA_PROPERTY_FLAG_WRITABLE, &property_p); value_p->value = ecma_make_uint32_value (index); } else { value_p = ECMA_PROPERTY_VALUE_PTR (property_p); value_p->value = ecma_make_uint32_value (index); } } else { ((ecma_extended_object_t *) iter_obj_p)->u.pseudo_array.u1.iterator_index = (uint16_t) index; } } /* ecma_op_iterator_set_index */ /** * The %{Set, Map}IteratorPrototype% object's 'next' routine * * See also: * ECMA-262 v6, 23.1.5.2.1 * ECMA-262 v6, 23.2.5.2.1 * * Note: * Returned value must be freed with ecma_free_value. * * @return iterator result object, if success * error - otherwise */ ecma_value_t ecma_op_container_iterator_next (ecma_value_t this_val, /**< this argument */ ecma_pseudo_array_type_t iterator_type) /**< type of the iterator */ { if (!ecma_is_value_object (this_val)) { return ecma_raise_type_error (ECMA_ERR_MSG ("Argument 'this' is not an object.")); } ecma_object_t *obj_p = ecma_get_object_from_value (this_val); ecma_extended_object_t *ext_obj_p = (ecma_extended_object_t *) obj_p; if (ecma_get_object_type (obj_p) != ECMA_OBJECT_TYPE_PSEUDO_ARRAY || ext_obj_p->u.pseudo_array.type != iterator_type) { return ecma_raise_type_error (ECMA_ERR_MSG ("Argument 'this' is not an iterator.")); } ecma_value_t iterated_value = ext_obj_p->u.pseudo_array.u2.iterated_value; if (ecma_is_value_empty (iterated_value)) { return ecma_create_iter_result_object (ECMA_VALUE_UNDEFINED, ECMA_VALUE_TRUE); } ecma_extended_object_t *map_object_p = (ecma_extended_object_t *) (ecma_get_object_from_value (iterated_value)); lit_magic_string_id_t lit_id = map_object_p->u.class_prop.class_id; ecma_collection_t *container_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_collection_t, map_object_p->u.class_prop.u.value); uint32_t entry_count = ECMA_CONTAINER_ENTRY_COUNT (container_p); uint32_t index = ecma_op_iterator_get_index (obj_p); if (index == entry_count) { ext_obj_p->u.pseudo_array.u2.iterated_value = ECMA_VALUE_EMPTY; return ecma_create_iter_result_object (ECMA_VALUE_UNDEFINED, ECMA_VALUE_TRUE); } uint8_t entry_size = ecma_op_container_entry_size (lit_id); uint8_t iterator_kind = ext_obj_p->u.pseudo_array.extra_info; ecma_value_t *start_p = ECMA_CONTAINER_START (container_p); ecma_value_t ret_value = ECMA_VALUE_UNDEFINED; for (uint32_t i = index; i < entry_count; i += entry_size) { ecma_value_t *entry_p = start_p + i; if (ecma_is_value_empty (*entry_p)) { if (i == (entry_count - entry_size)) { ret_value = ecma_create_iter_result_object (ECMA_VALUE_UNDEFINED, ECMA_VALUE_TRUE); break; } continue; } ecma_op_iterator_set_index (obj_p, i + entry_size); ecma_value_t key_arg = *entry_p; ecma_value_t value_arg = ecma_op_container_get_value (entry_p, lit_id); if (iterator_kind == ECMA_ITERATOR_KEYS) { ret_value = ecma_create_iter_result_object (key_arg, ECMA_VALUE_FALSE); } else if (iterator_kind == ECMA_ITERATOR_VALUES) { ret_value = ecma_create_iter_result_object (value_arg, ECMA_VALUE_FALSE); } else { JERRY_ASSERT (iterator_kind == ECMA_ITERATOR_KEYS_VALUES); ecma_value_t entry_array_value; entry_array_value = ecma_create_array_from_iter_element (value_arg, key_arg); ret_value = ecma_create_iter_result_object (entry_array_value, ECMA_VALUE_FALSE); ecma_free_value (entry_array_value); } break; } return ret_value; } /* ecma_op_container_iterator_next */ #endif /* ENABLED (JERRY_ES2015) */ /** * @} * @} */ #endif /* ENABLED (JERRY_ES2015_BUILTIN_CONTAINER) */
./CrossVul/dataset_final_sorted/CWE-119/c/good_4054_0
crossvul-cpp_data_bad_2129_0
/* * HID driver for Logitech Unifying receivers * * Copyright (c) 2011 Logitech */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include <linux/usb.h> #include <asm/unaligned.h> #include "hid-ids.h" #include "hid-logitech-dj.h" /* Keyboard descriptor (1) */ static const char kbd_descriptor[] = { 0x05, 0x01, /* USAGE_PAGE (generic Desktop) */ 0x09, 0x06, /* USAGE (Keyboard) */ 0xA1, 0x01, /* COLLECTION (Application) */ 0x85, 0x01, /* REPORT_ID (1) */ 0x95, 0x08, /* REPORT_COUNT (8) */ 0x75, 0x01, /* REPORT_SIZE (1) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x25, 0x01, /* LOGICAL_MAXIMUM (1) */ 0x05, 0x07, /* USAGE_PAGE (Keyboard) */ 0x19, 0xE0, /* USAGE_MINIMUM (Left Control) */ 0x29, 0xE7, /* USAGE_MAXIMUM (Right GUI) */ 0x81, 0x02, /* INPUT (Data,Var,Abs) */ 0x95, 0x06, /* REPORT_COUNT (6) */ 0x75, 0x08, /* REPORT_SIZE (8) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x26, 0xFF, 0x00, /* LOGICAL_MAXIMUM (255) */ 0x05, 0x07, /* USAGE_PAGE (Keyboard) */ 0x19, 0x00, /* USAGE_MINIMUM (no event) */ 0x2A, 0xFF, 0x00, /* USAGE_MAXIMUM (reserved) */ 0x81, 0x00, /* INPUT (Data,Ary,Abs) */ 0x85, 0x0e, /* REPORT_ID (14) */ 0x05, 0x08, /* USAGE PAGE (LED page) */ 0x95, 0x05, /* REPORT COUNT (5) */ 0x75, 0x01, /* REPORT SIZE (1) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x25, 0x01, /* LOGICAL_MAXIMUM (1) */ 0x19, 0x01, /* USAGE MINIMUM (1) */ 0x29, 0x05, /* USAGE MAXIMUM (5) */ 0x91, 0x02, /* OUTPUT (Data, Variable, Absolute) */ 0x95, 0x01, /* REPORT COUNT (1) */ 0x75, 0x03, /* REPORT SIZE (3) */ 0x91, 0x01, /* OUTPUT (Constant) */ 0xC0 }; /* Mouse descriptor (2) */ static const char mse_descriptor[] = { 0x05, 0x01, /* USAGE_PAGE (Generic Desktop) */ 0x09, 0x02, /* USAGE (Mouse) */ 0xA1, 0x01, /* COLLECTION (Application) */ 0x85, 0x02, /* REPORT_ID = 2 */ 0x09, 0x01, /* USAGE (pointer) */ 0xA1, 0x00, /* COLLECTION (physical) */ 0x05, 0x09, /* USAGE_PAGE (buttons) */ 0x19, 0x01, /* USAGE_MIN (1) */ 0x29, 0x10, /* USAGE_MAX (16) */ 0x15, 0x00, /* LOGICAL_MIN (0) */ 0x25, 0x01, /* LOGICAL_MAX (1) */ 0x95, 0x10, /* REPORT_COUNT (16) */ 0x75, 0x01, /* REPORT_SIZE (1) */ 0x81, 0x02, /* INPUT (data var abs) */ 0x05, 0x01, /* USAGE_PAGE (generic desktop) */ 0x16, 0x01, 0xF8, /* LOGICAL_MIN (-2047) */ 0x26, 0xFF, 0x07, /* LOGICAL_MAX (2047) */ 0x75, 0x0C, /* REPORT_SIZE (12) */ 0x95, 0x02, /* REPORT_COUNT (2) */ 0x09, 0x30, /* USAGE (X) */ 0x09, 0x31, /* USAGE (Y) */ 0x81, 0x06, /* INPUT */ 0x15, 0x81, /* LOGICAL_MIN (-127) */ 0x25, 0x7F, /* LOGICAL_MAX (127) */ 0x75, 0x08, /* REPORT_SIZE (8) */ 0x95, 0x01, /* REPORT_COUNT (1) */ 0x09, 0x38, /* USAGE (wheel) */ 0x81, 0x06, /* INPUT */ 0x05, 0x0C, /* USAGE_PAGE(consumer) */ 0x0A, 0x38, 0x02, /* USAGE(AC Pan) */ 0x95, 0x01, /* REPORT_COUNT (1) */ 0x81, 0x06, /* INPUT */ 0xC0, /* END_COLLECTION */ 0xC0, /* END_COLLECTION */ }; /* Consumer Control descriptor (3) */ static const char consumer_descriptor[] = { 0x05, 0x0C, /* USAGE_PAGE (Consumer Devices) */ 0x09, 0x01, /* USAGE (Consumer Control) */ 0xA1, 0x01, /* COLLECTION (Application) */ 0x85, 0x03, /* REPORT_ID = 3 */ 0x75, 0x10, /* REPORT_SIZE (16) */ 0x95, 0x02, /* REPORT_COUNT (2) */ 0x15, 0x01, /* LOGICAL_MIN (1) */ 0x26, 0x8C, 0x02, /* LOGICAL_MAX (652) */ 0x19, 0x01, /* USAGE_MIN (1) */ 0x2A, 0x8C, 0x02, /* USAGE_MAX (652) */ 0x81, 0x00, /* INPUT (Data Ary Abs) */ 0xC0, /* END_COLLECTION */ }; /* */ /* System control descriptor (4) */ static const char syscontrol_descriptor[] = { 0x05, 0x01, /* USAGE_PAGE (Generic Desktop) */ 0x09, 0x80, /* USAGE (System Control) */ 0xA1, 0x01, /* COLLECTION (Application) */ 0x85, 0x04, /* REPORT_ID = 4 */ 0x75, 0x02, /* REPORT_SIZE (2) */ 0x95, 0x01, /* REPORT_COUNT (1) */ 0x15, 0x01, /* LOGICAL_MIN (1) */ 0x25, 0x03, /* LOGICAL_MAX (3) */ 0x09, 0x82, /* USAGE (System Sleep) */ 0x09, 0x81, /* USAGE (System Power Down) */ 0x09, 0x83, /* USAGE (System Wake Up) */ 0x81, 0x60, /* INPUT (Data Ary Abs NPrf Null) */ 0x75, 0x06, /* REPORT_SIZE (6) */ 0x81, 0x03, /* INPUT (Cnst Var Abs) */ 0xC0, /* END_COLLECTION */ }; /* Media descriptor (8) */ static const char media_descriptor[] = { 0x06, 0xbc, 0xff, /* Usage Page 0xffbc */ 0x09, 0x88, /* Usage 0x0088 */ 0xa1, 0x01, /* BeginCollection */ 0x85, 0x08, /* Report ID 8 */ 0x19, 0x01, /* Usage Min 0x0001 */ 0x29, 0xff, /* Usage Max 0x00ff */ 0x15, 0x01, /* Logical Min 1 */ 0x26, 0xff, 0x00, /* Logical Max 255 */ 0x75, 0x08, /* Report Size 8 */ 0x95, 0x01, /* Report Count 1 */ 0x81, 0x00, /* Input */ 0xc0, /* EndCollection */ }; /* */ /* Maximum size of all defined hid reports in bytes (including report id) */ #define MAX_REPORT_SIZE 8 /* Make sure all descriptors are present here */ #define MAX_RDESC_SIZE \ (sizeof(kbd_descriptor) + \ sizeof(mse_descriptor) + \ sizeof(consumer_descriptor) + \ sizeof(syscontrol_descriptor) + \ sizeof(media_descriptor)) /* Number of possible hid report types that can be created by this driver. * * Right now, RF report types have the same report types (or report id's) * than the hid report created from those RF reports. In the future * this doesnt have to be true. * * For instance, RF report type 0x01 which has a size of 8 bytes, corresponds * to hid report id 0x01, this is standard keyboard. Same thing applies to mice * reports and consumer control, etc. If a new RF report is created, it doesn't * has to have the same report id as its corresponding hid report, so an * translation may have to take place for future report types. */ #define NUMBER_OF_HID_REPORTS 32 static const u8 hid_reportid_size_map[NUMBER_OF_HID_REPORTS] = { [1] = 8, /* Standard keyboard */ [2] = 8, /* Standard mouse */ [3] = 5, /* Consumer control */ [4] = 2, /* System control */ [8] = 2, /* Media Center */ }; #define LOGITECH_DJ_INTERFACE_NUMBER 0x02 static struct hid_ll_driver logi_dj_ll_driver; static int logi_dj_recv_query_paired_devices(struct dj_receiver_dev *djrcv_dev); static void logi_dj_recv_destroy_djhid_device(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* Called in delayed work context */ struct dj_device *dj_dev; unsigned long flags; spin_lock_irqsave(&djrcv_dev->lock, flags); dj_dev = djrcv_dev->paired_dj_devices[dj_report->device_index]; djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL; spin_unlock_irqrestore(&djrcv_dev->lock, flags); if (dj_dev != NULL) { hid_destroy_device(dj_dev->hdev); kfree(dj_dev); } else { dev_err(&djrcv_dev->hdev->dev, "%s: can't destroy a NULL device\n", __func__); } } static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* Called in delayed work context */ struct hid_device *djrcv_hdev = djrcv_dev->hdev; struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent); struct usb_device *usbdev = interface_to_usbdev(intf); struct hid_device *dj_hiddev; struct dj_device *dj_dev; /* Device index goes from 1 to 6, we need 3 bytes to store the * semicolon, the index, and a null terminator */ unsigned char tmpstr[3]; if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] & SPFUNCTION_DEVICE_LIST_EMPTY) { dbg_hid("%s: device list is empty\n", __func__); djrcv_dev->querying_devices = false; return; } if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) || (dj_report->device_index > DJ_DEVICE_INDEX_MAX)) { dev_err(&djrcv_hdev->dev, "%s: invalid device index:%d\n", __func__, dj_report->device_index); return; } if (djrcv_dev->paired_dj_devices[dj_report->device_index]) { /* The device is already known. No need to reallocate it. */ dbg_hid("%s: device is already known\n", __func__); return; } dj_hiddev = hid_allocate_device(); if (IS_ERR(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n", __func__); return; } dj_hiddev->ll_driver = &logi_dj_ll_driver; dj_hiddev->dev.parent = &djrcv_hdev->dev; dj_hiddev->bus = BUS_USB; dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor); dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct); snprintf(dj_hiddev->name, sizeof(dj_hiddev->name), "Logitech Unifying Device. Wireless PID:%02x%02x", dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB], dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]); usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys)); snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index); strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys)); dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL); if (!dj_dev) { dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n", __func__); goto dj_device_allocate_fail; } dj_dev->reports_supported = get_unaligned_le32( dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE); dj_dev->hdev = dj_hiddev; dj_dev->dj_receiver_dev = djrcv_dev; dj_dev->device_index = dj_report->device_index; dj_hiddev->driver_data = dj_dev; djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev; if (hid_add_device(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n", __func__); goto hid_add_device_fail; } return; hid_add_device_fail: djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL; kfree(dj_dev); dj_device_allocate_fail: hid_destroy_device(dj_hiddev); } static void delayedwork_callback(struct work_struct *work) { struct dj_receiver_dev *djrcv_dev = container_of(work, struct dj_receiver_dev, work); struct dj_report dj_report; unsigned long flags; int count; int retval; dbg_hid("%s\n", __func__); spin_lock_irqsave(&djrcv_dev->lock, flags); count = kfifo_out(&djrcv_dev->notif_fifo, &dj_report, sizeof(struct dj_report)); if (count != sizeof(struct dj_report)) { dev_err(&djrcv_dev->hdev->dev, "%s: workitem triggered without " "notifications available\n", __func__); spin_unlock_irqrestore(&djrcv_dev->lock, flags); return; } if (!kfifo_is_empty(&djrcv_dev->notif_fifo)) { if (schedule_work(&djrcv_dev->work) == 0) { dbg_hid("%s: did not schedule the work item, was " "already queued\n", __func__); } } spin_unlock_irqrestore(&djrcv_dev->lock, flags); switch (dj_report.report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: logi_dj_recv_add_djhid_device(djrcv_dev, &dj_report); break; case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_destroy_djhid_device(djrcv_dev, &dj_report); break; default: /* A normal report (i. e. not belonging to a pair/unpair notification) * arriving here, means that the report arrived but we did not have a * paired dj_device associated to the report's device_index, this * means that the original "device paired" notification corresponding * to this dj_device never arrived to this driver. The reason is that * hid-core discards all packets coming from a device while probe() is * executing. */ if (!djrcv_dev->paired_dj_devices[dj_report.device_index]) { /* ok, we don't know the device, just re-ask the * receiver for the list of connected devices. */ retval = logi_dj_recv_query_paired_devices(djrcv_dev); if (!retval) { /* everything went fine, so just leave */ break; } dev_err(&djrcv_dev->hdev->dev, "%s:logi_dj_recv_query_paired_devices " "error:%d\n", __func__, retval); } dbg_hid("%s: unexpected report type\n", __func__); } } static void logi_dj_recv_queue_notification(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* We are called from atomic context (tasklet && djrcv->lock held) */ kfifo_in(&djrcv_dev->notif_fifo, dj_report, sizeof(struct dj_report)); if (schedule_work(&djrcv_dev->work) == 0) { dbg_hid("%s: did not schedule the work item, was already " "queued\n", __func__); } } static void logi_dj_recv_forward_null_report(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* We are called from atomic context (tasklet && djrcv->lock held) */ unsigned int i; u8 reportbuffer[MAX_REPORT_SIZE]; struct dj_device *djdev; djdev = djrcv_dev->paired_dj_devices[dj_report->device_index]; if (!djdev) { dbg_hid("djrcv_dev->paired_dj_devices[dj_report->device_index]" " is NULL, index %d\n", dj_report->device_index); kfifo_in(&djrcv_dev->notif_fifo, dj_report, sizeof(struct dj_report)); if (schedule_work(&djrcv_dev->work) == 0) { dbg_hid("%s: did not schedule the work item, was already " "queued\n", __func__); } return; } memset(reportbuffer, 0, sizeof(reportbuffer)); for (i = 0; i < NUMBER_OF_HID_REPORTS; i++) { if (djdev->reports_supported & (1 << i)) { reportbuffer[0] = i; if (hid_input_report(djdev->hdev, HID_INPUT_REPORT, reportbuffer, hid_reportid_size_map[i], 1)) { dbg_hid("hid_input_report error sending null " "report\n"); } } } } static void logi_dj_recv_forward_report(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* We are called from atomic context (tasklet && djrcv->lock held) */ struct dj_device *dj_device; dj_device = djrcv_dev->paired_dj_devices[dj_report->device_index]; if (dj_device == NULL) { dbg_hid("djrcv_dev->paired_dj_devices[dj_report->device_index]" " is NULL, index %d\n", dj_report->device_index); kfifo_in(&djrcv_dev->notif_fifo, dj_report, sizeof(struct dj_report)); if (schedule_work(&djrcv_dev->work) == 0) { dbg_hid("%s: did not schedule the work item, was already " "queued\n", __func__); } return; } if ((dj_report->report_type > ARRAY_SIZE(hid_reportid_size_map) - 1) || (hid_reportid_size_map[dj_report->report_type] == 0)) { dbg_hid("invalid report type:%x\n", dj_report->report_type); return; } if (hid_input_report(dj_device->hdev, HID_INPUT_REPORT, &dj_report->report_type, hid_reportid_size_map[dj_report->report_type], 1)) { dbg_hid("hid_input_report error\n"); } } static int logi_dj_recv_send_report(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { struct hid_device *hdev = djrcv_dev->hdev; struct hid_report *report; struct hid_report_enum *output_report_enum; u8 *data = (u8 *)(&dj_report->device_index); unsigned int i; output_report_enum = &hdev->report_enum[HID_OUTPUT_REPORT]; report = output_report_enum->report_id_hash[REPORT_ID_DJ_SHORT]; if (!report) { dev_err(&hdev->dev, "%s: unable to find dj report\n", __func__); return -ENODEV; } for (i = 0; i < DJREPORT_SHORT_LENGTH - 1; i++) report->field[0]->value[i] = data[i]; hid_hw_request(hdev, report, HID_REQ_SET_REPORT); return 0; } static int logi_dj_recv_query_paired_devices(struct dj_receiver_dev *djrcv_dev) { struct dj_report *dj_report; int retval; /* no need to protect djrcv_dev->querying_devices */ if (djrcv_dev->querying_devices) return 0; dj_report = kzalloc(sizeof(struct dj_report), GFP_KERNEL); if (!dj_report) return -ENOMEM; dj_report->report_id = REPORT_ID_DJ_SHORT; dj_report->device_index = 0xFF; dj_report->report_type = REPORT_TYPE_CMD_GET_PAIRED_DEVICES; retval = logi_dj_recv_send_report(djrcv_dev, dj_report); kfree(dj_report); return retval; } static int logi_dj_recv_switch_to_dj_mode(struct dj_receiver_dev *djrcv_dev, unsigned timeout) { struct dj_report *dj_report; int retval; dj_report = kzalloc(sizeof(struct dj_report), GFP_KERNEL); if (!dj_report) return -ENOMEM; dj_report->report_id = REPORT_ID_DJ_SHORT; dj_report->device_index = 0xFF; dj_report->report_type = REPORT_TYPE_CMD_SWITCH; dj_report->report_params[CMD_SWITCH_PARAM_DEVBITFIELD] = 0x3F; dj_report->report_params[CMD_SWITCH_PARAM_TIMEOUT_SECONDS] = (u8)timeout; retval = logi_dj_recv_send_report(djrcv_dev, dj_report); kfree(dj_report); /* * Ugly sleep to work around a USB 3.0 bug when the receiver is still * processing the "switch-to-dj" command while we send an other command. * 50 msec should gives enough time to the receiver to be ready. */ msleep(50); return retval; } static int logi_dj_ll_open(struct hid_device *hid) { dbg_hid("%s:%s\n", __func__, hid->phys); return 0; } static void logi_dj_ll_close(struct hid_device *hid) { dbg_hid("%s:%s\n", __func__, hid->phys); } static int logi_dj_ll_raw_request(struct hid_device *hid, unsigned char reportnum, __u8 *buf, size_t count, unsigned char report_type, int reqtype) { struct dj_device *djdev = hid->driver_data; struct dj_receiver_dev *djrcv_dev = djdev->dj_receiver_dev; u8 *out_buf; int ret; if (buf[0] != REPORT_TYPE_LEDS) return -EINVAL; out_buf = kzalloc(DJREPORT_SHORT_LENGTH, GFP_ATOMIC); if (!out_buf) return -ENOMEM; if (count > DJREPORT_SHORT_LENGTH - 2) count = DJREPORT_SHORT_LENGTH - 2; out_buf[0] = REPORT_ID_DJ_SHORT; out_buf[1] = djdev->device_index; memcpy(out_buf + 2, buf, count); ret = hid_hw_raw_request(djrcv_dev->hdev, out_buf[0], out_buf, DJREPORT_SHORT_LENGTH, report_type, reqtype); kfree(out_buf); return ret; } static void rdcat(char *rdesc, unsigned int *rsize, const char *data, unsigned int size) { memcpy(rdesc + *rsize, data, size); *rsize += size; } static int logi_dj_ll_parse(struct hid_device *hid) { struct dj_device *djdev = hid->driver_data; unsigned int rsize = 0; char *rdesc; int retval; dbg_hid("%s\n", __func__); djdev->hdev->version = 0x0111; djdev->hdev->country = 0x00; rdesc = kmalloc(MAX_RDESC_SIZE, GFP_KERNEL); if (!rdesc) return -ENOMEM; if (djdev->reports_supported & STD_KEYBOARD) { dbg_hid("%s: sending a kbd descriptor, reports_supported: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, kbd_descriptor, sizeof(kbd_descriptor)); } if (djdev->reports_supported & STD_MOUSE) { dbg_hid("%s: sending a mouse descriptor, reports_supported: " "%x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, mse_descriptor, sizeof(mse_descriptor)); } if (djdev->reports_supported & MULTIMEDIA) { dbg_hid("%s: sending a multimedia report descriptor: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, consumer_descriptor, sizeof(consumer_descriptor)); } if (djdev->reports_supported & POWER_KEYS) { dbg_hid("%s: sending a power keys report descriptor: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, syscontrol_descriptor, sizeof(syscontrol_descriptor)); } if (djdev->reports_supported & MEDIA_CENTER) { dbg_hid("%s: sending a media center report descriptor: %x\n", __func__, djdev->reports_supported); rdcat(rdesc, &rsize, media_descriptor, sizeof(media_descriptor)); } if (djdev->reports_supported & KBD_LEDS) { dbg_hid("%s: need to send kbd leds report descriptor: %x\n", __func__, djdev->reports_supported); } retval = hid_parse_report(hid, rdesc, rsize); kfree(rdesc); return retval; } static int logi_dj_ll_start(struct hid_device *hid) { dbg_hid("%s\n", __func__); return 0; } static void logi_dj_ll_stop(struct hid_device *hid) { dbg_hid("%s\n", __func__); } static struct hid_ll_driver logi_dj_ll_driver = { .parse = logi_dj_ll_parse, .start = logi_dj_ll_start, .stop = logi_dj_ll_stop, .open = logi_dj_ll_open, .close = logi_dj_ll_close, .raw_request = logi_dj_ll_raw_request, }; static int logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; } static int logi_dj_probe(struct hid_device *hdev, const struct hid_device_id *id) { struct usb_interface *intf = to_usb_interface(hdev->dev.parent); struct dj_receiver_dev *djrcv_dev; int retval; if (is_dj_device((struct dj_device *)hdev->driver_data)) return -ENODEV; dbg_hid("%s called for ifnum %d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); /* Ignore interfaces 0 and 1, they will not carry any data, dont create * any hid_device for them */ if (intf->cur_altsetting->desc.bInterfaceNumber != LOGITECH_DJ_INTERFACE_NUMBER) { dbg_hid("%s: ignoring ifnum %d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); return -ENODEV; } /* Treat interface 2 */ djrcv_dev = kzalloc(sizeof(struct dj_receiver_dev), GFP_KERNEL); if (!djrcv_dev) { dev_err(&hdev->dev, "%s:failed allocating dj_receiver_dev\n", __func__); return -ENOMEM; } djrcv_dev->hdev = hdev; INIT_WORK(&djrcv_dev->work, delayedwork_callback); spin_lock_init(&djrcv_dev->lock); if (kfifo_alloc(&djrcv_dev->notif_fifo, DJ_MAX_NUMBER_NOTIFICATIONS * sizeof(struct dj_report), GFP_KERNEL)) { dev_err(&hdev->dev, "%s:failed allocating notif_fifo\n", __func__); kfree(djrcv_dev); return -ENOMEM; } hid_set_drvdata(hdev, djrcv_dev); /* Call to usbhid to fetch the HID descriptors of interface 2 and * subsequently call to the hid/hid-core to parse the fetched * descriptors, this will in turn create the hidraw and hiddev nodes * for interface 2 of the receiver */ retval = hid_parse(hdev); if (retval) { dev_err(&hdev->dev, "%s:parse of interface 2 failed\n", __func__); goto hid_parse_fail; } if (!hid_validate_values(hdev, HID_OUTPUT_REPORT, REPORT_ID_DJ_SHORT, 0, DJREPORT_SHORT_LENGTH - 1)) { retval = -ENODEV; goto hid_parse_fail; } /* Starts the usb device and connects to upper interfaces hiddev and * hidraw */ retval = hid_hw_start(hdev, HID_CONNECT_DEFAULT); if (retval) { dev_err(&hdev->dev, "%s:hid_hw_start returned error\n", __func__); goto hid_hw_start_fail; } retval = logi_dj_recv_switch_to_dj_mode(djrcv_dev, 0); if (retval < 0) { dev_err(&hdev->dev, "%s:logi_dj_recv_switch_to_dj_mode returned error:%d\n", __func__, retval); goto switch_to_dj_mode_fail; } /* This is enabling the polling urb on the IN endpoint */ retval = hid_hw_open(hdev); if (retval < 0) { dev_err(&hdev->dev, "%s:hid_hw_open returned error:%d\n", __func__, retval); goto llopen_failed; } /* Allow incoming packets to arrive: */ hid_device_io_start(hdev); retval = logi_dj_recv_query_paired_devices(djrcv_dev); if (retval < 0) { dev_err(&hdev->dev, "%s:logi_dj_recv_query_paired_devices " "error:%d\n", __func__, retval); goto logi_dj_recv_query_paired_devices_failed; } return retval; logi_dj_recv_query_paired_devices_failed: hid_hw_close(hdev); llopen_failed: switch_to_dj_mode_fail: hid_hw_stop(hdev); hid_hw_start_fail: hid_parse_fail: kfifo_free(&djrcv_dev->notif_fifo); kfree(djrcv_dev); hid_set_drvdata(hdev, NULL); return retval; } #ifdef CONFIG_PM static int logi_dj_reset_resume(struct hid_device *hdev) { int retval; struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); retval = logi_dj_recv_switch_to_dj_mode(djrcv_dev, 0); if (retval < 0) { dev_err(&hdev->dev, "%s:logi_dj_recv_switch_to_dj_mode returned error:%d\n", __func__, retval); } return 0; } #endif static void logi_dj_remove(struct hid_device *hdev) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_device *dj_dev; int i; dbg_hid("%s\n", __func__); cancel_work_sync(&djrcv_dev->work); hid_hw_close(hdev); hid_hw_stop(hdev); /* I suppose that at this point the only context that can access * the djrecv_data is this thread as the work item is guaranteed to * have finished and no more raw_event callbacks should arrive after * the remove callback was triggered so no locks are put around the * code below */ for (i = 0; i < (DJ_MAX_PAIRED_DEVICES + DJ_DEVICE_INDEX_MIN); i++) { dj_dev = djrcv_dev->paired_dj_devices[i]; if (dj_dev != NULL) { hid_destroy_device(dj_dev->hdev); kfree(dj_dev); djrcv_dev->paired_dj_devices[i] = NULL; } } kfifo_free(&djrcv_dev->notif_fifo); kfree(djrcv_dev); hid_set_drvdata(hdev, NULL); } static int logi_djdevice_probe(struct hid_device *hdev, const struct hid_device_id *id) { int ret; struct dj_device *dj_dev = hdev->driver_data; if (!is_dj_device(dj_dev)) return -ENODEV; ret = hid_parse(hdev); if (!ret) ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); return ret; } static const struct hid_device_id logi_dj_receivers[] = { {HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER)}, {HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER_2)}, {} }; MODULE_DEVICE_TABLE(hid, logi_dj_receivers); static struct hid_driver logi_djreceiver_driver = { .name = "logitech-djreceiver", .id_table = logi_dj_receivers, .probe = logi_dj_probe, .remove = logi_dj_remove, .raw_event = logi_dj_raw_event, #ifdef CONFIG_PM .reset_resume = logi_dj_reset_resume, #endif }; static const struct hid_device_id logi_dj_devices[] = { {HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER)}, {HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER_2)}, {} }; static struct hid_driver logi_djdevice_driver = { .name = "logitech-djdevice", .id_table = logi_dj_devices, .probe = logi_djdevice_probe, }; static int __init logi_dj_init(void) { int retval; dbg_hid("Logitech-DJ:%s\n", __func__); retval = hid_register_driver(&logi_djreceiver_driver); if (retval) return retval; retval = hid_register_driver(&logi_djdevice_driver); if (retval) hid_unregister_driver(&logi_djreceiver_driver); return retval; } static void __exit logi_dj_exit(void) { dbg_hid("Logitech-DJ:%s\n", __func__); hid_unregister_driver(&logi_djdevice_driver); hid_unregister_driver(&logi_djreceiver_driver); } module_init(logi_dj_init); module_exit(logi_dj_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Logitech"); MODULE_AUTHOR("Nestor Lopez Casado"); MODULE_AUTHOR("nlopezcasad@logitech.com");
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2129_0
crossvul-cpp_data_good_3116_0
/* * atusb.c - Driver for the ATUSB IEEE 802.15.4 dongle * * Written 2013 by Werner Almesberger <werner@almesberger.net> * * Copyright (c) 2015 - 2016 Stefan Schmidt <stefan@datenfreihafen.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 2 * * Based on at86rf230.c and spi_atusb.c. * at86rf230.c is * Copyright (C) 2009 Siemens AG * Written by: Dmitry Eremin-Solenikov <dmitry.baryshkov@siemens.com> * * spi_atusb.c is * Copyright (c) 2011 Richard Sharpe <realrichardsharpe@gmail.com> * Copyright (c) 2011 Stefan Schmidt <stefan@datenfreihafen.org> * Copyright (c) 2011 Werner Almesberger <werner@almesberger.net> * * USB initialization is * Copyright (c) 2013 Alexander Aring <alex.aring@gmail.com> */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/jiffies.h> #include <linux/usb.h> #include <linux/skbuff.h> #include <net/cfg802154.h> #include <net/mac802154.h> #include "at86rf230.h" #include "atusb.h" #define ATUSB_JEDEC_ATMEL 0x1f /* JEDEC manufacturer ID */ #define ATUSB_NUM_RX_URBS 4 /* allow for a bit of local latency */ #define ATUSB_ALLOC_DELAY_MS 100 /* delay after failed allocation */ #define ATUSB_TX_TIMEOUT_MS 200 /* on the air timeout */ struct atusb { struct ieee802154_hw *hw; struct usb_device *usb_dev; int shutdown; /* non-zero if shutting down */ int err; /* set by first error */ /* RX variables */ struct delayed_work work; /* memory allocations */ struct usb_anchor idle_urbs; /* URBs waiting to be submitted */ struct usb_anchor rx_urbs; /* URBs waiting for reception */ /* TX variables */ struct usb_ctrlrequest tx_dr; struct urb *tx_urb; struct sk_buff *tx_skb; uint8_t tx_ack_seq; /* current TX ACK sequence number */ /* Firmware variable */ unsigned char fw_ver_maj; /* Firmware major version number */ unsigned char fw_ver_min; /* Firmware minor version number */ unsigned char fw_hw_type; /* Firmware hardware type */ }; /* ----- USB commands without data ----------------------------------------- */ /* To reduce the number of error checks in the code, we record the first error * in atusb->err and reject all subsequent requests until the error is cleared. */ static int atusb_control_msg(struct atusb *atusb, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout) { struct usb_device *usb_dev = atusb->usb_dev; int ret; if (atusb->err) return atusb->err; ret = usb_control_msg(usb_dev, pipe, request, requesttype, value, index, data, size, timeout); if (ret < 0) { atusb->err = ret; dev_err(&usb_dev->dev, "atusb_control_msg: req 0x%02x val 0x%x idx 0x%x, error %d\n", request, value, index, ret); } return ret; } static int atusb_command(struct atusb *atusb, uint8_t cmd, uint8_t arg) { struct usb_device *usb_dev = atusb->usb_dev; dev_dbg(&usb_dev->dev, "atusb_command: cmd = 0x%x\n", cmd); return atusb_control_msg(atusb, usb_sndctrlpipe(usb_dev, 0), cmd, ATUSB_REQ_TO_DEV, arg, 0, NULL, 0, 1000); } static int atusb_write_reg(struct atusb *atusb, uint8_t reg, uint8_t value) { struct usb_device *usb_dev = atusb->usb_dev; dev_dbg(&usb_dev->dev, "atusb_write_reg: 0x%02x <- 0x%02x\n", reg, value); return atusb_control_msg(atusb, usb_sndctrlpipe(usb_dev, 0), ATUSB_REG_WRITE, ATUSB_REQ_TO_DEV, value, reg, NULL, 0, 1000); } static int atusb_read_reg(struct atusb *atusb, uint8_t reg) { struct usb_device *usb_dev = atusb->usb_dev; int ret; uint8_t *buffer; uint8_t value; buffer = kmalloc(1, GFP_KERNEL); if (!buffer) return -ENOMEM; dev_dbg(&usb_dev->dev, "atusb: reg = 0x%x\n", reg); ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_REG_READ, ATUSB_REQ_FROM_DEV, 0, reg, buffer, 1, 1000); if (ret >= 0) { value = buffer[0]; kfree(buffer); return value; } else { kfree(buffer); return ret; } } static int atusb_write_subreg(struct atusb *atusb, uint8_t reg, uint8_t mask, uint8_t shift, uint8_t value) { struct usb_device *usb_dev = atusb->usb_dev; uint8_t orig, tmp; int ret = 0; dev_dbg(&usb_dev->dev, "atusb_write_subreg: 0x%02x <- 0x%02x\n", reg, value); orig = atusb_read_reg(atusb, reg); /* Write the value only into that part of the register which is allowed * by the mask. All other bits stay as before. */ tmp = orig & ~mask; tmp |= (value << shift) & mask; if (tmp != orig) ret = atusb_write_reg(atusb, reg, tmp); return ret; } static int atusb_get_and_clear_error(struct atusb *atusb) { int err = atusb->err; atusb->err = 0; return err; } /* ----- skb allocation ---------------------------------------------------- */ #define MAX_PSDU 127 #define MAX_RX_XFER (1 + MAX_PSDU + 2 + 1) /* PHR+PSDU+CRC+LQI */ #define SKB_ATUSB(skb) (*(struct atusb **)(skb)->cb) static void atusb_in(struct urb *urb); static int atusb_submit_rx_urb(struct atusb *atusb, struct urb *urb) { struct usb_device *usb_dev = atusb->usb_dev; struct sk_buff *skb = urb->context; int ret; if (!skb) { skb = alloc_skb(MAX_RX_XFER, GFP_KERNEL); if (!skb) { dev_warn_ratelimited(&usb_dev->dev, "atusb_in: can't allocate skb\n"); return -ENOMEM; } skb_put(skb, MAX_RX_XFER); SKB_ATUSB(skb) = atusb; } usb_fill_bulk_urb(urb, usb_dev, usb_rcvbulkpipe(usb_dev, 1), skb->data, MAX_RX_XFER, atusb_in, skb); usb_anchor_urb(urb, &atusb->rx_urbs); ret = usb_submit_urb(urb, GFP_KERNEL); if (ret) { usb_unanchor_urb(urb); kfree_skb(skb); urb->context = NULL; } return ret; } static void atusb_work_urbs(struct work_struct *work) { struct atusb *atusb = container_of(to_delayed_work(work), struct atusb, work); struct usb_device *usb_dev = atusb->usb_dev; struct urb *urb; int ret; if (atusb->shutdown) return; do { urb = usb_get_from_anchor(&atusb->idle_urbs); if (!urb) return; ret = atusb_submit_rx_urb(atusb, urb); } while (!ret); usb_anchor_urb(urb, &atusb->idle_urbs); dev_warn_ratelimited(&usb_dev->dev, "atusb_in: can't allocate/submit URB (%d)\n", ret); schedule_delayed_work(&atusb->work, msecs_to_jiffies(ATUSB_ALLOC_DELAY_MS) + 1); } /* ----- Asynchronous USB -------------------------------------------------- */ static void atusb_tx_done(struct atusb *atusb, uint8_t seq) { struct usb_device *usb_dev = atusb->usb_dev; uint8_t expect = atusb->tx_ack_seq; dev_dbg(&usb_dev->dev, "atusb_tx_done (0x%02x/0x%02x)\n", seq, expect); if (seq == expect) { /* TODO check for ifs handling in firmware */ ieee802154_xmit_complete(atusb->hw, atusb->tx_skb, false); } else { /* TODO I experience this case when atusb has a tx complete * irq before probing, we should fix the firmware it's an * unlikely case now that seq == expect is then true, but can * happen and fail with a tx_skb = NULL; */ ieee802154_wake_queue(atusb->hw); if (atusb->tx_skb) dev_kfree_skb_irq(atusb->tx_skb); } } static void atusb_in_good(struct urb *urb) { struct usb_device *usb_dev = urb->dev; struct sk_buff *skb = urb->context; struct atusb *atusb = SKB_ATUSB(skb); uint8_t len, lqi; if (!urb->actual_length) { dev_dbg(&usb_dev->dev, "atusb_in: zero-sized URB ?\n"); return; } len = *skb->data; if (urb->actual_length == 1) { atusb_tx_done(atusb, len); return; } if (len + 1 > urb->actual_length - 1) { dev_dbg(&usb_dev->dev, "atusb_in: frame len %d+1 > URB %u-1\n", len, urb->actual_length); return; } if (!ieee802154_is_valid_psdu_len(len)) { dev_dbg(&usb_dev->dev, "atusb_in: frame corrupted\n"); return; } lqi = skb->data[len + 1]; dev_dbg(&usb_dev->dev, "atusb_in: rx len %d lqi 0x%02x\n", len, lqi); skb_pull(skb, 1); /* remove PHR */ skb_trim(skb, len); /* get payload only */ ieee802154_rx_irqsafe(atusb->hw, skb, lqi); urb->context = NULL; /* skb is gone */ } static void atusb_in(struct urb *urb) { struct usb_device *usb_dev = urb->dev; struct sk_buff *skb = urb->context; struct atusb *atusb = SKB_ATUSB(skb); dev_dbg(&usb_dev->dev, "atusb_in: status %d len %d\n", urb->status, urb->actual_length); if (urb->status) { if (urb->status == -ENOENT) { /* being killed */ kfree_skb(skb); urb->context = NULL; return; } dev_dbg(&usb_dev->dev, "atusb_in: URB error %d\n", urb->status); } else { atusb_in_good(urb); } usb_anchor_urb(urb, &atusb->idle_urbs); if (!atusb->shutdown) schedule_delayed_work(&atusb->work, 0); } /* ----- URB allocation/deallocation --------------------------------------- */ static void atusb_free_urbs(struct atusb *atusb) { struct urb *urb; while (1) { urb = usb_get_from_anchor(&atusb->idle_urbs); if (!urb) break; kfree_skb(urb->context); usb_free_urb(urb); } } static int atusb_alloc_urbs(struct atusb *atusb, int n) { struct urb *urb; while (n) { urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) { atusb_free_urbs(atusb); return -ENOMEM; } usb_anchor_urb(urb, &atusb->idle_urbs); n--; } return 0; } /* ----- IEEE 802.15.4 interface operations -------------------------------- */ static void atusb_xmit_complete(struct urb *urb) { dev_dbg(&urb->dev->dev, "atusb_xmit urb completed"); } static int atusb_xmit(struct ieee802154_hw *hw, struct sk_buff *skb) { struct atusb *atusb = hw->priv; struct usb_device *usb_dev = atusb->usb_dev; int ret; dev_dbg(&usb_dev->dev, "atusb_xmit (%d)\n", skb->len); atusb->tx_skb = skb; atusb->tx_ack_seq++; atusb->tx_dr.wIndex = cpu_to_le16(atusb->tx_ack_seq); atusb->tx_dr.wLength = cpu_to_le16(skb->len); usb_fill_control_urb(atusb->tx_urb, usb_dev, usb_sndctrlpipe(usb_dev, 0), (unsigned char *)&atusb->tx_dr, skb->data, skb->len, atusb_xmit_complete, NULL); ret = usb_submit_urb(atusb->tx_urb, GFP_ATOMIC); dev_dbg(&usb_dev->dev, "atusb_xmit done (%d)\n", ret); return ret; } static int atusb_channel(struct ieee802154_hw *hw, u8 page, u8 channel) { struct atusb *atusb = hw->priv; int ret; ret = atusb_write_subreg(atusb, SR_CHANNEL, channel); if (ret < 0) return ret; msleep(1); /* @@@ ugly synchronization */ return 0; } static int atusb_ed(struct ieee802154_hw *hw, u8 *level) { BUG_ON(!level); *level = 0xbe; return 0; } static int atusb_set_hw_addr_filt(struct ieee802154_hw *hw, struct ieee802154_hw_addr_filt *filt, unsigned long changed) { struct atusb *atusb = hw->priv; struct device *dev = &atusb->usb_dev->dev; if (changed & IEEE802154_AFILT_SADDR_CHANGED) { u16 addr = le16_to_cpu(filt->short_addr); dev_vdbg(dev, "atusb_set_hw_addr_filt called for saddr\n"); atusb_write_reg(atusb, RG_SHORT_ADDR_0, addr); atusb_write_reg(atusb, RG_SHORT_ADDR_1, addr >> 8); } if (changed & IEEE802154_AFILT_PANID_CHANGED) { u16 pan = le16_to_cpu(filt->pan_id); dev_vdbg(dev, "atusb_set_hw_addr_filt called for pan id\n"); atusb_write_reg(atusb, RG_PAN_ID_0, pan); atusb_write_reg(atusb, RG_PAN_ID_1, pan >> 8); } if (changed & IEEE802154_AFILT_IEEEADDR_CHANGED) { u8 i, addr[IEEE802154_EXTENDED_ADDR_LEN]; memcpy(addr, &filt->ieee_addr, IEEE802154_EXTENDED_ADDR_LEN); dev_vdbg(dev, "atusb_set_hw_addr_filt called for IEEE addr\n"); for (i = 0; i < 8; i++) atusb_write_reg(atusb, RG_IEEE_ADDR_0 + i, addr[i]); } if (changed & IEEE802154_AFILT_PANC_CHANGED) { dev_vdbg(dev, "atusb_set_hw_addr_filt called for panc change\n"); if (filt->pan_coord) atusb_write_subreg(atusb, SR_AACK_I_AM_COORD, 1); else atusb_write_subreg(atusb, SR_AACK_I_AM_COORD, 0); } return atusb_get_and_clear_error(atusb); } static int atusb_start(struct ieee802154_hw *hw) { struct atusb *atusb = hw->priv; struct usb_device *usb_dev = atusb->usb_dev; int ret; dev_dbg(&usb_dev->dev, "atusb_start\n"); schedule_delayed_work(&atusb->work, 0); atusb_command(atusb, ATUSB_RX_MODE, 1); ret = atusb_get_and_clear_error(atusb); if (ret < 0) usb_kill_anchored_urbs(&atusb->idle_urbs); return ret; } static void atusb_stop(struct ieee802154_hw *hw) { struct atusb *atusb = hw->priv; struct usb_device *usb_dev = atusb->usb_dev; dev_dbg(&usb_dev->dev, "atusb_stop\n"); usb_kill_anchored_urbs(&atusb->idle_urbs); atusb_command(atusb, ATUSB_RX_MODE, 0); atusb_get_and_clear_error(atusb); } #define ATUSB_MAX_TX_POWERS 0xF static const s32 atusb_powers[ATUSB_MAX_TX_POWERS + 1] = { 300, 280, 230, 180, 130, 70, 0, -100, -200, -300, -400, -500, -700, -900, -1200, -1700, }; static int atusb_set_txpower(struct ieee802154_hw *hw, s32 mbm) { struct atusb *atusb = hw->priv; u32 i; for (i = 0; i < hw->phy->supported.tx_powers_size; i++) { if (hw->phy->supported.tx_powers[i] == mbm) return atusb_write_subreg(atusb, SR_TX_PWR_23X, i); } return -EINVAL; } #define ATUSB_MAX_ED_LEVELS 0xF static const s32 atusb_ed_levels[ATUSB_MAX_ED_LEVELS + 1] = { -9100, -8900, -8700, -8500, -8300, -8100, -7900, -7700, -7500, -7300, -7100, -6900, -6700, -6500, -6300, -6100, }; static int atusb_set_cca_mode(struct ieee802154_hw *hw, const struct wpan_phy_cca *cca) { struct atusb *atusb = hw->priv; u8 val; /* mapping 802.15.4 to driver spec */ switch (cca->mode) { case NL802154_CCA_ENERGY: val = 1; break; case NL802154_CCA_CARRIER: val = 2; break; case NL802154_CCA_ENERGY_CARRIER: switch (cca->opt) { case NL802154_CCA_OPT_ENERGY_CARRIER_AND: val = 3; break; case NL802154_CCA_OPT_ENERGY_CARRIER_OR: val = 0; break; default: return -EINVAL; } break; default: return -EINVAL; } return atusb_write_subreg(atusb, SR_CCA_MODE, val); } static int atusb_set_cca_ed_level(struct ieee802154_hw *hw, s32 mbm) { struct atusb *atusb = hw->priv; u32 i; for (i = 0; i < hw->phy->supported.cca_ed_levels_size; i++) { if (hw->phy->supported.cca_ed_levels[i] == mbm) return atusb_write_subreg(atusb, SR_CCA_ED_THRES, i); } return -EINVAL; } static int atusb_set_csma_params(struct ieee802154_hw *hw, u8 min_be, u8 max_be, u8 retries) { struct atusb *atusb = hw->priv; int ret; ret = atusb_write_subreg(atusb, SR_MIN_BE, min_be); if (ret) return ret; ret = atusb_write_subreg(atusb, SR_MAX_BE, max_be); if (ret) return ret; return atusb_write_subreg(atusb, SR_MAX_CSMA_RETRIES, retries); } static int atusb_set_frame_retries(struct ieee802154_hw *hw, s8 retries) { struct atusb *atusb = hw->priv; struct device *dev = &atusb->usb_dev->dev; if (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 3) { dev_info(dev, "Automatic frame retransmission is only available from " "firmware version 0.3. Please update if you want this feature."); return -EINVAL; } return atusb_write_subreg(atusb, SR_MAX_FRAME_RETRIES, retries); } static int atusb_set_promiscuous_mode(struct ieee802154_hw *hw, const bool on) { struct atusb *atusb = hw->priv; int ret; if (on) { ret = atusb_write_subreg(atusb, SR_AACK_DIS_ACK, 1); if (ret < 0) return ret; ret = atusb_write_subreg(atusb, SR_AACK_PROM_MODE, 1); if (ret < 0) return ret; } else { ret = atusb_write_subreg(atusb, SR_AACK_PROM_MODE, 0); if (ret < 0) return ret; ret = atusb_write_subreg(atusb, SR_AACK_DIS_ACK, 0); if (ret < 0) return ret; } return 0; } static const struct ieee802154_ops atusb_ops = { .owner = THIS_MODULE, .xmit_async = atusb_xmit, .ed = atusb_ed, .set_channel = atusb_channel, .start = atusb_start, .stop = atusb_stop, .set_hw_addr_filt = atusb_set_hw_addr_filt, .set_txpower = atusb_set_txpower, .set_cca_mode = atusb_set_cca_mode, .set_cca_ed_level = atusb_set_cca_ed_level, .set_csma_params = atusb_set_csma_params, .set_frame_retries = atusb_set_frame_retries, .set_promiscuous_mode = atusb_set_promiscuous_mode, }; /* ----- Firmware and chip version information ----------------------------- */ static int atusb_get_and_show_revision(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; unsigned char *buffer; int ret; buffer = kmalloc(3, GFP_KERNEL); if (!buffer) return -ENOMEM; /* Get a couple of the ATMega Firmware values */ ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_ID, ATUSB_REQ_FROM_DEV, 0, 0, buffer, 3, 1000); if (ret >= 0) { atusb->fw_ver_maj = buffer[0]; atusb->fw_ver_min = buffer[1]; atusb->fw_hw_type = buffer[2]; dev_info(&usb_dev->dev, "Firmware: major: %u, minor: %u, hardware type: %u\n", atusb->fw_ver_maj, atusb->fw_ver_min, atusb->fw_hw_type); } if (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 2) { dev_info(&usb_dev->dev, "Firmware version (%u.%u) predates our first public release.", atusb->fw_ver_maj, atusb->fw_ver_min); dev_info(&usb_dev->dev, "Please update to version 0.2 or newer"); } kfree(buffer); return ret; } static int atusb_get_and_show_build(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; char *build; int ret; build = kmalloc(ATUSB_BUILD_SIZE + 1, GFP_KERNEL); if (!build) return -ENOMEM; ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_BUILD, ATUSB_REQ_FROM_DEV, 0, 0, build, ATUSB_BUILD_SIZE, 1000); if (ret >= 0) { build[ret] = 0; dev_info(&usb_dev->dev, "Firmware: build %s\n", build); } kfree(build); return ret; } static int atusb_get_and_show_chip(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; uint8_t man_id_0, man_id_1, part_num, version_num; const char *chip; man_id_0 = atusb_read_reg(atusb, RG_MAN_ID_0); man_id_1 = atusb_read_reg(atusb, RG_MAN_ID_1); part_num = atusb_read_reg(atusb, RG_PART_NUM); version_num = atusb_read_reg(atusb, RG_VERSION_NUM); if (atusb->err) return atusb->err; if ((man_id_1 << 8 | man_id_0) != ATUSB_JEDEC_ATMEL) { dev_err(&usb_dev->dev, "non-Atmel transceiver xxxx%02x%02x\n", man_id_1, man_id_0); goto fail; } switch (part_num) { case 2: chip = "AT86RF230"; break; case 3: chip = "AT86RF231"; break; default: dev_err(&usb_dev->dev, "unexpected transceiver, part 0x%02x version 0x%02x\n", part_num, version_num); goto fail; } dev_info(&usb_dev->dev, "ATUSB: %s version %d\n", chip, version_num); return 0; fail: atusb->err = -ENODEV; return -ENODEV; } static int atusb_set_extended_addr(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; unsigned char buffer[IEEE802154_EXTENDED_ADDR_LEN]; __le64 extended_addr; u64 addr; int ret; /* Firmware versions before 0.3 do not support the EUI64_READ command. * Just use a random address and be done */ if (atusb->fw_ver_maj == 0 && atusb->fw_ver_min < 3) { ieee802154_random_extended_addr(&atusb->hw->phy->perm_extended_addr); return 0; } /* Firmware is new enough so we fetch the address from EEPROM */ ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_EUI64_READ, ATUSB_REQ_FROM_DEV, 0, 0, buffer, IEEE802154_EXTENDED_ADDR_LEN, 1000); if (ret < 0) dev_err(&usb_dev->dev, "failed to fetch extended address\n"); memcpy(&extended_addr, buffer, IEEE802154_EXTENDED_ADDR_LEN); /* Check if read address is not empty and the unicast bit is set correctly */ if (!ieee802154_is_valid_extended_unicast_addr(extended_addr)) { dev_info(&usb_dev->dev, "no permanent extended address found, random address set\n"); ieee802154_random_extended_addr(&atusb->hw->phy->perm_extended_addr); } else { atusb->hw->phy->perm_extended_addr = extended_addr; addr = swab64((__force u64)atusb->hw->phy->perm_extended_addr); dev_info(&usb_dev->dev, "Read permanent extended address %8phC from device\n", &addr); } return ret; } /* ----- Setup ------------------------------------------------------------- */ static int atusb_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *usb_dev = interface_to_usbdev(interface); struct ieee802154_hw *hw; struct atusb *atusb = NULL; int ret = -ENOMEM; hw = ieee802154_alloc_hw(sizeof(struct atusb), &atusb_ops); if (!hw) return -ENOMEM; atusb = hw->priv; atusb->hw = hw; atusb->usb_dev = usb_get_dev(usb_dev); usb_set_intfdata(interface, atusb); atusb->shutdown = 0; atusb->err = 0; INIT_DELAYED_WORK(&atusb->work, atusb_work_urbs); init_usb_anchor(&atusb->idle_urbs); init_usb_anchor(&atusb->rx_urbs); if (atusb_alloc_urbs(atusb, ATUSB_NUM_RX_URBS)) goto fail; atusb->tx_dr.bRequestType = ATUSB_REQ_TO_DEV; atusb->tx_dr.bRequest = ATUSB_TX; atusb->tx_dr.wValue = cpu_to_le16(0); atusb->tx_urb = usb_alloc_urb(0, GFP_ATOMIC); if (!atusb->tx_urb) goto fail; hw->parent = &usb_dev->dev; hw->flags = IEEE802154_HW_TX_OMIT_CKSUM | IEEE802154_HW_AFILT | IEEE802154_HW_PROMISCUOUS | IEEE802154_HW_CSMA_PARAMS | IEEE802154_HW_FRAME_RETRIES; hw->phy->flags = WPAN_PHY_FLAG_TXPOWER | WPAN_PHY_FLAG_CCA_ED_LEVEL | WPAN_PHY_FLAG_CCA_MODE; hw->phy->supported.cca_modes = BIT(NL802154_CCA_ENERGY) | BIT(NL802154_CCA_CARRIER) | BIT(NL802154_CCA_ENERGY_CARRIER); hw->phy->supported.cca_opts = BIT(NL802154_CCA_OPT_ENERGY_CARRIER_AND) | BIT(NL802154_CCA_OPT_ENERGY_CARRIER_OR); hw->phy->supported.cca_ed_levels = atusb_ed_levels; hw->phy->supported.cca_ed_levels_size = ARRAY_SIZE(atusb_ed_levels); hw->phy->cca.mode = NL802154_CCA_ENERGY; hw->phy->current_page = 0; hw->phy->current_channel = 11; /* reset default */ hw->phy->supported.channels[0] = 0x7FFF800; hw->phy->supported.tx_powers = atusb_powers; hw->phy->supported.tx_powers_size = ARRAY_SIZE(atusb_powers); hw->phy->transmit_power = hw->phy->supported.tx_powers[0]; hw->phy->cca_ed_level = hw->phy->supported.cca_ed_levels[7]; atusb_command(atusb, ATUSB_RF_RESET, 0); atusb_get_and_show_chip(atusb); atusb_get_and_show_revision(atusb); atusb_get_and_show_build(atusb); atusb_set_extended_addr(atusb); ret = atusb_get_and_clear_error(atusb); if (ret) { dev_err(&atusb->usb_dev->dev, "%s: initialization failed, error = %d\n", __func__, ret); goto fail; } ret = ieee802154_register_hw(hw); if (ret) goto fail; /* If we just powered on, we're now in P_ON and need to enter TRX_OFF * explicitly. Any resets after that will send us straight to TRX_OFF, * making the command below redundant. */ atusb_write_reg(atusb, RG_TRX_STATE, STATE_FORCE_TRX_OFF); msleep(1); /* reset => TRX_OFF, tTR13 = 37 us */ #if 0 /* Calculating the maximum time available to empty the frame buffer * on reception: * * According to [1], the inter-frame gap is * R * 20 * 16 us + 128 us * where R is a random number from 0 to 7. Furthermore, we have 20 bit * times (80 us at 250 kbps) of SHR of the next frame before the * transceiver begins storing data in the frame buffer. * * This yields a minimum time of 208 us between the last data of a * frame and the first data of the next frame. This time is further * reduced by interrupt latency in the atusb firmware. * * atusb currently needs about 500 us to retrieve a maximum-sized * frame. We therefore have to allow reception of a new frame to begin * while we retrieve the previous frame. * * [1] "JN-AN-1035 Calculating data rates in an IEEE 802.15.4-based * network", Jennic 2006. * http://www.jennic.com/download_file.php?supportFile=JN-AN-1035%20Calculating%20802-15-4%20Data%20Rates-1v0.pdf */ atusb_write_subreg(atusb, SR_RX_SAFE_MODE, 1); #endif atusb_write_reg(atusb, RG_IRQ_MASK, 0xff); ret = atusb_get_and_clear_error(atusb); if (!ret) return 0; dev_err(&atusb->usb_dev->dev, "%s: setup failed, error = %d\n", __func__, ret); ieee802154_unregister_hw(hw); fail: atusb_free_urbs(atusb); usb_kill_urb(atusb->tx_urb); usb_free_urb(atusb->tx_urb); usb_put_dev(usb_dev); ieee802154_free_hw(hw); return ret; } static void atusb_disconnect(struct usb_interface *interface) { struct atusb *atusb = usb_get_intfdata(interface); dev_dbg(&atusb->usb_dev->dev, "atusb_disconnect\n"); atusb->shutdown = 1; cancel_delayed_work_sync(&atusb->work); usb_kill_anchored_urbs(&atusb->rx_urbs); atusb_free_urbs(atusb); usb_kill_urb(atusb->tx_urb); usb_free_urb(atusb->tx_urb); ieee802154_unregister_hw(atusb->hw); ieee802154_free_hw(atusb->hw); usb_set_intfdata(interface, NULL); usb_put_dev(atusb->usb_dev); pr_debug("atusb_disconnect done\n"); } /* The devices we work with */ static const struct usb_device_id atusb_device_table[] = { { .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = ATUSB_VENDOR_ID, .idProduct = ATUSB_PRODUCT_ID, .bInterfaceClass = USB_CLASS_VENDOR_SPEC }, /* end with null element */ {} }; MODULE_DEVICE_TABLE(usb, atusb_device_table); static struct usb_driver atusb_driver = { .name = "atusb", .probe = atusb_probe, .disconnect = atusb_disconnect, .id_table = atusb_device_table, }; module_usb_driver(atusb_driver); MODULE_AUTHOR("Alexander Aring <alex.aring@gmail.com>"); MODULE_AUTHOR("Richard Sharpe <realrichardsharpe@gmail.com>"); MODULE_AUTHOR("Stefan Schmidt <stefan@datenfreihafen.org>"); MODULE_AUTHOR("Werner Almesberger <werner@almesberger.net>"); MODULE_DESCRIPTION("ATUSB IEEE 802.15.4 Driver"); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-119/c/good_3116_0
crossvul-cpp_data_good_5579_0
/* net_packet.c -- Handles in- and outgoing VPN packets Copyright (C) 1998-2005 Ivo Timmermans, 2000-2013 Guus Sliepen <guus@tinc-vpn.org> 2010 Timothy Redaelli <timothy@redaelli.eu> 2010 Brandon Black <blblack@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "system.h" #include <openssl/rand.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/hmac.h> #ifdef HAVE_ZLIB #include <zlib.h> #endif #ifdef HAVE_LZO #include LZO1X_H #endif #include "avl_tree.h" #include "conf.h" #include "connection.h" #include "device.h" #include "ethernet.h" #include "event.h" #include "graph.h" #include "logger.h" #include "net.h" #include "netutl.h" #include "protocol.h" #include "process.h" #include "route.h" #include "utils.h" #include "xalloc.h" int keylifetime = 0; int keyexpires = 0; #ifdef HAVE_LZO static char lzo_wrkmem[LZO1X_999_MEM_COMPRESS > LZO1X_1_MEM_COMPRESS ? LZO1X_999_MEM_COMPRESS : LZO1X_1_MEM_COMPRESS]; #endif static void send_udppacket(node_t *, vpn_packet_t *); unsigned replaywin = 16; bool localdiscovery = false; #define MAX_SEQNO 1073741824 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval mtuprobes == 31: sleep pinginterval seconds mtuprobes == 32: send 1 burst, sleep pingtimeout second mtuprobes == 33: no response from other side, restart PMTU discovery process Probes are sent in batches of at least three, with random sizes between the lower and upper boundaries for the MTU thus far discovered. After the initial discovery, a fourth packet is added to each batch with a size larger than the currently known PMTU, to test if the PMTU has increased. In case local discovery is enabled, another packet is added to each batch, which will be broadcast to the local network. */ void send_mtu_probe(node_t *n) { vpn_packet_t packet; int len, i; int timeout = 1; n->mtuprobes++; n->mtuevent = NULL; if(!n->status.reachable || !n->status.validkey) { ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send MTU probe to unreachable or rekeying node %s (%s)", n->name, n->hostname); n->mtuprobes = 0; return; } if(n->mtuprobes > 32) { if(!n->minmtu) { n->mtuprobes = 31; timeout = pinginterval; goto end; } ifdebug(TRAFFIC) logger(LOG_INFO, "%s (%s) did not respond to UDP ping, restarting PMTU discovery", n->name, n->hostname); n->mtuprobes = 1; n->minmtu = 0; n->maxmtu = MTU; } if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) { ifdebug(TRAFFIC) logger(LOG_INFO, "No response to MTU probes from %s (%s)", n->name, n->hostname); n->mtuprobes = 31; } if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) { if(n->minmtu > n->maxmtu) n->minmtu = n->maxmtu; else n->maxmtu = n->minmtu; n->mtu = n->minmtu; ifdebug(TRAFFIC) logger(LOG_INFO, "Fixing MTU of %s (%s) to %d after %d probes", n->name, n->hostname, n->mtu, n->mtuprobes); n->mtuprobes = 31; } if(n->mtuprobes == 31) { timeout = pinginterval; goto end; } else if(n->mtuprobes == 32) { timeout = pingtimeout; } for(i = 0; i < 4 + localdiscovery; i++) { if(i == 0) { if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU) continue; len = n->maxmtu + 8; } else if(n->maxmtu <= n->minmtu) { len = n->maxmtu; } else { len = n->minmtu + 1 + rand() % (n->maxmtu - n->minmtu); } if(len < 64) len = 64; memset(packet.data, 0, 14); RAND_pseudo_bytes(packet.data + 14, len - 14); packet.len = len; if(i >= 4 && n->mtuprobes <= 10) packet.priority = -1; else packet.priority = 0; ifdebug(TRAFFIC) logger(LOG_INFO, "Sending MTU probe length %d to %s (%s)", len, n->name, n->hostname); send_udppacket(n, &packet); } end: n->mtuevent = new_event(); n->mtuevent->handler = (event_handler_t)send_mtu_probe; n->mtuevent->data = n; n->mtuevent->time = now + timeout; event_add(n->mtuevent); } void mtu_probe_h(node_t *n, vpn_packet_t *packet, length_t len) { ifdebug(TRAFFIC) logger(LOG_INFO, "Got MTU probe length %d from %s (%s)", packet->len, n->name, n->hostname); if(!packet->data[0]) { packet->data[0] = 1; send_udppacket(n, packet); } else { if(n->mtuprobes > 30) { if (len == n->maxmtu + 8) { ifdebug(TRAFFIC) logger(LOG_INFO, "Increase in PMTU to %s (%s) detected, restarting PMTU discovery", n->name, n->hostname); n->maxmtu = MTU; n->mtuprobes = 10; return; } if(n->minmtu) n->mtuprobes = 30; else n->mtuprobes = 1; } if(len > n->maxmtu) len = n->maxmtu; if(n->minmtu < len) n->minmtu = len; } } static length_t compress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) { if(level == 0) { memcpy(dest, source, len); return len; } else if(level == 10) { #ifdef HAVE_LZO lzo_uint lzolen = MAXSIZE; lzo1x_1_compress(source, len, dest, &lzolen, lzo_wrkmem); return lzolen; #else return -1; #endif } else if(level < 10) { #ifdef HAVE_ZLIB unsigned long destlen = MAXSIZE; if(compress2(dest, &destlen, source, len, level) == Z_OK) return destlen; else #endif return -1; } else { #ifdef HAVE_LZO lzo_uint lzolen = MAXSIZE; lzo1x_999_compress(source, len, dest, &lzolen, lzo_wrkmem); return lzolen; #else return -1; #endif } return -1; } static length_t uncompress_packet(uint8_t *dest, const uint8_t *source, length_t len, int level) { if(level == 0) { memcpy(dest, source, len); return len; } else if(level > 9) { #ifdef HAVE_LZO lzo_uint lzolen = MAXSIZE; if(lzo1x_decompress_safe(source, len, dest, &lzolen, NULL) == LZO_E_OK) return lzolen; else #endif return -1; } #ifdef HAVE_ZLIB else { unsigned long destlen = MAXSIZE; if(uncompress(dest, &destlen, source, len) == Z_OK) return destlen; else return -1; } #endif return -1; } /* VPN packet I/O */ static void receive_packet(node_t *n, vpn_packet_t *packet) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Received packet of %d bytes from %s (%s)", packet->len, n->name, n->hostname); route(n, packet); } static bool try_mac(const node_t *n, const vpn_packet_t *inpkt) { unsigned char hmac[EVP_MAX_MD_SIZE]; if(!n->indigest || !n->inmaclength || !n->inkey || inpkt->len < sizeof inpkt->seqno + n->inmaclength) return false; HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len - n->inmaclength, (unsigned char *)hmac, NULL); return !memcmp(hmac, (char *) &inpkt->seqno + inpkt->len - n->inmaclength, n->inmaclength); } static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) { vpn_packet_t pkt1, pkt2; vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 }; int nextpkt = 0; vpn_packet_t *outpkt = pkt[0]; int outlen, outpad; unsigned char hmac[EVP_MAX_MD_SIZE]; int i; if(!n->inkey) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet", n->name, n->hostname); return; } /* Check packet length */ if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)", n->name, n->hostname); return; } /* Check the message authentication code */ if(n->indigest && n->inmaclength) { inpkt->len -= n->inmaclength; HMAC(n->indigest, n->inkey, n->inkeylength, (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL); if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)", n->name, n->hostname); return; } } /* Decrypt the packet */ if(n->incipher) { outpkt = pkt[nextpkt++]; if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL) || !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen, (unsigned char *) &inpkt->seqno, inpkt->len) || !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s", n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL)); return; } outpkt->len = outlen + outpad; inpkt = outpkt; } /* Check the sequence number */ inpkt->len -= sizeof(inpkt->seqno); inpkt->seqno = ntohl(inpkt->seqno); if(replaywin) { if(inpkt->seqno != n->received_seqno + 1) { if(inpkt->seqno >= n->received_seqno + replaywin * 8) { if(n->farfuture++ < replaywin >> 2) { logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)", n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture); return; } logger(LOG_WARNING, "Lost %d packets from %s (%s)", inpkt->seqno - n->received_seqno - 1, n->name, n->hostname); memset(n->late, 0, replaywin); } else if (inpkt->seqno <= n->received_seqno) { if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) { logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d", n->name, n->hostname, inpkt->seqno, n->received_seqno); return; } } else { for(i = n->received_seqno + 1; i < inpkt->seqno; i++) n->late[(i / 8) % replaywin] |= 1 << i % 8; } } n->farfuture = 0; n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8); } if(inpkt->seqno > n->received_seqno) n->received_seqno = inpkt->seqno; if(n->received_seqno > MAX_SEQNO) keyexpires = 0; /* Decompress the packet */ length_t origlen = inpkt->len; if(n->incompression) { outpkt = pkt[nextpkt++]; if((outpkt->len = uncompress_packet(outpkt->data, inpkt->data, inpkt->len, n->incompression)) < 0) { ifdebug(TRAFFIC) logger(LOG_ERR, "Error while uncompressing packet from %s (%s)", n->name, n->hostname); return; } inpkt = outpkt; origlen -= MTU/64 + 20; } inpkt->priority = 0; if(!inpkt->data[12] && !inpkt->data[13]) mtu_probe_h(n, inpkt, origlen); else receive_packet(n, inpkt); } void receive_tcppacket(connection_t *c, const char *buffer, int len) { vpn_packet_t outpkt; if(len > sizeof outpkt.data) return; outpkt.len = len; if(c->options & OPTION_TCPONLY) outpkt.priority = 0; else outpkt.priority = -1; memcpy(outpkt.data, buffer, len); receive_packet(c->node, &outpkt); } static void send_udppacket(node_t *n, vpn_packet_t *origpkt) { vpn_packet_t pkt1, pkt2; vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 }; vpn_packet_t *inpkt = origpkt; int nextpkt = 0; vpn_packet_t *outpkt; int origlen; int outlen, outpad; #if defined(SOL_IP) && defined(IP_TOS) static int priority = 0; #endif int origpriority; if(!n->status.reachable) { ifdebug(TRAFFIC) logger(LOG_INFO, "Trying to send UDP packet to unreachable node %s (%s)", n->name, n->hostname); return; } /* Make sure we have a valid key */ if(!n->status.validkey) { ifdebug(TRAFFIC) logger(LOG_INFO, "No valid key known yet for %s (%s), forwarding via TCP", n->name, n->hostname); if(n->last_req_key + 10 <= now) { send_req_key(n); n->last_req_key = now; } send_tcppacket(n->nexthop->connection, origpkt); return; } if(n->options & OPTION_PMTU_DISCOVERY && inpkt->len > n->minmtu && (inpkt->data[12] | inpkt->data[13])) { ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) larger than minimum MTU, forwarding via %s", n->name, n->hostname, n != n->nexthop ? n->nexthop->name : "TCP"); if(n != n->nexthop) send_packet(n->nexthop, origpkt); else send_tcppacket(n->nexthop->connection, origpkt); return; } origlen = inpkt->len; origpriority = inpkt->priority; /* Compress the packet */ if(n->outcompression) { outpkt = pkt[nextpkt++]; if((outpkt->len = compress_packet(outpkt->data, inpkt->data, inpkt->len, n->outcompression)) < 0) { ifdebug(TRAFFIC) logger(LOG_ERR, "Error while compressing packet to %s (%s)", n->name, n->hostname); return; } inpkt = outpkt; } /* Add sequence number */ inpkt->seqno = htonl(++(n->sent_seqno)); inpkt->len += sizeof(inpkt->seqno); /* Encrypt the packet */ if(n->outcipher) { outpkt = pkt[nextpkt++]; if(!EVP_EncryptInit_ex(&n->outctx, NULL, NULL, NULL, NULL) || !EVP_EncryptUpdate(&n->outctx, (unsigned char *) &outpkt->seqno, &outlen, (unsigned char *) &inpkt->seqno, inpkt->len) || !EVP_EncryptFinal_ex(&n->outctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) { ifdebug(TRAFFIC) logger(LOG_ERR, "Error while encrypting packet to %s (%s): %s", n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL)); goto end; } outpkt->len = outlen + outpad; inpkt = outpkt; } /* Add the message authentication code */ if(n->outdigest && n->outmaclength) { HMAC(n->outdigest, n->outkey, n->outkeylength, (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *) &inpkt->seqno + inpkt->len, NULL); inpkt->len += n->outmaclength; } /* Determine which socket we have to use */ if(n->address.sa.sa_family != listen_socket[n->sock].sa.sa.sa_family) { for(int sock = 0; sock < listen_sockets; sock++) { if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family) { n->sock = sock; break; } } } /* Send the packet */ struct sockaddr *sa; socklen_t sl; int sock; sockaddr_t broadcast; /* Overloaded use of priority field: -1 means local broadcast */ if(origpriority == -1 && n->prevedge) { sock = rand() % listen_sockets; memset(&broadcast, 0, sizeof broadcast); if(listen_socket[sock].sa.sa.sa_family == AF_INET6) { broadcast.in6.sin6_family = AF_INET6; broadcast.in6.sin6_addr.s6_addr[0x0] = 0xff; broadcast.in6.sin6_addr.s6_addr[0x1] = 0x02; broadcast.in6.sin6_addr.s6_addr[0xf] = 0x01; broadcast.in6.sin6_port = n->prevedge->address.in.sin_port; broadcast.in6.sin6_scope_id = listen_socket[sock].sa.in6.sin6_scope_id; } else { broadcast.in.sin_family = AF_INET; broadcast.in.sin_addr.s_addr = -1; broadcast.in.sin_port = n->prevedge->address.in.sin_port; } sa = &broadcast.sa; sl = SALEN(broadcast.sa); } else { if(origpriority == -1) origpriority = 0; sa = &(n->address.sa); sl = SALEN(n->address.sa); sock = n->sock; } #if defined(SOL_IP) && defined(IP_TOS) if(priorityinheritance && origpriority != priority && listen_socket[n->sock].sa.sa.sa_family == AF_INET) { priority = origpriority; ifdebug(TRAFFIC) logger(LOG_DEBUG, "Setting outgoing packet priority to %d", priority); if(setsockopt(listen_socket[n->sock].udp, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */ logger(LOG_ERR, "System call `%s' failed: %s", "setsockopt", strerror(errno)); } #endif if(sendto(listen_socket[sock].udp, (char *) &inpkt->seqno, inpkt->len, 0, sa, sl) < 0 && !sockwouldblock(sockerrno)) { if(sockmsgsize(sockerrno)) { if(n->maxmtu >= origlen) n->maxmtu = origlen - 1; if(n->mtu >= origlen) n->mtu = origlen - 1; } else ifdebug(TRAFFIC) logger(LOG_WARNING, "Error sending packet to %s (%s): %s", n->name, n->hostname, sockstrerror(sockerrno)); } end: origpkt->len = origlen; } /* send a packet to the given vpn ip. */ void send_packet(const node_t *n, vpn_packet_t *packet) { node_t *via; if(n == myself) { if(overwrite_mac) memcpy(packet->data, mymac.x, ETH_ALEN); devops.write(packet); return; } ifdebug(TRAFFIC) logger(LOG_ERR, "Sending packet of %d bytes to %s (%s)", packet->len, n->name, n->hostname); if(!n->status.reachable) { ifdebug(TRAFFIC) logger(LOG_INFO, "Node %s (%s) is not reachable", n->name, n->hostname); return; } via = (packet->priority == -1 || n->via == myself) ? n->nexthop : n->via; if(via != n) ifdebug(TRAFFIC) logger(LOG_INFO, "Sending packet to %s via %s (%s)", n->name, via->name, n->via->hostname); if(packet->priority == -1 || ((myself->options | via->options) & OPTION_TCPONLY)) { if(!send_tcppacket(via->connection, packet)) terminate_connection(via->connection, true); } else send_udppacket(via, packet); } /* Broadcast a packet using the minimum spanning tree */ void broadcast_packet(const node_t *from, vpn_packet_t *packet) { avl_node_t *node; connection_t *c; node_t *n; // Always give ourself a copy of the packet. if(from != myself) send_packet(myself, packet); // In TunnelServer mode, do not forward broadcast packets. // The MST might not be valid and create loops. if(tunnelserver || broadcast_mode == BMODE_NONE) return; ifdebug(TRAFFIC) logger(LOG_INFO, "Broadcasting packet of %d bytes from %s (%s)", packet->len, from->name, from->hostname); switch(broadcast_mode) { // In MST mode, broadcast packets travel via the Minimum Spanning Tree. // This guarantees all nodes receive the broadcast packet, and // usually distributes the sending of broadcast packets over all nodes. case BMODE_MST: for(node = connection_tree->head; node; node = node->next) { c = node->data; if(c->status.active && c->status.mst && c != from->nexthop->connection) send_packet(c->node, packet); } break; // In direct mode, we send copies to each node we know of. // However, this only reaches nodes that can be reached in a single hop. // We don't have enough information to forward broadcast packets in this case. case BMODE_DIRECT: if(from != myself) break; for(node = node_udp_tree->head; node; node = node->next) { n = node->data; if(n->status.reachable && ((n->via == myself && n->nexthop == n) || n->via == n)) send_packet(n, packet); } break; default: break; } } static node_t *try_harder(const sockaddr_t *from, const vpn_packet_t *pkt) { avl_node_t *node; edge_t *e; node_t *n = NULL; bool hard = false; static time_t last_hard_try = 0; for(node = edge_weight_tree->head; node; node = node->next) { e = node->data; if(e->to == myself) continue; if(sockaddrcmp_noport(from, &e->address)) { if(last_hard_try == now) continue; hard = true; } if(!try_mac(e->to, pkt)) continue; n = e->to; break; } if(hard) last_hard_try = now; last_hard_try = now; return n; } void handle_incoming_vpn_data(int sock) { vpn_packet_t pkt; char *hostname; sockaddr_t from; socklen_t fromlen = sizeof(from); node_t *n; pkt.len = recvfrom(listen_socket[sock].udp, (char *) &pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen); if(pkt.len < 0) { if(!sockwouldblock(sockerrno)) logger(LOG_ERR, "Receiving packet failed: %s", sockstrerror(sockerrno)); return; } sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */ n = lookup_node_udp(&from); if(!n) { n = try_harder(&from, &pkt); if(n) update_node_udp(n, &from); else ifdebug(PROTOCOL) { hostname = sockaddr2hostname(&from); logger(LOG_WARNING, "Received UDP packet from unknown source %s", hostname); free(hostname); return; } else return; } n->sock = sock; receive_udppacket(n, &pkt); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5579_0
crossvul-cpp_data_bad_5034_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2008 Joerg Sonnenberger * Copyright (c) 2011-2012 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_mtree.c 201165 2009-12-29 05:52:13Z kientzle $"); #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include <stddef.h> /* #include <stdint.h> */ /* See archive_platform.h */ #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include "archive.h" #include "archive_entry.h" #include "archive_private.h" #include "archive_read_private.h" #include "archive_string.h" #include "archive_pack_dev.h" #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif #define MTREE_HAS_DEVICE 0x0001 #define MTREE_HAS_FFLAGS 0x0002 #define MTREE_HAS_GID 0x0004 #define MTREE_HAS_GNAME 0x0008 #define MTREE_HAS_MTIME 0x0010 #define MTREE_HAS_NLINK 0x0020 #define MTREE_HAS_PERM 0x0040 #define MTREE_HAS_SIZE 0x0080 #define MTREE_HAS_TYPE 0x0100 #define MTREE_HAS_UID 0x0200 #define MTREE_HAS_UNAME 0x0400 #define MTREE_HAS_OPTIONAL 0x0800 #define MTREE_HAS_NOCHANGE 0x1000 /* FreeBSD specific */ struct mtree_option { struct mtree_option *next; char *value; }; struct mtree_entry { struct mtree_entry *next; struct mtree_option *options; char *name; char full; char used; }; struct mtree { struct archive_string line; size_t buffsize; char *buff; int64_t offset; int fd; int archive_format; const char *archive_format_name; struct mtree_entry *entries; struct mtree_entry *this_entry; struct archive_string current_dir; struct archive_string contents_name; struct archive_entry_linkresolver *resolver; int64_t cur_size; char checkfs; }; static int bid_keycmp(const char *, const char *, ssize_t); static int cleanup(struct archive_read *); static int detect_form(struct archive_read *, int *); static int mtree_bid(struct archive_read *, int); static int parse_file(struct archive_read *, struct archive_entry *, struct mtree *, struct mtree_entry *, int *); static void parse_escapes(char *, struct mtree_entry *); static int parse_line(struct archive_read *, struct archive_entry *, struct mtree *, struct mtree_entry *, int *); static int parse_keyword(struct archive_read *, struct mtree *, struct archive_entry *, struct mtree_option *, int *); static int read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset); static ssize_t readline(struct archive_read *, struct mtree *, char **, ssize_t); static int skip(struct archive_read *a); static int read_header(struct archive_read *, struct archive_entry *); static int64_t mtree_atol10(char **); static int64_t mtree_atol8(char **); static int64_t mtree_atol(char **); /* * There's no standard for TIME_T_MAX/TIME_T_MIN. So we compute them * here. TODO: Move this to configure time, but be careful * about cross-compile environments. */ static int64_t get_time_t_max(void) { #if defined(TIME_T_MAX) return TIME_T_MAX; #else /* ISO C allows time_t to be a floating-point type, but POSIX requires an integer type. The following should work on any system that follows the POSIX conventions. */ if (((time_t)0) < ((time_t)-1)) { /* Time_t is unsigned */ return (~(time_t)0); } else { /* Time_t is signed. */ /* Assume it's the same as int64_t or int32_t */ if (sizeof(time_t) == sizeof(int64_t)) { return (time_t)INT64_MAX; } else { return (time_t)INT32_MAX; } } #endif } static int64_t get_time_t_min(void) { #if defined(TIME_T_MIN) return TIME_T_MIN; #else if (((time_t)0) < ((time_t)-1)) { /* Time_t is unsigned */ return (time_t)0; } else { /* Time_t is signed. */ if (sizeof(time_t) == sizeof(int64_t)) { return (time_t)INT64_MIN; } else { return (time_t)INT32_MIN; } } #endif } static int archive_read_format_mtree_options(struct archive_read *a, const char *key, const char *val) { struct mtree *mtree; mtree = (struct mtree *)(a->format->data); if (strcmp(key, "checkfs") == 0) { /* Allows to read information missing from the mtree from the file system */ if (val == NULL || val[0] == 0) { mtree->checkfs = 0; } else { mtree->checkfs = 1; } return (ARCHIVE_OK); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static void free_options(struct mtree_option *head) { struct mtree_option *next; for (; head != NULL; head = next) { next = head->next; free(head->value); free(head); } } int archive_read_support_format_mtree(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct mtree *mtree; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_mtree"); mtree = (struct mtree *)malloc(sizeof(*mtree)); if (mtree == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate mtree data"); return (ARCHIVE_FATAL); } memset(mtree, 0, sizeof(*mtree)); mtree->fd = -1; r = __archive_read_register_format(a, mtree, "mtree", mtree_bid, archive_read_format_mtree_options, read_header, read_data, skip, NULL, cleanup, NULL, NULL); if (r != ARCHIVE_OK) free(mtree); return (ARCHIVE_OK); } static int cleanup(struct archive_read *a) { struct mtree *mtree; struct mtree_entry *p, *q; mtree = (struct mtree *)(a->format->data); p = mtree->entries; while (p != NULL) { q = p->next; free(p->name); free_options(p->options); free(p); p = q; } archive_string_free(&mtree->line); archive_string_free(&mtree->current_dir); archive_string_free(&mtree->contents_name); archive_entry_linkresolver_free(mtree->resolver); free(mtree->buff); free(mtree); (a->format->data) = NULL; return (ARCHIVE_OK); } static ssize_t get_line_size(const char *b, ssize_t avail, ssize_t *nlsize) { ssize_t len; len = 0; while (len < avail) { switch (*b) { case '\0':/* Non-ascii character or control character. */ if (nlsize != NULL) *nlsize = 0; return (-1); case '\r': if (avail-len > 1 && b[1] == '\n') { if (nlsize != NULL) *nlsize = 2; return (len+2); } /* FALL THROUGH */ case '\n': if (nlsize != NULL) *nlsize = 1; return (len+1); default: b++; len++; break; } } if (nlsize != NULL) *nlsize = 0; return (avail); } static ssize_t next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b, *avail, nl); if (len >= 0) len += tested; } return (len); } /* * Compare characters with a mtree keyword. * Returns the length of a mtree keyword if matched. * Returns 0 if not matched. */ static int bid_keycmp(const char *p, const char *key, ssize_t len) { int match_len = 0; while (len > 0 && *p && *key) { if (*p == *key) { --len; ++p; ++key; ++match_len; continue; } return (0);/* Not match */ } if (*key != '\0') return (0);/* Not match */ /* A following character should be specified characters */ if (p[0] == '=' || p[0] == ' ' || p[0] == '\t' || p[0] == '\n' || p[0] == '\r' || (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r'))) return (match_len); return (0);/* Not match */ } /* * Test whether the characters 'p' has is mtree keyword. * Returns the length of a detected keyword. * Returns 0 if any keywords were not found. */ static int bid_keyword(const char *p, ssize_t len) { static const char *keys_c[] = { "content", "contents", "cksum", NULL }; static const char *keys_df[] = { "device", "flags", NULL }; static const char *keys_g[] = { "gid", "gname", NULL }; static const char *keys_il[] = { "ignore", "inode", "link", NULL }; static const char *keys_m[] = { "md5", "md5digest", "mode", NULL }; static const char *keys_no[] = { "nlink", "nochange", "optional", NULL }; static const char *keys_r[] = { "resdevice", "rmd160", "rmd160digest", NULL }; static const char *keys_s[] = { "sha1", "sha1digest", "sha256", "sha256digest", "sha384", "sha384digest", "sha512", "sha512digest", "size", NULL }; static const char *keys_t[] = { "tags", "time", "type", NULL }; static const char *keys_u[] = { "uid", "uname", NULL }; const char **keys; int i; switch (*p) { case 'c': keys = keys_c; break; case 'd': case 'f': keys = keys_df; break; case 'g': keys = keys_g; break; case 'i': case 'l': keys = keys_il; break; case 'm': keys = keys_m; break; case 'n': case 'o': keys = keys_no; break; case 'r': keys = keys_r; break; case 's': keys = keys_s; break; case 't': keys = keys_t; break; case 'u': keys = keys_u; break; default: return (0);/* Unknown key */ } for (i = 0; keys[i] != NULL; i++) { int l = bid_keycmp(p, keys[i], len); if (l > 0) return (l); } return (0);/* Unknown key */ } /* * Test whether there is a set of mtree keywords. * Returns the number of keyword. * Returns -1 if we got incorrect sequence. * This function expects a set of "<space characters>keyword=value". * When "unset" is specified, expects a set of "<space characters>keyword". */ static int bid_keyword_list(const char *p, ssize_t len, int unset, int last_is_path) { int l; int keycnt = 0; while (len > 0 && *p) { int blank = 0; /* Test whether there are blank characters in the line. */ while (len >0 && (*p == ' ' || *p == '\t')) { ++p; --len; blank = 1; } if (*p == '\n' || *p == '\r') break; if (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r')) break; if (!blank && !last_is_path) /* No blank character. */ return (-1); if (last_is_path && len == 0) return (keycnt); if (unset) { l = bid_keycmp(p, "all", len); if (l > 0) return (1); } /* Test whether there is a correct key in the line. */ l = bid_keyword(p, len); if (l == 0) return (-1);/* Unknown keyword was found. */ p += l; len -= l; keycnt++; /* Skip value */ if (*p == '=') { int value = 0; ++p; --len; while (len > 0 && *p != ' ' && *p != '\t') { ++p; --len; value = 1; } /* A keyword should have a its value unless * "/unset" operation. */ if (!unset && value == 0) return (-1); } } return (keycnt); } static int bid_entry(const char *p, ssize_t len, ssize_t nl, int *last_is_path) { int f = 0; static const unsigned char safe_char[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ /* !"$%&'()*+,-./ EXCLUSION:( )(#) */ 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */ /* 0123456789:;<>? EXCLUSION:(=) */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, /* 30 - 3F */ /* @ABCDEFGHIJKLMNO */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ /* PQRSTUVWXYZ[\]^_ */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */ /* `abcdefghijklmno */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */ /* pqrstuvwxyz{|}~ */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 70 - 7F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ }; ssize_t ll; const char *pp = p; const char * const pp_end = pp + len; *last_is_path = 0; /* * Skip the path-name which is quoted. */ for (;pp < pp_end; ++pp) { if (!safe_char[*(const unsigned char *)pp]) { if (*pp != ' ' && *pp != '\t' && *pp != '\r' && *pp != '\n') f = 0; break; } f = 1; } ll = pp_end - pp; /* If a path-name was not found at the first, try to check * a mtree format(a.k.a form D) ``NetBSD's mtree -D'' creates, * which places the path-name at the last. */ if (f == 0) { const char *pb = p + len - nl; int name_len = 0; int slash; /* The form D accepts only a single line for an entry. */ if (pb-2 >= p && pb[-1] == '\\' && (pb[-2] == ' ' || pb[-2] == '\t')) return (-1); if (pb-1 >= p && pb[-1] == '\\') return (-1); slash = 0; while (p <= --pb && *pb != ' ' && *pb != '\t') { if (!safe_char[*(const unsigned char *)pb]) return (-1); name_len++; /* The pathname should have a slash in this * format. */ if (*pb == '/') slash = 1; } if (name_len == 0 || slash == 0) return (-1); /* If '/' is placed at the first in this field, this is not * a valid filename. */ if (pb[1] == '/') return (-1); ll = len - nl - name_len; pp = p; *last_is_path = 1; } return (bid_keyword_list(pp, ll, 0, *last_is_path)); } #define MAX_BID_ENTRY 3 static int mtree_bid(struct archive_read *a, int best_bid) { const char *signature = "#mtree"; const char *p; (void)best_bid; /* UNUSED */ /* Now let's look at the actual header and see if it matches. */ p = __archive_read_ahead(a, strlen(signature), NULL); if (p == NULL) return (-1); if (memcmp(p, signature, strlen(signature)) == 0) return (8 * (int)strlen(signature)); /* * There is not a mtree signature. Let's try to detect mtree format. */ return (detect_form(a, NULL)); } static int detect_form(struct archive_read *a, int *is_form_d) { const char *p; ssize_t avail, ravail; ssize_t detected_bytes = 0, len, nl; int entry_cnt = 0, multiline = 0; int form_D = 0;/* The archive is generated by `NetBSD mtree -D' * (In this source we call it `form D') . */ if (is_form_d != NULL) *is_form_d = 0; p = __archive_read_ahead(a, 1, &avail); if (p == NULL) return (-1); ravail = avail; for (;;) { len = next_line(a, &p, &avail, &ravail, &nl); /* The terminal character of the line should be * a new line character, '\r\n' or '\n'. */ if (len <= 0 || nl == 0) break; if (!multiline) { /* Leading whitespace is never significant, * ignore it. */ while (len > 0 && (*p == ' ' || *p == '\t')) { ++p; --avail; --len; } /* Skip comment or empty line. */ if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') { p += len; avail -= len; continue; } } else { /* A continuance line; the terminal * character of previous line was '\' character. */ if (bid_keyword_list(p, len, 0, 0) <= 0) break; if (multiline == 1) detected_bytes += len; if (p[len-nl-1] != '\\') { if (multiline == 1 && ++entry_cnt >= MAX_BID_ENTRY) break; multiline = 0; } p += len; avail -= len; continue; } if (p[0] != '/') { int last_is_path, keywords; keywords = bid_entry(p, len, nl, &last_is_path); if (keywords >= 0) { detected_bytes += len; if (form_D == 0) { if (last_is_path) form_D = 1; else if (keywords > 0) /* This line is not `form D'. */ form_D = -1; } else if (form_D == 1) { if (!last_is_path && keywords > 0) /* This this is not `form D' * and We cannot accept mixed * format. */ break; } if (!last_is_path && p[len-nl-1] == '\\') /* This line continues. */ multiline = 1; else { /* We've got plenty of correct lines * to assume that this file is a mtree * format. */ if (++entry_cnt >= MAX_BID_ENTRY) break; } } else break; } else if (strncmp(p, "/set", 4) == 0) { if (bid_keyword_list(p+4, len-4, 0, 0) <= 0) break; /* This line continues. */ if (p[len-nl-1] == '\\') multiline = 2; } else if (strncmp(p, "/unset", 6) == 0) { if (bid_keyword_list(p+6, len-6, 1, 0) <= 0) break; /* This line continues. */ if (p[len-nl-1] == '\\') multiline = 2; } else break; /* Test next line. */ p += len; avail -= len; } if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0)) { if (is_form_d != NULL) { if (form_D == 1) *is_form_d = 1; } return (32); } return (0); } /* * The extended mtree format permits multiple lines specifying * attributes for each file. For those entries, only the last line * is actually used. Practically speaking, that means we have * to read the entire mtree file into memory up front. * * The parsing is done in two steps. First, it is decided if a line * changes the global defaults and if it is, processed accordingly. * Otherwise, the options of the line are merged with the current * global options. */ static int add_option(struct archive_read *a, struct mtree_option **global, const char *value, size_t len) { struct mtree_option *opt; if ((opt = malloc(sizeof(*opt))) == NULL) { archive_set_error(&a->archive, errno, "Can't allocate memory"); return (ARCHIVE_FATAL); } if ((opt->value = malloc(len + 1)) == NULL) { free(opt); archive_set_error(&a->archive, errno, "Can't allocate memory"); return (ARCHIVE_FATAL); } memcpy(opt->value, value, len); opt->value[len] = '\0'; opt->next = *global; *global = opt; return (ARCHIVE_OK); } static void remove_option(struct mtree_option **global, const char *value, size_t len) { struct mtree_option *iter, *last; last = NULL; for (iter = *global; iter != NULL; last = iter, iter = iter->next) { if (strncmp(iter->value, value, len) == 0 && (iter->value[len] == '\0' || iter->value[len] == '=')) break; } if (iter == NULL) return; if (last == NULL) *global = iter->next; else last->next = iter->next; free(iter->value); free(iter); } static int process_global_set(struct archive_read *a, struct mtree_option **global, const char *line) { const char *next, *eq; size_t len; int r; line += 4; for (;;) { next = line + strspn(line, " \t\r\n"); if (*next == '\0') return (ARCHIVE_OK); line = next; next = line + strcspn(line, " \t\r\n"); eq = strchr(line, '='); if (eq > next) len = next - line; else len = eq - line; remove_option(global, line, len); r = add_option(a, global, line, next - line); if (r != ARCHIVE_OK) return (r); line = next; } } static int process_global_unset(struct archive_read *a, struct mtree_option **global, const char *line) { const char *next; size_t len; line += 6; if (strchr(line, '=') != NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "/unset shall not contain `='"); return ARCHIVE_FATAL; } for (;;) { next = line + strspn(line, " \t\r\n"); if (*next == '\0') return (ARCHIVE_OK); line = next; len = strcspn(line, " \t\r\n"); if (len == 3 && strncmp(line, "all", 3) == 0) { free_options(*global); *global = NULL; } else { remove_option(global, line, len); } line += len; } } static int process_add_entry(struct archive_read *a, struct mtree *mtree, struct mtree_option **global, const char *line, ssize_t line_len, struct mtree_entry **last_entry, int is_form_d) { struct mtree_entry *entry; struct mtree_option *iter; const char *next, *eq, *name, *end; size_t name_len, len; int r, i; if ((entry = malloc(sizeof(*entry))) == NULL) { archive_set_error(&a->archive, errno, "Can't allocate memory"); return (ARCHIVE_FATAL); } entry->next = NULL; entry->options = NULL; entry->name = NULL; entry->used = 0; entry->full = 0; /* Add this entry to list. */ if (*last_entry == NULL) mtree->entries = entry; else (*last_entry)->next = entry; *last_entry = entry; if (is_form_d) { /* Filename is last item on line. */ /* Adjust line_len to trim trailing whitespace */ while (line_len > 0) { char last_character = line[line_len - 1]; if (last_character == '\r' || last_character == '\n' || last_character == '\t' || last_character == ' ') { line_len--; } else { break; } } /* Name starts after the last whitespace separator */ name = line; for (i = 0; i < line_len; i++) { if (line[i] == '\r' || line[i] == '\n' || line[i] == '\t' || line[i] == ' ') { name = line + i + 1; } } name_len = line + line_len - name; end = name; } else { /* Filename is first item on line */ name_len = strcspn(line, " \t\r\n"); name = line; line += name_len; end = line + line_len; } /* name/name_len is the name within the line. */ /* line..end brackets the entire line except the name */ if ((entry->name = malloc(name_len + 1)) == NULL) { archive_set_error(&a->archive, errno, "Can't allocate memory"); return (ARCHIVE_FATAL); } memcpy(entry->name, name, name_len); entry->name[name_len] = '\0'; parse_escapes(entry->name, entry); for (iter = *global; iter != NULL; iter = iter->next) { r = add_option(a, &entry->options, iter->value, strlen(iter->value)); if (r != ARCHIVE_OK) return (r); } for (;;) { next = line + strspn(line, " \t\r\n"); if (*next == '\0') return (ARCHIVE_OK); if (next >= end) return (ARCHIVE_OK); line = next; next = line + strcspn(line, " \t\r\n"); eq = strchr(line, '='); if (eq == NULL || eq > next) len = next - line; else len = eq - line; remove_option(&entry->options, line, len); r = add_option(a, &entry->options, line, next - line); if (r != ARCHIVE_OK) return (r); line = next; } } static int read_mtree(struct archive_read *a, struct mtree *mtree) { ssize_t len; uintmax_t counter; char *p; struct mtree_option *global; struct mtree_entry *last_entry; int r, is_form_d; mtree->archive_format = ARCHIVE_FORMAT_MTREE; mtree->archive_format_name = "mtree"; global = NULL; last_entry = NULL; (void)detect_form(a, &is_form_d); for (counter = 1; ; ++counter) { len = readline(a, mtree, &p, 65536); if (len == 0) { mtree->this_entry = mtree->entries; free_options(global); return (ARCHIVE_OK); } if (len < 0) { free_options(global); return ((int)len); } /* Leading whitespace is never significant, ignore it. */ while (*p == ' ' || *p == '\t') { ++p; --len; } /* Skip content lines and blank lines. */ if (*p == '#') continue; if (*p == '\r' || *p == '\n' || *p == '\0') continue; if (*p != '/') { r = process_add_entry(a, mtree, &global, p, len, &last_entry, is_form_d); } else if (strncmp(p, "/set", 4) == 0) { if (p[4] != ' ' && p[4] != '\t') break; r = process_global_set(a, &global, p); } else if (strncmp(p, "/unset", 6) == 0) { if (p[6] != ' ' && p[6] != '\t') break; r = process_global_unset(a, &global, p); } else break; if (r != ARCHIVE_OK) { free_options(global); return r; } } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Can't parse line %ju", counter); free_options(global); return (ARCHIVE_FATAL); } /* * Read in the entire mtree file into memory on the first request. * Then use the next unused file to satisfy each header request. */ static int read_header(struct archive_read *a, struct archive_entry *entry) { struct mtree *mtree; char *p; int r, use_next; mtree = (struct mtree *)(a->format->data); if (mtree->fd >= 0) { close(mtree->fd); mtree->fd = -1; } if (mtree->entries == NULL) { mtree->resolver = archive_entry_linkresolver_new(); if (mtree->resolver == NULL) return ARCHIVE_FATAL; archive_entry_linkresolver_set_strategy(mtree->resolver, ARCHIVE_FORMAT_MTREE); r = read_mtree(a, mtree); if (r != ARCHIVE_OK) return (r); } a->archive.archive_format = mtree->archive_format; a->archive.archive_format_name = mtree->archive_format_name; for (;;) { if (mtree->this_entry == NULL) return (ARCHIVE_EOF); if (strcmp(mtree->this_entry->name, "..") == 0) { mtree->this_entry->used = 1; if (archive_strlen(&mtree->current_dir) > 0) { /* Roll back current path. */ p = mtree->current_dir.s + mtree->current_dir.length - 1; while (p >= mtree->current_dir.s && *p != '/') --p; if (p >= mtree->current_dir.s) --p; mtree->current_dir.length = p - mtree->current_dir.s + 1; } } if (!mtree->this_entry->used) { use_next = 0; r = parse_file(a, entry, mtree, mtree->this_entry, &use_next); if (use_next == 0) return (r); } mtree->this_entry = mtree->this_entry->next; } } /* * A single file can have multiple lines contribute specifications. * Parse as many lines as necessary, then pull additional information * from a backing file on disk as necessary. */ static int parse_file(struct archive_read *a, struct archive_entry *entry, struct mtree *mtree, struct mtree_entry *mentry, int *use_next) { const char *path; struct stat st_storage, *st; struct mtree_entry *mp; struct archive_entry *sparse_entry; int r = ARCHIVE_OK, r1, parsed_kws; mentry->used = 1; /* Initialize reasonable defaults. */ archive_entry_set_filetype(entry, AE_IFREG); archive_entry_set_size(entry, 0); archive_string_empty(&mtree->contents_name); /* Parse options from this line. */ parsed_kws = 0; r = parse_line(a, entry, mtree, mentry, &parsed_kws); if (mentry->full) { archive_entry_copy_pathname(entry, mentry->name); /* * "Full" entries are allowed to have multiple lines * and those lines aren't required to be adjacent. We * don't support multiple lines for "relative" entries * nor do we make any attempt to merge data from * separate "relative" and "full" entries. (Merging * "relative" and "full" entries would require dealing * with pathname canonicalization, which is a very * tricky subject.) */ for (mp = mentry->next; mp != NULL; mp = mp->next) { if (mp->full && !mp->used && strcmp(mentry->name, mp->name) == 0) { /* Later lines override earlier ones. */ mp->used = 1; r1 = parse_line(a, entry, mtree, mp, &parsed_kws); if (r1 < r) r = r1; } } } else { /* * Relative entries require us to construct * the full path and possibly update the * current directory. */ size_t n = archive_strlen(&mtree->current_dir); if (n > 0) archive_strcat(&mtree->current_dir, "/"); archive_strcat(&mtree->current_dir, mentry->name); archive_entry_copy_pathname(entry, mtree->current_dir.s); if (archive_entry_filetype(entry) != AE_IFDIR) mtree->current_dir.length = n; } if (mtree->checkfs) { /* * Try to open and stat the file to get the real size * and other file info. It would be nice to avoid * this here so that getting a listing of an mtree * wouldn't require opening every referenced contents * file. But then we wouldn't know the actual * contents size, so I don't see a really viable way * around this. (Also, we may want to someday pull * other unspecified info from the contents file on * disk.) */ mtree->fd = -1; if (archive_strlen(&mtree->contents_name) > 0) path = mtree->contents_name.s; else path = archive_entry_pathname(entry); if (archive_entry_filetype(entry) == AE_IFREG || archive_entry_filetype(entry) == AE_IFDIR) { mtree->fd = open(path, O_RDONLY | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(mtree->fd); if (mtree->fd == -1 && (errno != ENOENT || archive_strlen(&mtree->contents_name) > 0)) { archive_set_error(&a->archive, errno, "Can't open %s", path); r = ARCHIVE_WARN; } } st = &st_storage; if (mtree->fd >= 0) { if (fstat(mtree->fd, st) == -1) { archive_set_error(&a->archive, errno, "Could not fstat %s", path); r = ARCHIVE_WARN; /* If we can't stat it, don't keep it open. */ close(mtree->fd); mtree->fd = -1; st = NULL; } } else if (lstat(path, st) == -1) { st = NULL; } /* * Check for a mismatch between the type in the specification * and the type of the contents object on disk. */ if (st != NULL) { if (((st->st_mode & S_IFMT) == S_IFREG && archive_entry_filetype(entry) == AE_IFREG) #ifdef S_IFLNK ||((st->st_mode & S_IFMT) == S_IFLNK && archive_entry_filetype(entry) == AE_IFLNK) #endif #ifdef S_IFSOCK ||((st->st_mode & S_IFSOCK) == S_IFSOCK && archive_entry_filetype(entry) == AE_IFSOCK) #endif #ifdef S_IFCHR ||((st->st_mode & S_IFMT) == S_IFCHR && archive_entry_filetype(entry) == AE_IFCHR) #endif #ifdef S_IFBLK ||((st->st_mode & S_IFMT) == S_IFBLK && archive_entry_filetype(entry) == AE_IFBLK) #endif ||((st->st_mode & S_IFMT) == S_IFDIR && archive_entry_filetype(entry) == AE_IFDIR) #ifdef S_IFIFO ||((st->st_mode & S_IFMT) == S_IFIFO && archive_entry_filetype(entry) == AE_IFIFO) #endif ) { /* Types match. */ } else { /* Types don't match; bail out gracefully. */ if (mtree->fd >= 0) close(mtree->fd); mtree->fd = -1; if (parsed_kws & MTREE_HAS_OPTIONAL) { /* It's not an error for an optional * entry to not match disk. */ *use_next = 1; } else if (r == ARCHIVE_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "mtree specification has different" " type for %s", archive_entry_pathname(entry)); r = ARCHIVE_WARN; } return (r); } } /* * If there is a contents file on disk, pick some of the * metadata from that file. For most of these, we only * set it from the contents if it wasn't already parsed * from the specification. */ if (st != NULL) { if (((parsed_kws & MTREE_HAS_DEVICE) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) && (archive_entry_filetype(entry) == AE_IFCHR || archive_entry_filetype(entry) == AE_IFBLK)) archive_entry_set_rdev(entry, st->st_rdev); if ((parsed_kws & (MTREE_HAS_GID | MTREE_HAS_GNAME)) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) archive_entry_set_gid(entry, st->st_gid); if ((parsed_kws & (MTREE_HAS_UID | MTREE_HAS_UNAME)) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) archive_entry_set_uid(entry, st->st_uid); if ((parsed_kws & MTREE_HAS_MTIME) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) { #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC archive_entry_set_mtime(entry, st->st_mtime, st->st_mtimespec.tv_nsec); #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC archive_entry_set_mtime(entry, st->st_mtime, st->st_mtim.tv_nsec); #elif HAVE_STRUCT_STAT_ST_MTIME_N archive_entry_set_mtime(entry, st->st_mtime, st->st_mtime_n); #elif HAVE_STRUCT_STAT_ST_UMTIME archive_entry_set_mtime(entry, st->st_mtime, st->st_umtime*1000); #elif HAVE_STRUCT_STAT_ST_MTIME_USEC archive_entry_set_mtime(entry, st->st_mtime, st->st_mtime_usec*1000); #else archive_entry_set_mtime(entry, st->st_mtime, 0); #endif } if ((parsed_kws & MTREE_HAS_NLINK) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) archive_entry_set_nlink(entry, st->st_nlink); if ((parsed_kws & MTREE_HAS_PERM) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) archive_entry_set_perm(entry, st->st_mode); if ((parsed_kws & MTREE_HAS_SIZE) == 0 || (parsed_kws & MTREE_HAS_NOCHANGE) != 0) archive_entry_set_size(entry, st->st_size); archive_entry_set_ino(entry, st->st_ino); archive_entry_set_dev(entry, st->st_dev); archive_entry_linkify(mtree->resolver, &entry, &sparse_entry); } else if (parsed_kws & MTREE_HAS_OPTIONAL) { /* * Couldn't open the entry, stat it or the on-disk type * didn't match. If this entry is optional, just * ignore it and read the next header entry. */ *use_next = 1; return ARCHIVE_OK; } } mtree->cur_size = archive_entry_size(entry); mtree->offset = 0; return r; } /* * Each line contains a sequence of keywords. */ static int parse_line(struct archive_read *a, struct archive_entry *entry, struct mtree *mtree, struct mtree_entry *mp, int *parsed_kws) { struct mtree_option *iter; int r = ARCHIVE_OK, r1; for (iter = mp->options; iter != NULL; iter = iter->next) { r1 = parse_keyword(a, mtree, entry, iter, parsed_kws); if (r1 < r) r = r1; } if (r == ARCHIVE_OK && (*parsed_kws & MTREE_HAS_TYPE) == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Missing type keyword in mtree specification"); return (ARCHIVE_WARN); } return (r); } /* * Device entries have one of the following forms: * - raw dev_t * - format,major,minor[,subdevice] * When parsing succeeded, `pdev' will contain the appropriate dev_t value. */ /* strsep() is not in C90, but strcspn() is. */ /* Taken from http://unixpapa.com/incnote/string.html */ static char * la_strsep(char **sp, const char *sep) { char *p, *s; if (sp == NULL || *sp == NULL || **sp == '\0') return(NULL); s = *sp; p = s + strcspn(s, sep); if (*p != '\0') *p++ = '\0'; *sp = p; return(s); } static int parse_device(dev_t *pdev, struct archive *a, char *val) { #define MAX_PACK_ARGS 3 unsigned long numbers[MAX_PACK_ARGS]; char *p, *dev; int argc; pack_t *pack; dev_t result; const char *error = NULL; memset(pdev, 0, sizeof(*pdev)); if ((dev = strchr(val, ',')) != NULL) { /* * Device's major/minor are given in a specified format. * Decode and pack it accordingly. */ *dev++ = '\0'; if ((pack = pack_find(val)) == NULL) { archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown format `%s'", val); return ARCHIVE_WARN; } argc = 0; while ((p = la_strsep(&dev, ",")) != NULL) { if (*p == '\0') { archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, "Missing number"); return ARCHIVE_WARN; } numbers[argc++] = (unsigned long)mtree_atol(&p); if (argc > MAX_PACK_ARGS) { archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, "Too many arguments"); return ARCHIVE_WARN; } } if (argc < 2) { archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, "Not enough arguments"); return ARCHIVE_WARN; } result = (*pack)(argc, numbers, &error); if (error != NULL) { archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT, "%s", error); return ARCHIVE_WARN; } } else { /* file system raw value. */ result = (dev_t)mtree_atol(&val); } *pdev = result; return ARCHIVE_OK; #undef MAX_PACK_ARGS } /* * Parse a single keyword and its value. */ static int parse_keyword(struct archive_read *a, struct mtree *mtree, struct archive_entry *entry, struct mtree_option *opt, int *parsed_kws) { char *val, *key; key = opt->value; if (*key == '\0') return (ARCHIVE_OK); if (strcmp(key, "nochange") == 0) { *parsed_kws |= MTREE_HAS_NOCHANGE; return (ARCHIVE_OK); } if (strcmp(key, "optional") == 0) { *parsed_kws |= MTREE_HAS_OPTIONAL; return (ARCHIVE_OK); } if (strcmp(key, "ignore") == 0) { /* * The mtree processing is not recursive, so * recursion will only happen for explicitly listed * entries. */ return (ARCHIVE_OK); } val = strchr(key, '='); if (val == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Malformed attribute \"%s\" (%d)", key, key[0]); return (ARCHIVE_WARN); } *val = '\0'; ++val; switch (key[0]) { case 'c': if (strcmp(key, "content") == 0 || strcmp(key, "contents") == 0) { parse_escapes(val, NULL); archive_strcpy(&mtree->contents_name, val); break; } if (strcmp(key, "cksum") == 0) break; case 'd': if (strcmp(key, "device") == 0) { /* stat(2) st_rdev field, e.g. the major/minor IDs * of a char/block special file */ int r; dev_t dev; *parsed_kws |= MTREE_HAS_DEVICE; r = parse_device(&dev, &a->archive, val); if (r == ARCHIVE_OK) archive_entry_set_rdev(entry, dev); return r; } case 'f': if (strcmp(key, "flags") == 0) { *parsed_kws |= MTREE_HAS_FFLAGS; archive_entry_copy_fflags_text(entry, val); break; } case 'g': if (strcmp(key, "gid") == 0) { *parsed_kws |= MTREE_HAS_GID; archive_entry_set_gid(entry, mtree_atol10(&val)); break; } if (strcmp(key, "gname") == 0) { *parsed_kws |= MTREE_HAS_GNAME; archive_entry_copy_gname(entry, val); break; } case 'i': if (strcmp(key, "inode") == 0) { archive_entry_set_ino(entry, mtree_atol10(&val)); break; } case 'l': if (strcmp(key, "link") == 0) { archive_entry_copy_symlink(entry, val); break; } case 'm': if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0) break; if (strcmp(key, "mode") == 0) { if (val[0] >= '0' && val[0] <= '9') { *parsed_kws |= MTREE_HAS_PERM; archive_entry_set_perm(entry, (mode_t)mtree_atol8(&val)); } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Symbolic mode \"%s\" unsupported", val); return ARCHIVE_WARN; } break; } case 'n': if (strcmp(key, "nlink") == 0) { *parsed_kws |= MTREE_HAS_NLINK; archive_entry_set_nlink(entry, (unsigned int)mtree_atol10(&val)); break; } case 'r': if (strcmp(key, "resdevice") == 0) { /* stat(2) st_dev field, e.g. the device ID where the * inode resides */ int r; dev_t dev; r = parse_device(&dev, &a->archive, val); if (r == ARCHIVE_OK) archive_entry_set_dev(entry, dev); return r; } if (strcmp(key, "rmd160") == 0 || strcmp(key, "rmd160digest") == 0) break; case 's': if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0) break; if (strcmp(key, "sha256") == 0 || strcmp(key, "sha256digest") == 0) break; if (strcmp(key, "sha384") == 0 || strcmp(key, "sha384digest") == 0) break; if (strcmp(key, "sha512") == 0 || strcmp(key, "sha512digest") == 0) break; if (strcmp(key, "size") == 0) { archive_entry_set_size(entry, mtree_atol10(&val)); break; } case 't': if (strcmp(key, "tags") == 0) { /* * Comma delimited list of tags. * Ignore the tags for now, but the interface * should be extended to allow inclusion/exclusion. */ break; } if (strcmp(key, "time") == 0) { int64_t m; int64_t my_time_t_max = get_time_t_max(); int64_t my_time_t_min = get_time_t_min(); long ns = 0; *parsed_kws |= MTREE_HAS_MTIME; m = mtree_atol10(&val); /* Replicate an old mtree bug: * 123456789.1 represents 123456789 * seconds and 1 nanosecond. */ if (*val == '.') { ++val; ns = (long)mtree_atol10(&val); } else ns = 0; if (m > my_time_t_max) m = my_time_t_max; else if (m < my_time_t_min) m = my_time_t_min; archive_entry_set_mtime(entry, (time_t)m, ns); break; } if (strcmp(key, "type") == 0) { switch (val[0]) { case 'b': if (strcmp(val, "block") == 0) { archive_entry_set_filetype(entry, AE_IFBLK); break; } case 'c': if (strcmp(val, "char") == 0) { archive_entry_set_filetype(entry, AE_IFCHR); break; } case 'd': if (strcmp(val, "dir") == 0) { archive_entry_set_filetype(entry, AE_IFDIR); break; } case 'f': if (strcmp(val, "fifo") == 0) { archive_entry_set_filetype(entry, AE_IFIFO); break; } if (strcmp(val, "file") == 0) { archive_entry_set_filetype(entry, AE_IFREG); break; } case 'l': if (strcmp(val, "link") == 0) { archive_entry_set_filetype(entry, AE_IFLNK); break; } default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unrecognized file type \"%s\"; " "assuming \"file\"", val); archive_entry_set_filetype(entry, AE_IFREG); return (ARCHIVE_WARN); } *parsed_kws |= MTREE_HAS_TYPE; break; } case 'u': if (strcmp(key, "uid") == 0) { *parsed_kws |= MTREE_HAS_UID; archive_entry_set_uid(entry, mtree_atol10(&val)); break; } if (strcmp(key, "uname") == 0) { *parsed_kws |= MTREE_HAS_UNAME; archive_entry_copy_uname(entry, val); break; } default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unrecognized key %s=%s", key, val); return (ARCHIVE_WARN); } return (ARCHIVE_OK); } static int read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { size_t bytes_to_read; ssize_t bytes_read; struct mtree *mtree; mtree = (struct mtree *)(a->format->data); if (mtree->fd < 0) { *buff = NULL; *offset = 0; *size = 0; return (ARCHIVE_EOF); } if (mtree->buff == NULL) { mtree->buffsize = 64 * 1024; mtree->buff = malloc(mtree->buffsize); if (mtree->buff == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } } *buff = mtree->buff; *offset = mtree->offset; if ((int64_t)mtree->buffsize > mtree->cur_size - mtree->offset) bytes_to_read = (size_t)(mtree->cur_size - mtree->offset); else bytes_to_read = mtree->buffsize; bytes_read = read(mtree->fd, mtree->buff, bytes_to_read); if (bytes_read < 0) { archive_set_error(&a->archive, errno, "Can't read"); return (ARCHIVE_WARN); } if (bytes_read == 0) { *size = 0; return (ARCHIVE_EOF); } mtree->offset += bytes_read; *size = bytes_read; return (ARCHIVE_OK); } /* Skip does nothing except possibly close the contents file. */ static int skip(struct archive_read *a) { struct mtree *mtree; mtree = (struct mtree *)(a->format->data); if (mtree->fd >= 0) { close(mtree->fd); mtree->fd = -1; } return (ARCHIVE_OK); } /* * Since parsing backslash sequences always makes strings shorter, * we can always do this conversion in-place. */ static void parse_escapes(char *src, struct mtree_entry *mentry) { char *dest = src; char c; if (mentry != NULL && strcmp(src, ".") == 0) mentry->full = 1; while (*src != '\0') { c = *src++; if (c == '/' && mentry != NULL) mentry->full = 1; if (c == '\\') { switch (src[0]) { case '0': if (src[1] < '0' || src[1] > '7') { c = 0; ++src; break; } /* FALLTHROUGH */ case '1': case '2': case '3': if (src[1] >= '0' && src[1] <= '7' && src[2] >= '0' && src[2] <= '7') { c = (src[0] - '0') << 6; c |= (src[1] - '0') << 3; c |= (src[2] - '0'); src += 3; } break; case 'a': c = '\a'; ++src; break; case 'b': c = '\b'; ++src; break; case 'f': c = '\f'; ++src; break; case 'n': c = '\n'; ++src; break; case 'r': c = '\r'; ++src; break; case 's': c = ' '; ++src; break; case 't': c = '\t'; ++src; break; case 'v': c = '\v'; ++src; break; case '\\': c = '\\'; ++src; break; } } *dest++ = c; } *dest = '\0'; } /* * Note that this implementation does not (and should not!) obey * locale settings; you cannot simply substitute strtol here, since * it does obey locale. */ static int64_t mtree_atol8(char **p) { int64_t l, limit, last_digit_limit; int digit, base; base = 8; limit = INT64_MAX / base; last_digit_limit = INT64_MAX % base; l = 0; digit = **p - '0'; while (digit >= 0 && digit < base) { if (l>limit || (l == limit && digit > last_digit_limit)) { l = INT64_MAX; /* Truncate on overflow. */ break; } l = (l * base) + digit; digit = *++(*p) - '0'; } return (l); } /* * Note that this implementation does not (and should not!) obey * locale settings; you cannot simply substitute strtol here, since * it does obey locale. */ static int64_t mtree_atol10(char **p) { int64_t l, limit, last_digit_limit; int base, digit, sign; base = 10; if (**p == '-') { sign = -1; limit = ((uint64_t)(INT64_MAX) + 1) / base; last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base; ++(*p); } else { sign = 1; limit = INT64_MAX / base; last_digit_limit = INT64_MAX % base; } l = 0; digit = **p - '0'; while (digit >= 0 && digit < base) { if (l > limit || (l == limit && digit > last_digit_limit)) return (sign < 0) ? INT64_MIN : INT64_MAX; l = (l * base) + digit; digit = *++(*p) - '0'; } return (sign < 0) ? -l : l; } /* Parse a hex digit. */ static int parsehex(char c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'a' && c <= 'f') return c - 'a'; else if (c >= 'A' && c <= 'F') return c - 'A'; else return -1; } /* * Note that this implementation does not (and should not!) obey * locale settings; you cannot simply substitute strtol here, since * it does obey locale. */ static int64_t mtree_atol16(char **p) { int64_t l, limit, last_digit_limit; int base, digit, sign; base = 16; if (**p == '-') { sign = -1; limit = ((uint64_t)(INT64_MAX) + 1) / base; last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base; ++(*p); } else { sign = 1; limit = INT64_MAX / base; last_digit_limit = INT64_MAX % base; } l = 0; digit = parsehex(**p); while (digit >= 0 && digit < base) { if (l > limit || (l == limit && digit > last_digit_limit)) return (sign < 0) ? INT64_MIN : INT64_MAX; l = (l * base) + digit; digit = parsehex(*++(*p)); } return (sign < 0) ? -l : l; } static int64_t mtree_atol(char **p) { if (**p != '0') return mtree_atol10(p); if ((*p)[1] == 'x' || (*p)[1] == 'X') { *p += 2; return mtree_atol16(p); } return mtree_atol8(p); } /* * Returns length of line (including trailing newline) * or negative on error. 'start' argument is updated to * point to first character of line. */ static ssize_t readline(struct archive_read *a, struct mtree *mtree, char **start, ssize_t limit) { ssize_t bytes_read; ssize_t total_size = 0; ssize_t find_off = 0; const void *t; void *nl; char *u; /* Accumulate line in a line buffer. */ for (;;) { /* Read some more. */ t = __archive_read_ahead(a, 1, &bytes_read); if (t == NULL) return (0); if (bytes_read < 0) return (ARCHIVE_FATAL); nl = memchr(t, '\n', bytes_read); /* If we found '\n', trim the read to end exactly there. */ if (nl != NULL) { bytes_read = ((const char *)nl) - ((const char *)t) + 1; } if (total_size + bytes_read + 1 > limit) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Line too long"); return (ARCHIVE_FATAL); } if (archive_string_ensure(&mtree->line, total_size + bytes_read + 1) == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate working buffer"); return (ARCHIVE_FATAL); } /* Append new bytes to string. */ memcpy(mtree->line.s + total_size, t, bytes_read); __archive_read_consume(a, bytes_read); total_size += bytes_read; mtree->line.s[total_size] = '\0'; for (u = mtree->line.s + find_off; *u; ++u) { if (u[0] == '\n') { /* Ends with unescaped newline. */ *start = mtree->line.s; return total_size; } else if (u[0] == '#') { /* Ends with comment sequence #...\n */ if (nl == NULL) { /* But we've not found the \n yet */ break; } } else if (u[0] == '\\') { if (u[1] == '\n') { /* Trim escaped newline. */ total_size -= 2; mtree->line.s[total_size] = '\0'; break; } else if (u[1] != '\0') { /* Skip the two-char escape sequence */ ++u; } } } find_off = u - mtree->line.s; } }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_5034_0
crossvul-cpp_data_good_3859_0
/****************************************************************************** * * Copyright(c) 2003 - 2011 Intel Corporation. All rights reserved. * * Portions of this file are derived from the ipw3945 project, as well * as portions of the ieee80211 subsystem header files. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * Intel Linux Wireless <ilw@linux.intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * *****************************************************************************/ #include <net/mac80211.h> #include "iwl-dev.h" #include "iwl-core.h" #include "iwl-agn.h" #include "iwl-trans.h" /* priv->shrd->sta_lock must be held */ static int iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id) { if (sta_id >= IWLAGN_STATION_COUNT) { IWL_ERR(priv, "invalid sta_id %u", sta_id); return -EINVAL; } if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u " "addr %pM\n", sta_id, priv->stations[sta_id].sta.sta.addr); if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_ASSOC(priv, "STA id %u addr %pM already present in uCode " "(according to driver)\n", sta_id, priv->stations[sta_id].sta.sta.addr); } else { priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE; IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n", sta_id, priv->stations[sta_id].sta.sta.addr); } return 0; } 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"); ret = iwl_sta_ucode_activate(priv, sta_id); 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; } int iwl_add_sta_callback(struct iwl_priv *priv, struct iwl_rx_mem_buffer *rxb, struct iwl_device_cmd *cmd) { struct iwl_rx_packet *pkt = rxb_addr(rxb); struct iwl_addsta_cmd *addsta = (struct iwl_addsta_cmd *) cmd->payload; return iwl_process_add_sta_resp(priv, addsta, pkt); } int iwl_send_add_sta(struct iwl_priv *priv, struct iwl_addsta_cmd *sta, u8 flags) { int ret = 0; struct iwl_host_cmd cmd = { .id = REPLY_ADD_STA, .flags = flags, .data = { sta, }, .len = { sizeof(*sta), }, }; u8 sta_id __maybe_unused = sta->sta.sta_id; IWL_DEBUG_INFO(priv, "Adding sta %u (%pM) %ssynchronously\n", sta_id, sta->sta.addr, flags & CMD_ASYNC ? "a" : ""); if (!(flags & CMD_ASYNC)) { cmd.flags |= CMD_WANT_SKB; might_sleep(); } ret = iwl_trans_send_cmd(trans(priv), &cmd); if (ret || (flags & CMD_ASYNC)) return ret; /*else the command was successfully sent in SYNC mode, need to free * the reply page */ iwl_free_pages(priv->shrd, cmd.reply_page); if (cmd.handler_status) IWL_ERR(priv, "%s - error in the CMD response %d", __func__, cmd.handler_status); return cmd.handler_status; } static void iwl_set_ht_add_station(struct iwl_priv *priv, u8 index, struct ieee80211_sta *sta, struct iwl_rxon_context *ctx) { struct ieee80211_sta_ht_cap *sta_ht_inf = &sta->ht_cap; __le32 sta_flags; u8 mimo_ps_mode; if (!sta || !sta_ht_inf->ht_supported) goto done; mimo_ps_mode = (sta_ht_inf->cap & IEEE80211_HT_CAP_SM_PS) >> 2; IWL_DEBUG_ASSOC(priv, "spatial multiplexing power save mode: %s\n", (mimo_ps_mode == WLAN_HT_CAP_SM_PS_STATIC) ? "static" : (mimo_ps_mode == WLAN_HT_CAP_SM_PS_DYNAMIC) ? "dynamic" : "disabled"); sta_flags = priv->stations[index].sta.station_flags; sta_flags &= ~(STA_FLG_RTS_MIMO_PROT_MSK | STA_FLG_MIMO_DIS_MSK); switch (mimo_ps_mode) { case WLAN_HT_CAP_SM_PS_STATIC: sta_flags |= STA_FLG_MIMO_DIS_MSK; break; case WLAN_HT_CAP_SM_PS_DYNAMIC: sta_flags |= STA_FLG_RTS_MIMO_PROT_MSK; break; case WLAN_HT_CAP_SM_PS_DISABLED: break; default: IWL_WARN(priv, "Invalid MIMO PS mode %d\n", mimo_ps_mode); break; } sta_flags |= cpu_to_le32( (u32)sta_ht_inf->ampdu_factor << STA_FLG_MAX_AGG_SIZE_POS); sta_flags |= cpu_to_le32( (u32)sta_ht_inf->ampdu_density << STA_FLG_AGG_MPDU_DENSITY_POS); if (iwl_is_ht40_tx_allowed(priv, ctx, &sta->ht_cap)) sta_flags |= STA_FLG_HT40_EN_MSK; else sta_flags &= ~STA_FLG_HT40_EN_MSK; priv->stations[index].sta.station_flags = sta_flags; done: return; } /** * iwl_prep_station - Prepare station information for addition * * should be called with sta_lock held */ u8 iwl_prep_station(struct iwl_priv *priv, struct iwl_rxon_context *ctx, const u8 *addr, bool is_ap, struct ieee80211_sta *sta) { struct iwl_station_entry *station; int i; u8 sta_id = IWL_INVALID_STATION; if (is_ap) sta_id = ctx->ap_sta_id; else if (is_broadcast_ether_addr(addr)) sta_id = ctx->bcast_sta_id; else for (i = IWL_STA_ID; i < IWLAGN_STATION_COUNT; i++) { if (!compare_ether_addr(priv->stations[i].sta.sta.addr, addr)) { sta_id = i; break; } if (!priv->stations[i].used && sta_id == IWL_INVALID_STATION) sta_id = i; } /* * These two conditions have the same outcome, but keep them * separate */ if (unlikely(sta_id == IWL_INVALID_STATION)) return sta_id; /* * uCode is not able to deal with multiple requests to add a * station. Keep track if one is in progress so that we do not send * another. */ if (priv->stations[sta_id].used & IWL_STA_UCODE_INPROGRESS) { IWL_DEBUG_INFO(priv, "STA %d already in process of being " "added.\n", sta_id); return sta_id; } if ((priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE) && (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) && !compare_ether_addr(priv->stations[sta_id].sta.sta.addr, addr)) { IWL_DEBUG_ASSOC(priv, "STA %d (%pM) already added, not " "adding again.\n", sta_id, addr); return sta_id; } station = &priv->stations[sta_id]; station->used = IWL_STA_DRIVER_ACTIVE; IWL_DEBUG_ASSOC(priv, "Add STA to driver ID %d: %pM\n", sta_id, addr); priv->num_stations++; /* Set up the REPLY_ADD_STA command to send to device */ memset(&station->sta, 0, sizeof(struct iwl_addsta_cmd)); memcpy(station->sta.sta.addr, addr, ETH_ALEN); station->sta.mode = 0; station->sta.sta.sta_id = sta_id; station->sta.station_flags = ctx->station_flags; station->ctxid = ctx->ctxid; if (sta) { struct iwl_station_priv *sta_priv; sta_priv = (void *)sta->drv_priv; sta_priv->ctx = ctx; } /* * OK to call unconditionally, since local stations (IBSS BSSID * STA and broadcast STA) pass in a NULL sta, and mac80211 * doesn't allow HT IBSS. */ iwl_set_ht_add_station(priv, sta_id, sta, ctx); return sta_id; } #define STA_WAIT_TIMEOUT (HZ/2) /** * iwl_add_station_common - */ int iwl_add_station_common(struct iwl_priv *priv, struct iwl_rxon_context *ctx, const u8 *addr, bool is_ap, struct ieee80211_sta *sta, u8 *sta_id_r) { unsigned long flags_spin; int ret = 0; u8 sta_id; struct iwl_addsta_cmd sta_cmd; *sta_id_r = 0; spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); sta_id = iwl_prep_station(priv, ctx, addr, is_ap, sta); if (sta_id == IWL_INVALID_STATION) { IWL_ERR(priv, "Unable to prepare station %pM for addition\n", addr); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); return -EINVAL; } /* * uCode is not able to deal with multiple requests to add a * station. Keep track if one is in progress so that we do not send * another. */ if (priv->stations[sta_id].used & IWL_STA_UCODE_INPROGRESS) { IWL_DEBUG_INFO(priv, "STA %d already in process of being " "added.\n", sta_id); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); return -EEXIST; } if ((priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE) && (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE)) { IWL_DEBUG_ASSOC(priv, "STA %d (%pM) already added, not " "adding again.\n", sta_id, addr); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); return -EEXIST; } priv->stations[sta_id].used |= IWL_STA_UCODE_INPROGRESS; memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(struct iwl_addsta_cmd)); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); /* Add station to device's station table */ ret = iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); if (ret) { spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); IWL_ERR(priv, "Adding station %pM failed.\n", priv->stations[sta_id].sta.sta.addr); priv->stations[sta_id].used &= ~IWL_STA_DRIVER_ACTIVE; priv->stations[sta_id].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); } *sta_id_r = sta_id; return ret; } /** * iwl_sta_ucode_deactivate - deactivate ucode status for a station * * priv->shrd->sta_lock must be held */ static void iwl_sta_ucode_deactivate(struct iwl_priv *priv, u8 sta_id) { /* Ucode must be active and driver must be non active */ if ((priv->stations[sta_id].used & (IWL_STA_UCODE_ACTIVE | IWL_STA_DRIVER_ACTIVE)) != IWL_STA_UCODE_ACTIVE) IWL_ERR(priv, "removed non active STA %u\n", sta_id); priv->stations[sta_id].used &= ~IWL_STA_UCODE_ACTIVE; memset(&priv->stations[sta_id], 0, sizeof(struct iwl_station_entry)); IWL_DEBUG_ASSOC(priv, "Removed STA %u\n", sta_id); } static int iwl_send_remove_station(struct iwl_priv *priv, const u8 *addr, int sta_id, bool temporary) { struct iwl_rx_packet *pkt; int ret; unsigned long flags_spin; struct iwl_rem_sta_cmd rm_sta_cmd; struct iwl_host_cmd cmd = { .id = REPLY_REMOVE_STA, .len = { sizeof(struct iwl_rem_sta_cmd), }, .flags = CMD_SYNC, .data = { &rm_sta_cmd, }, }; memset(&rm_sta_cmd, 0, sizeof(rm_sta_cmd)); rm_sta_cmd.num_sta = 1; memcpy(&rm_sta_cmd.addr, addr, ETH_ALEN); cmd.flags |= CMD_WANT_SKB; ret = iwl_trans_send_cmd(trans(priv), &cmd); if (ret) return ret; pkt = (struct iwl_rx_packet *)cmd.reply_page; if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) { IWL_ERR(priv, "Bad return from REPLY_REMOVE_STA (0x%08X)\n", pkt->hdr.flags); ret = -EIO; } if (!ret) { switch (pkt->u.rem_sta.status) { case REM_STA_SUCCESS_MSK: if (!temporary) { spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); iwl_sta_ucode_deactivate(priv, sta_id); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); } IWL_DEBUG_ASSOC(priv, "REPLY_REMOVE_STA PASSED\n"); break; default: ret = -EIO; IWL_ERR(priv, "REPLY_REMOVE_STA failed\n"); break; } } iwl_free_pages(priv->shrd, cmd.reply_page); return ret; } /** * iwl_remove_station - Remove driver's knowledge of station. */ int iwl_remove_station(struct iwl_priv *priv, const u8 sta_id, const u8 *addr) { unsigned long flags; u8 tid; if (!iwl_is_ready(priv->shrd)) { IWL_DEBUG_INFO(priv, "Unable to remove station %pM, device not ready.\n", addr); /* * It is typical for stations to be removed when we are * going down. Return success since device will be down * soon anyway */ return 0; } IWL_DEBUG_ASSOC(priv, "Removing STA from driver:%d %pM\n", sta_id, addr); if (WARN_ON(sta_id == IWL_INVALID_STATION)) return -EINVAL; spin_lock_irqsave(&priv->shrd->sta_lock, flags); if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) { IWL_DEBUG_INFO(priv, "Removing %pM but non DRIVER active\n", addr); goto out_err; } if (!(priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE)) { IWL_DEBUG_INFO(priv, "Removing %pM but non UCODE active\n", addr); goto out_err; } if (priv->stations[sta_id].used & IWL_STA_LOCAL) { kfree(priv->stations[sta_id].lq); priv->stations[sta_id].lq = NULL; } for (tid = 0; tid < IWL_MAX_TID_COUNT; tid++) memset(&priv->tid_data[sta_id][tid], 0, sizeof(priv->tid_data[sta_id][tid])); priv->stations[sta_id].used &= ~IWL_STA_DRIVER_ACTIVE; priv->num_stations--; if (WARN_ON(priv->num_stations < 0)) priv->num_stations = 0; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return iwl_send_remove_station(priv, addr, sta_id, false); out_err: spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return -EINVAL; } /** * iwl_clear_ucode_stations - clear ucode station table bits * * This function clears all the bits in the driver indicating * which stations are active in the ucode. Call when something * other than explicit station management would cause this in * the ucode, e.g. unassociated RXON. */ void iwl_clear_ucode_stations(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { int i; unsigned long flags_spin; bool cleared = false; IWL_DEBUG_INFO(priv, "Clearing ucode stations in driver\n"); spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); for (i = 0; i < IWLAGN_STATION_COUNT; i++) { if (ctx && ctx->ctxid != priv->stations[i].ctxid) continue; if (priv->stations[i].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_INFO(priv, "Clearing ucode active for station %d\n", i); priv->stations[i].used &= ~IWL_STA_UCODE_ACTIVE; cleared = true; } } spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); if (!cleared) IWL_DEBUG_INFO(priv, "No active stations found to be cleared\n"); } /** * iwl_restore_stations() - Restore driver known stations to device * * All stations considered active by driver, but not present in ucode, is * restored. * * Function sleeps. */ void iwl_restore_stations(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { struct iwl_addsta_cmd sta_cmd; struct iwl_link_quality_cmd lq; unsigned long flags_spin; int i; bool found = false; int ret; bool send_lq; if (!iwl_is_ready(priv->shrd)) { IWL_DEBUG_INFO(priv, "Not ready yet, not restoring any stations.\n"); return; } IWL_DEBUG_ASSOC(priv, "Restoring all known stations ... start.\n"); spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); for (i = 0; i < IWLAGN_STATION_COUNT; i++) { if (ctx->ctxid != priv->stations[i].ctxid) continue; if ((priv->stations[i].used & IWL_STA_DRIVER_ACTIVE) && !(priv->stations[i].used & IWL_STA_UCODE_ACTIVE)) { IWL_DEBUG_ASSOC(priv, "Restoring sta %pM\n", priv->stations[i].sta.sta.addr); priv->stations[i].sta.mode = 0; priv->stations[i].used |= IWL_STA_UCODE_INPROGRESS; found = true; } } for (i = 0; i < IWLAGN_STATION_COUNT; i++) { if ((priv->stations[i].used & IWL_STA_UCODE_INPROGRESS)) { memcpy(&sta_cmd, &priv->stations[i].sta, sizeof(struct iwl_addsta_cmd)); send_lq = false; if (priv->stations[i].lq) { if (priv->shrd->wowlan) iwl_sta_fill_lq(priv, ctx, i, &lq); else memcpy(&lq, priv->stations[i].lq, sizeof(struct iwl_link_quality_cmd)); send_lq = true; } spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); ret = iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); if (ret) { spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); IWL_ERR(priv, "Adding station %pM failed.\n", priv->stations[i].sta.sta.addr); priv->stations[i].used &= ~IWL_STA_DRIVER_ACTIVE; priv->stations[i].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); } /* * Rate scaling has already been initialized, send * current LQ command */ if (send_lq) iwl_send_lq_cmd(priv, ctx, &lq, CMD_SYNC, true); spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); priv->stations[i].used &= ~IWL_STA_UCODE_INPROGRESS; } } spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); if (!found) IWL_DEBUG_INFO(priv, "Restoring all known stations .... " "no stations to be restored.\n"); else IWL_DEBUG_INFO(priv, "Restoring all known stations .... " "complete.\n"); } void iwl_reprogram_ap_sta(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { unsigned long flags; int sta_id = ctx->ap_sta_id; int ret; struct iwl_addsta_cmd sta_cmd; struct iwl_link_quality_cmd lq; bool active, have_lq = false; spin_lock_irqsave(&priv->shrd->sta_lock, flags); if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) { spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return; } memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(sta_cmd)); sta_cmd.mode = 0; if (priv->stations[sta_id].lq) { memcpy(&lq, priv->stations[sta_id].lq, sizeof(lq)); have_lq = true; } active = priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE; priv->stations[sta_id].used &= ~IWL_STA_DRIVER_ACTIVE; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); if (active) { ret = iwl_send_remove_station( priv, priv->stations[sta_id].sta.sta.addr, sta_id, true); if (ret) IWL_ERR(priv, "failed to remove STA %pM (%d)\n", priv->stations[sta_id].sta.sta.addr, ret); } spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].used |= IWL_STA_DRIVER_ACTIVE; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); ret = iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); if (ret) IWL_ERR(priv, "failed to re-add STA %pM (%d)\n", priv->stations[sta_id].sta.sta.addr, ret); if (have_lq) iwl_send_lq_cmd(priv, ctx, &lq, CMD_SYNC, true); } int iwl_get_free_ucode_key_offset(struct iwl_priv *priv) { int i; for (i = 0; i < priv->sta_key_max_num; i++) if (!test_and_set_bit(i, &priv->ucode_key_table)) return i; return WEP_INVALID_OFFSET; } void iwl_dealloc_bcast_stations(struct iwl_priv *priv) { unsigned long flags; int i; spin_lock_irqsave(&priv->shrd->sta_lock, flags); for (i = 0; i < IWLAGN_STATION_COUNT; i++) { if (!(priv->stations[i].used & IWL_STA_BCAST)) continue; priv->stations[i].used &= ~IWL_STA_UCODE_ACTIVE; priv->num_stations--; if (WARN_ON(priv->num_stations < 0)) priv->num_stations = 0; kfree(priv->stations[i].lq); priv->stations[i].lq = NULL; } spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); } #ifdef CONFIG_IWLWIFI_DEBUG static void iwl_dump_lq_cmd(struct iwl_priv *priv, struct iwl_link_quality_cmd *lq) { int i; IWL_DEBUG_RATE(priv, "lq station id 0x%x\n", lq->sta_id); IWL_DEBUG_RATE(priv, "lq ant 0x%X 0x%X\n", lq->general_params.single_stream_ant_msk, lq->general_params.dual_stream_ant_msk); for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) IWL_DEBUG_RATE(priv, "lq index %d 0x%X\n", i, lq->rs_table[i].rate_n_flags); } #else static inline void iwl_dump_lq_cmd(struct iwl_priv *priv, struct iwl_link_quality_cmd *lq) { } #endif /** * is_lq_table_valid() - Test one aspect of LQ cmd for validity * * It sometimes happens when a HT rate has been in use and we * loose connectivity with AP then mac80211 will first tell us that the * current channel is not HT anymore before removing the station. In such a * scenario the RXON flags will be updated to indicate we are not * communicating HT anymore, but the LQ command may still contain HT rates. * Test for this to prevent driver from sending LQ command between the time * RXON flags are updated and when LQ command is updated. */ static bool is_lq_table_valid(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct iwl_link_quality_cmd *lq) { int i; if (ctx->ht.enabled) return true; IWL_DEBUG_INFO(priv, "Channel %u is not an HT channel\n", ctx->active.channel); for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) { if (le32_to_cpu(lq->rs_table[i].rate_n_flags) & RATE_MCS_HT_MSK) { IWL_DEBUG_INFO(priv, "index %d of LQ expects HT channel\n", i); return false; } } return true; } /** * iwl_send_lq_cmd() - Send link quality command * @init: This command is sent as part of station initialization right * after station has been added. * * The link quality command is sent as the last step of station creation. * This is the special case in which init is set and we call a callback in * this case to clear the state indicating that station creation is in * progress. */ int iwl_send_lq_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct iwl_link_quality_cmd *lq, u8 flags, bool init) { int ret = 0; unsigned long flags_spin; struct iwl_host_cmd cmd = { .id = REPLY_TX_LINK_QUALITY_CMD, .len = { sizeof(struct iwl_link_quality_cmd), }, .flags = flags, .data = { lq, }, }; if (WARN_ON(lq->sta_id == IWL_INVALID_STATION)) return -EINVAL; spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); if (!(priv->stations[lq->sta_id].used & IWL_STA_DRIVER_ACTIVE)) { spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); return -EINVAL; } spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); iwl_dump_lq_cmd(priv, lq); if (WARN_ON(init && (cmd.flags & CMD_ASYNC))) return -EINVAL; if (is_lq_table_valid(priv, ctx, lq)) ret = iwl_trans_send_cmd(trans(priv), &cmd); else ret = -EINVAL; if (cmd.flags & CMD_ASYNC) return ret; if (init) { IWL_DEBUG_INFO(priv, "init LQ command complete, " "clearing sta addition status for sta %d\n", lq->sta_id); spin_lock_irqsave(&priv->shrd->sta_lock, flags_spin); priv->stations[lq->sta_id].used &= ~IWL_STA_UCODE_INPROGRESS; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags_spin); } return ret; } void iwl_sta_fill_lq(struct iwl_priv *priv, struct iwl_rxon_context *ctx, u8 sta_id, struct iwl_link_quality_cmd *link_cmd) { int i, r; u32 rate_flags = 0; __le32 rate_n_flags; lockdep_assert_held(&priv->shrd->mutex); memset(link_cmd, 0, sizeof(*link_cmd)); /* Set up the rate scaling to start at selected rate, fall back * all the way down to 1M in IEEE order, and then spin on 1M */ if (priv->band == IEEE80211_BAND_5GHZ) r = IWL_RATE_6M_INDEX; else if (ctx && ctx->vif && ctx->vif->p2p) r = IWL_RATE_6M_INDEX; else r = IWL_RATE_1M_INDEX; if (r >= IWL_FIRST_CCK_RATE && r <= IWL_LAST_CCK_RATE) rate_flags |= RATE_MCS_CCK_MSK; rate_flags |= first_antenna(hw_params(priv).valid_tx_ant) << RATE_MCS_ANT_POS; rate_n_flags = iwl_hw_set_rate_n_flags(iwl_rates[r].plcp, rate_flags); for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++) link_cmd->rs_table[i].rate_n_flags = rate_n_flags; link_cmd->general_params.single_stream_ant_msk = first_antenna(hw_params(priv).valid_tx_ant); link_cmd->general_params.dual_stream_ant_msk = hw_params(priv).valid_tx_ant & ~first_antenna(hw_params(priv).valid_tx_ant); if (!link_cmd->general_params.dual_stream_ant_msk) { link_cmd->general_params.dual_stream_ant_msk = ANT_AB; } else if (num_of_ant(hw_params(priv).valid_tx_ant) == 2) { link_cmd->general_params.dual_stream_ant_msk = hw_params(priv).valid_tx_ant; } link_cmd->agg_params.agg_dis_start_th = LINK_QUAL_AGG_DISABLE_START_DEF; link_cmd->agg_params.agg_time_limit = cpu_to_le16(LINK_QUAL_AGG_TIME_LIMIT_DEF); link_cmd->sta_id = sta_id; } static struct iwl_link_quality_cmd * iwl_sta_alloc_lq(struct iwl_priv *priv, struct iwl_rxon_context *ctx, u8 sta_id) { struct iwl_link_quality_cmd *link_cmd; link_cmd = kzalloc(sizeof(struct iwl_link_quality_cmd), GFP_KERNEL); if (!link_cmd) { IWL_ERR(priv, "Unable to allocate memory for LQ cmd.\n"); return NULL; } iwl_sta_fill_lq(priv, ctx, sta_id, link_cmd); return link_cmd; } /* * iwlagn_add_bssid_station - Add the special IBSS BSSID station * * Function sleeps. */ int iwlagn_add_bssid_station(struct iwl_priv *priv, struct iwl_rxon_context *ctx, const u8 *addr, u8 *sta_id_r) { int ret; u8 sta_id; struct iwl_link_quality_cmd *link_cmd; unsigned long flags; if (sta_id_r) *sta_id_r = IWL_INVALID_STATION; ret = iwl_add_station_common(priv, ctx, addr, 0, NULL, &sta_id); if (ret) { IWL_ERR(priv, "Unable to add station %pM\n", addr); return ret; } if (sta_id_r) *sta_id_r = sta_id; spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].used |= IWL_STA_LOCAL; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); /* Set up default rate scaling table in device's station table */ link_cmd = iwl_sta_alloc_lq(priv, ctx, sta_id); if (!link_cmd) { IWL_ERR(priv, "Unable to initialize rate scaling for station %pM.\n", addr); return -ENOMEM; } ret = iwl_send_lq_cmd(priv, ctx, link_cmd, CMD_SYNC, true); if (ret) IWL_ERR(priv, "Link quality command failed (%d)\n", ret); spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].lq = link_cmd; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return 0; } /* * static WEP keys * * For each context, the device has a table of 4 static WEP keys * (one for each key index) that is updated with the following * commands. */ static int iwl_send_static_wepkey_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx, bool send_if_empty) { int i, not_empty = 0; u8 buff[sizeof(struct iwl_wep_cmd) + sizeof(struct iwl_wep_key) * WEP_KEYS_MAX]; struct iwl_wep_cmd *wep_cmd = (struct iwl_wep_cmd *)buff; size_t cmd_size = sizeof(struct iwl_wep_cmd); struct iwl_host_cmd cmd = { .id = ctx->wep_key_cmd, .data = { wep_cmd, }, .flags = CMD_SYNC, }; might_sleep(); memset(wep_cmd, 0, cmd_size + (sizeof(struct iwl_wep_key) * WEP_KEYS_MAX)); for (i = 0; i < WEP_KEYS_MAX ; i++) { wep_cmd->key[i].key_index = i; if (ctx->wep_keys[i].key_size) { wep_cmd->key[i].key_offset = i; not_empty = 1; } else { wep_cmd->key[i].key_offset = WEP_INVALID_OFFSET; } wep_cmd->key[i].key_size = ctx->wep_keys[i].key_size; memcpy(&wep_cmd->key[i].key[3], ctx->wep_keys[i].key, ctx->wep_keys[i].key_size); } wep_cmd->global_key_type = WEP_KEY_WEP_TYPE; wep_cmd->num_keys = WEP_KEYS_MAX; cmd_size += sizeof(struct iwl_wep_key) * WEP_KEYS_MAX; cmd.len[0] = cmd_size; if (not_empty || send_if_empty) return iwl_trans_send_cmd(trans(priv), &cmd); else return 0; } int iwl_restore_default_wep_keys(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { lockdep_assert_held(&priv->shrd->mutex); return iwl_send_static_wepkey_cmd(priv, ctx, false); } int iwl_remove_default_wep_key(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct ieee80211_key_conf *keyconf) { int ret; lockdep_assert_held(&priv->shrd->mutex); IWL_DEBUG_WEP(priv, "Removing default WEP key: idx=%d\n", keyconf->keyidx); memset(&ctx->wep_keys[keyconf->keyidx], 0, sizeof(ctx->wep_keys[0])); if (iwl_is_rfkill(priv->shrd)) { IWL_DEBUG_WEP(priv, "Not sending REPLY_WEPKEY command due to RFKILL.\n"); /* but keys in device are clear anyway so return success */ return 0; } ret = iwl_send_static_wepkey_cmd(priv, ctx, 1); IWL_DEBUG_WEP(priv, "Remove default WEP key: idx=%d ret=%d\n", keyconf->keyidx, ret); return ret; } int iwl_set_default_wep_key(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct ieee80211_key_conf *keyconf) { int ret; lockdep_assert_held(&priv->shrd->mutex); if (keyconf->keylen != WEP_KEY_LEN_128 && keyconf->keylen != WEP_KEY_LEN_64) { IWL_DEBUG_WEP(priv, "Bad WEP key length %d\n", keyconf->keylen); return -EINVAL; } keyconf->hw_key_idx = IWLAGN_HW_KEY_DEFAULT; ctx->wep_keys[keyconf->keyidx].key_size = keyconf->keylen; memcpy(&ctx->wep_keys[keyconf->keyidx].key, &keyconf->key, keyconf->keylen); ret = iwl_send_static_wepkey_cmd(priv, ctx, false); IWL_DEBUG_WEP(priv, "Set default WEP key: len=%d idx=%d ret=%d\n", keyconf->keylen, keyconf->keyidx, ret); return ret; } /* * dynamic (per-station) keys * * The dynamic keys are a little more complicated. The device has * a key cache of up to STA_KEY_MAX_NUM/STA_KEY_MAX_NUM_PAN keys. * These are linked to stations by a table that contains an index * into the key table for each station/key index/{mcast,unicast}, * i.e. it's basically an array of pointers like this: * key_offset_t key_mapping[NUM_STATIONS][4][2]; * (it really works differently, but you can think of it as such) * * The key uploading and linking happens in the same command, the * add station command with STA_MODIFY_KEY_MASK. */ static u8 iwlagn_key_sta_id(struct iwl_priv *priv, struct ieee80211_vif *vif, struct ieee80211_sta *sta) { struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv; u8 sta_id = IWL_INVALID_STATION; if (sta) sta_id = iwl_sta_id(sta); /* * The device expects GTKs for station interfaces to be * installed as GTKs for the AP station. If we have no * station ID, then use the ap_sta_id in that case. */ if (!sta && vif && vif_priv->ctx) { switch (vif->type) { case NL80211_IFTYPE_STATION: sta_id = vif_priv->ctx->ap_sta_id; break; default: /* * In all other cases, the key will be * used either for TX only or is bound * to a station already. */ break; } } return sta_id; } static int iwlagn_send_sta_key(struct iwl_priv *priv, struct ieee80211_key_conf *keyconf, u8 sta_id, u32 tkip_iv32, u16 *tkip_p1k, u32 cmd_flags) { unsigned long flags; __le16 key_flags; struct iwl_addsta_cmd sta_cmd; int i; spin_lock_irqsave(&priv->shrd->sta_lock, flags); memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(sta_cmd)); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); key_flags = cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS); key_flags |= STA_KEY_FLG_MAP_KEY_MSK; switch (keyconf->cipher) { case WLAN_CIPHER_SUITE_CCMP: key_flags |= STA_KEY_FLG_CCMP; memcpy(sta_cmd.key.key, keyconf->key, keyconf->keylen); break; case WLAN_CIPHER_SUITE_TKIP: key_flags |= STA_KEY_FLG_TKIP; sta_cmd.key.tkip_rx_tsc_byte2 = tkip_iv32; for (i = 0; i < 5; i++) sta_cmd.key.tkip_rx_ttak[i] = cpu_to_le16(tkip_p1k[i]); memcpy(sta_cmd.key.key, keyconf->key, keyconf->keylen); break; case WLAN_CIPHER_SUITE_WEP104: key_flags |= STA_KEY_FLG_KEY_SIZE_MSK; /* fall through */ case WLAN_CIPHER_SUITE_WEP40: key_flags |= STA_KEY_FLG_WEP; memcpy(&sta_cmd.key.key[3], keyconf->key, keyconf->keylen); break; default: WARN_ON(1); return -EINVAL; } if (!(keyconf->flags & IEEE80211_KEY_FLAG_PAIRWISE)) key_flags |= STA_KEY_MULTICAST_MSK; /* key pointer (offset) */ sta_cmd.key.key_offset = keyconf->hw_key_idx; sta_cmd.key.key_flags = key_flags; sta_cmd.mode = STA_CONTROL_MODIFY_MSK; sta_cmd.sta.modify_mask = STA_MODIFY_KEY_MASK; return iwl_send_add_sta(priv, &sta_cmd, cmd_flags); } void iwl_update_tkip_key(struct iwl_priv *priv, struct ieee80211_vif *vif, struct ieee80211_key_conf *keyconf, struct ieee80211_sta *sta, u32 iv32, u16 *phase1key) { u8 sta_id = iwlagn_key_sta_id(priv, vif, sta); if (sta_id == IWL_INVALID_STATION) return; if (iwl_scan_cancel(priv)) { /* cancel scan failed, just live w/ bad key and rely briefly on SW decryption */ return; } iwlagn_send_sta_key(priv, keyconf, sta_id, iv32, phase1key, CMD_ASYNC); } int iwl_remove_dynamic_key(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct ieee80211_key_conf *keyconf, struct ieee80211_sta *sta) { unsigned long flags; struct iwl_addsta_cmd sta_cmd; u8 sta_id = iwlagn_key_sta_id(priv, ctx->vif, sta); /* if station isn't there, neither is the key */ if (sta_id == IWL_INVALID_STATION) return -ENOENT; spin_lock_irqsave(&priv->shrd->sta_lock, flags); memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(sta_cmd)); if (!(priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE)) sta_id = IWL_INVALID_STATION; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); if (sta_id == IWL_INVALID_STATION) return 0; lockdep_assert_held(&priv->shrd->mutex); ctx->key_mapping_keys--; IWL_DEBUG_WEP(priv, "Remove dynamic key: idx=%d sta=%d\n", keyconf->keyidx, sta_id); if (!test_and_clear_bit(keyconf->hw_key_idx, &priv->ucode_key_table)) IWL_ERR(priv, "offset %d not used in uCode key table.\n", keyconf->hw_key_idx); sta_cmd.key.key_flags = STA_KEY_FLG_NO_ENC | STA_KEY_FLG_INVALID; sta_cmd.key.key_offset = WEP_INVALID_OFFSET; sta_cmd.sta.modify_mask = STA_MODIFY_KEY_MASK; sta_cmd.mode = STA_CONTROL_MODIFY_MSK; return iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); } int iwl_set_dynamic_key(struct iwl_priv *priv, struct iwl_rxon_context *ctx, struct ieee80211_key_conf *keyconf, struct ieee80211_sta *sta) { struct ieee80211_key_seq seq; u16 p1k[5]; int ret; u8 sta_id = iwlagn_key_sta_id(priv, ctx->vif, sta); const u8 *addr; if (sta_id == IWL_INVALID_STATION) return -EINVAL; lockdep_assert_held(&priv->shrd->mutex); keyconf->hw_key_idx = iwl_get_free_ucode_key_offset(priv); if (keyconf->hw_key_idx == WEP_INVALID_OFFSET) return -ENOSPC; ctx->key_mapping_keys++; switch (keyconf->cipher) { case WLAN_CIPHER_SUITE_TKIP: if (sta) addr = sta->addr; else /* station mode case only */ addr = ctx->active.bssid_addr; /* pre-fill phase 1 key into device cache */ ieee80211_get_key_rx_seq(keyconf, 0, &seq); ieee80211_get_tkip_rx_p1k(keyconf, addr, seq.tkip.iv32, p1k); ret = iwlagn_send_sta_key(priv, keyconf, sta_id, seq.tkip.iv32, p1k, CMD_SYNC); break; case WLAN_CIPHER_SUITE_CCMP: case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: ret = iwlagn_send_sta_key(priv, keyconf, sta_id, 0, NULL, CMD_SYNC); break; default: IWL_ERR(priv, "Unknown cipher %x\n", keyconf->cipher); ret = -EINVAL; } if (ret) { ctx->key_mapping_keys--; clear_bit(keyconf->hw_key_idx, &priv->ucode_key_table); } IWL_DEBUG_WEP(priv, "Set dynamic key: cipher=%x len=%d idx=%d sta=%pM ret=%d\n", keyconf->cipher, keyconf->keylen, keyconf->keyidx, sta ? sta->addr : NULL, ret); return ret; } /** * iwlagn_alloc_bcast_station - add broadcast station into driver's station table. * * This adds the broadcast station into the driver's station table * and marks it driver active, so that it will be restored to the * device at the next best time. */ int iwlagn_alloc_bcast_station(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { struct iwl_link_quality_cmd *link_cmd; unsigned long flags; u8 sta_id; spin_lock_irqsave(&priv->shrd->sta_lock, flags); sta_id = iwl_prep_station(priv, ctx, iwl_bcast_addr, false, NULL); if (sta_id == IWL_INVALID_STATION) { IWL_ERR(priv, "Unable to prepare broadcast station\n"); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return -EINVAL; } priv->stations[sta_id].used |= IWL_STA_DRIVER_ACTIVE; priv->stations[sta_id].used |= IWL_STA_BCAST; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); link_cmd = iwl_sta_alloc_lq(priv, ctx, sta_id); if (!link_cmd) { IWL_ERR(priv, "Unable to initialize rate scaling for bcast station.\n"); return -ENOMEM; } spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].lq = link_cmd; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return 0; } /** * iwl_update_bcast_station - update broadcast station's LQ command * * Only used by iwlagn. Placed here to have all bcast station management * code together. */ int iwl_update_bcast_station(struct iwl_priv *priv, struct iwl_rxon_context *ctx) { unsigned long flags; struct iwl_link_quality_cmd *link_cmd; u8 sta_id = ctx->bcast_sta_id; link_cmd = iwl_sta_alloc_lq(priv, ctx, sta_id); if (!link_cmd) { IWL_ERR(priv, "Unable to initialize rate scaling for bcast station.\n"); return -ENOMEM; } spin_lock_irqsave(&priv->shrd->sta_lock, flags); if (priv->stations[sta_id].lq) kfree(priv->stations[sta_id].lq); else IWL_DEBUG_INFO(priv, "Bcast station rate scaling has not been initialized yet.\n"); priv->stations[sta_id].lq = link_cmd; spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return 0; } int iwl_update_bcast_stations(struct iwl_priv *priv) { struct iwl_rxon_context *ctx; int ret = 0; for_each_context(priv, ctx) { ret = iwl_update_bcast_station(priv, ctx); if (ret) break; } return ret; } /** * iwl_sta_tx_modify_enable_tid - Enable Tx for this TID in station table */ int iwl_sta_tx_modify_enable_tid(struct iwl_priv *priv, int sta_id, int tid) { unsigned long flags; struct iwl_addsta_cmd sta_cmd; lockdep_assert_held(&priv->shrd->mutex); /* Remove "disable" flag, to enable Tx for this TID */ spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_TID_DISABLE_TX; priv->stations[sta_id].sta.tid_disable_tx &= cpu_to_le16(~(1 << tid)); priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK; memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(struct iwl_addsta_cmd)); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); } int iwl_sta_rx_agg_start(struct iwl_priv *priv, struct ieee80211_sta *sta, int tid, u16 ssn) { unsigned long flags; int sta_id; struct iwl_addsta_cmd sta_cmd; lockdep_assert_held(&priv->shrd->mutex); sta_id = iwl_sta_id(sta); if (sta_id == IWL_INVALID_STATION) return -ENXIO; spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].sta.station_flags_msk = 0; priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_ADDBA_TID_MSK; priv->stations[sta_id].sta.add_immediate_ba_tid = (u8)tid; priv->stations[sta_id].sta.add_immediate_ba_ssn = cpu_to_le16(ssn); priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK; memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(struct iwl_addsta_cmd)); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); } int iwl_sta_rx_agg_stop(struct iwl_priv *priv, struct ieee80211_sta *sta, int tid) { unsigned long flags; int sta_id; struct iwl_addsta_cmd sta_cmd; lockdep_assert_held(&priv->shrd->mutex); sta_id = iwl_sta_id(sta); if (sta_id == IWL_INVALID_STATION) { IWL_ERR(priv, "Invalid station for AGG tid %d\n", tid); return -ENXIO; } spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].sta.station_flags_msk = 0; priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_DELBA_TID_MSK; priv->stations[sta_id].sta.remove_immediate_ba_tid = (u8)tid; priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK; memcpy(&sta_cmd, &priv->stations[sta_id].sta, sizeof(struct iwl_addsta_cmd)); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); return iwl_send_add_sta(priv, &sta_cmd, CMD_SYNC); } void iwl_sta_modify_sleep_tx_count(struct iwl_priv *priv, int sta_id, int cnt) { unsigned long flags; spin_lock_irqsave(&priv->shrd->sta_lock, flags); priv->stations[sta_id].sta.station_flags |= STA_FLG_PWR_SAVE_MSK; priv->stations[sta_id].sta.station_flags_msk = STA_FLG_PWR_SAVE_MSK; priv->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_SLEEP_TX_COUNT_MSK; priv->stations[sta_id].sta.sleep_tx_count = cpu_to_le16(cnt); priv->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK; iwl_send_add_sta(priv, &priv->stations[sta_id].sta, CMD_ASYNC); spin_unlock_irqrestore(&priv->shrd->sta_lock, flags); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_3859_0
crossvul-cpp_data_good_342_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid = fs->cache.array[x].objectId.id; if (bufLen < 2) break; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count += 2; bufLen -= 2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-119/c/good_342_2
crossvul-cpp_data_bad_3674_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-119/c/bad_3674_0
crossvul-cpp_data_bad_2412_0
/* * symlink.c * * PURPOSE * Symlink handling routines for the OSTA-UDF(tm) filesystem. * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. * * (C) 1998-2001 Ben Fennema * (C) 1999 Stelias Computing Inc * * HISTORY * * 04/16/99 blf Created. * */ #include "udfdecl.h" #include <linux/uaccess.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/time.h> #include <linux/mm.h> #include <linux/stat.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include "udf_i.h" static void udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to) { struct pathComponent *pc; int elen = 0; unsigned char *p = to; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: p = to; *p++ = '/'; break; case 3: memcpy(p, "../", 3); p += 3; break; case 4: memcpy(p, "./", 2); p += 2; /* that would be . - just ignore */ break; case 5: p += udf_get_filename(sb, pc->componentIdent, p, pc->lengthComponentIdent); *p++ = '/'; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; } static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err = -EIO; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) goto out; symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out: up_read(&iinfo->i_data_sem); SetPageError(page); kunmap(page); unlock_page(page); return err; } /* * symlinks can't do much... */ const struct address_space_operations udf_symlink_aops = { .readpage = udf_symlink_filler, };
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2412_0
crossvul-cpp_data_good_552_4
/* * Boa, an http server * Copyright (C) 1999 Larry Doolittle <ldoolitt@boa.org> * Copyright (C) 2000-2005 Jon Nelson <jnelson@boa.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* $Id: sublog.c,v 1.6.2.6 2005/02/22 14:11:29 jnelson Exp $*/ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "compat.h" int open_pipe_fd(const char *command); int open_net_fd(const char *spec); int open_gen_fd(const char *spec); /* Like popen, but gives fd instead of FILE * */ int open_pipe_fd(const char *command) { int pipe_fds[2]; int pid; /* "man pipe" says "filedes[0] is for reading, * filedes[1] is for writing. */ if (pipe(pipe_fds) == -1) return -1; pid = fork(); if (pid == 0) { /* child */ close(pipe_fds[1]); if (pipe_fds[0] != 0) { dup2(pipe_fds[0], 0); close(pipe_fds[0]); } execl("/bin/sh", "sh", "-c", command, (char *) 0); exit(EXIT_FAILURE); } close(pipe_fds[0]); if (pid < 0) { close(pipe_fds[1]); return -1; } return pipe_fds[1]; } int open_net_fd(const char *spec) { char *p; int fd, port; struct sockaddr_in sa; struct hostent *he; p = strchr(spec, ':'); if (!p) return -1; *p++ = '\0'; port = strtol(p, NULL, 10); /* printf("Host %s, port %d\n",spec,port); */ sa.sin_family = PF_INET; sa.sin_port = htons(port); he = gethostbyname(spec); if (!he) { #ifdef HAVE_HERROR herror("open_net_fd"); #endif return -1; } memcpy(&sa.sin_addr, he->h_addr, he->h_length); /* printf("using ip %s\n",inet_ntoa(sa.sin_addr)); */ fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd < 0) return fd; if (connect(fd, (struct sockaddr *) &sa, sizeof (sa)) < 0) return -1; return fd; } int open_gen_fd(const char *spec) { int fd; if (*spec == '|') { fd = open_pipe_fd(spec + 1); } else if (*spec == ':') { fd = open_net_fd(spec + 1); } else { fd = open(spec, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP); } return fd; } #ifdef STANDALONE_TEST int main(int argc, char *argv[]) { char buff[1024]; int fd, nr, nw; if (argc < 2) { fprintf(stderr, "usage: %s output-filename\n" " %s |output-command\n" " %s :host:port\n", argv[0], argv[0], argv[0]); return 1; } fd = open_gen_fd(argv[1]); if (fd < 0) { perror("open_gen_fd"); exit(EXIT_FAILURE); } while ((nr = read(0, buff, sizeof (buff))) != 0) { if (nr < 0) { if (errno == EINTR) continue; perror("read"); exit(EXIT_FAILURE); } nw = write(fd, buff, nr); if (nw < 0) { perror("write"); exit(EXIT_FAILURE); } } close(fd); return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-119/c/good_552_4
crossvul-cpp_data_bad_811_0
#include "jsi.h" #include "jslex.h" #include "jsparse.h" #include "jscompile.h" #include "jsvalue.h" /* for jsV_numbertostring */ #define cexp jsC_cexp /* collision with math.h */ #define JF js_State *J, js_Function *F JS_NORETURN void jsC_error(js_State *J, js_Ast *node, const char *fmt, ...) JS_PRINTFLIKE(3,4); static void cfunbody(JF, js_Ast *name, js_Ast *params, js_Ast *body); static void cexp(JF, js_Ast *exp); static void cstmlist(JF, js_Ast *list); static void cstm(JF, js_Ast *stm); void jsC_error(js_State *J, js_Ast *node, const char *fmt, ...) { va_list ap; char buf[512]; char msgbuf[256]; va_start(ap, fmt); vsnprintf(msgbuf, 256, fmt, ap); va_end(ap); snprintf(buf, 256, "%s:%d: ", J->filename, node->line); strcat(buf, msgbuf); js_newsyntaxerror(J, buf); js_throw(J); } static const char *futurewords[] = { "class", "const", "enum", "export", "extends", "import", "super", }; static const char *strictfuturewords[] = { "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", }; static void checkfutureword(JF, js_Ast *exp) { if (jsY_findword(exp->string, futurewords, nelem(futurewords)) >= 0) jsC_error(J, exp, "'%s' is a future reserved word", exp->string); if (F->strict) { if (jsY_findword(exp->string, strictfuturewords, nelem(strictfuturewords)) >= 0) jsC_error(J, exp, "'%s' is a strict mode future reserved word", exp->string); } } static js_Function *newfun(js_State *J, int line, js_Ast *name, js_Ast *params, js_Ast *body, int script, int default_strict) { js_Function *F = js_malloc(J, sizeof *F); memset(F, 0, sizeof *F); F->gcmark = 0; F->gcnext = J->gcfun; J->gcfun = F; ++J->gccounter; F->filename = js_intern(J, J->filename); F->line = line; F->script = script; F->strict = default_strict; F->name = name ? name->string : ""; cfunbody(J, F, name, params, body); return F; } /* Emit opcodes, constants and jumps */ static void emitraw(JF, int value) { if (value != (js_Instruction)value) js_syntaxerror(J, "integer overflow in instruction coding"); if (F->codelen >= F->codecap) { F->codecap = F->codecap ? F->codecap * 2 : 64; F->code = js_realloc(J, F->code, F->codecap * sizeof *F->code); } F->code[F->codelen++] = value; } static void emit(JF, int value) { emitraw(J, F, F->lastline); emitraw(J, F, value); } static void emitarg(JF, int value) { emitraw(J, F, value); } static void emitline(JF, js_Ast *node) { F->lastline = node->line; } static int addfunction(JF, js_Function *value) { if (F->funlen >= F->funcap) { F->funcap = F->funcap ? F->funcap * 2 : 16; F->funtab = js_realloc(J, F->funtab, F->funcap * sizeof *F->funtab); } F->funtab[F->funlen] = value; return F->funlen++; } static int addnumber(JF, double value) { int i; for (i = 0; i < F->numlen; ++i) if (F->numtab[i] == value) return i; if (F->numlen >= F->numcap) { F->numcap = F->numcap ? F->numcap * 2 : 16; F->numtab = js_realloc(J, F->numtab, F->numcap * sizeof *F->numtab); } F->numtab[F->numlen] = value; return F->numlen++; } static int addstring(JF, const char *value) { int i; for (i = 0; i < F->strlen; ++i) if (!strcmp(F->strtab[i], value)) return i; if (F->strlen >= F->strcap) { F->strcap = F->strcap ? F->strcap * 2 : 16; F->strtab = js_realloc(J, F->strtab, F->strcap * sizeof *F->strtab); } F->strtab[F->strlen] = value; return F->strlen++; } static int addlocal(JF, js_Ast *ident, int reuse) { const char *name = ident->string; if (F->strict) { if (!strcmp(name, "arguments")) jsC_error(J, ident, "redefining 'arguments' is not allowed in strict mode"); if (!strcmp(name, "eval")) jsC_error(J, ident, "redefining 'eval' is not allowed in strict mode"); } else { if (!strcmp(name, "eval")) js_evalerror(J, "%s:%d: invalid use of 'eval'", J->filename, ident->line); } if (reuse || F->strict) { int i; for (i = 0; i < F->varlen; ++i) { if (!strcmp(F->vartab[i], name)) { if (reuse) return i+1; if (F->strict) jsC_error(J, ident, "duplicate formal parameter '%s'", name); } } } if (F->varlen >= F->varcap) { F->varcap = F->varcap ? F->varcap * 2 : 16; F->vartab = js_realloc(J, F->vartab, F->varcap * sizeof *F->vartab); } F->vartab[F->varlen] = name; return ++F->varlen; } static int findlocal(JF, const char *name) { int i; for (i = F->varlen; i > 0; --i) if (!strcmp(F->vartab[i-1], name)) return i; return -1; } static void emitfunction(JF, js_Function *fun) { F->lightweight = 0; emit(J, F, OP_CLOSURE); emitarg(J, F, addfunction(J, F, fun)); } static void emitnumber(JF, double num) { if (num == 0) { emit(J, F, OP_INTEGER); emitarg(J, F, 32768); if (signbit(num)) emit(J, F, OP_NEG); } else { double nv = num + 32768; js_Instruction iv = nv; if (nv == iv) { emit(J, F, OP_INTEGER); emitarg(J, F, iv); } else { emit(J, F, OP_NUMBER); emitarg(J, F, addnumber(J, F, num)); } } } static void emitstring(JF, int opcode, const char *str) { emit(J, F, opcode); emitarg(J, F, addstring(J, F, str)); } static void emitlocal(JF, int oploc, int opvar, js_Ast *ident) { int is_arguments = !strcmp(ident->string, "arguments"); int is_eval = !strcmp(ident->string, "eval"); int i; if (is_arguments) { F->lightweight = 0; F->arguments = 1; } checkfutureword(J, F, ident); if (F->strict && oploc == OP_SETLOCAL) { if (is_arguments) jsC_error(J, ident, "'arguments' is read-only in strict mode"); if (is_eval) jsC_error(J, ident, "'eval' is read-only in strict mode"); } if (is_eval) js_evalerror(J, "%s:%d: invalid use of 'eval'", J->filename, ident->line); i = findlocal(J, F, ident->string); if (i < 0) { emitstring(J, F, opvar, ident->string); } else { emit(J, F, oploc); emitarg(J, F, i); } } static int here(JF) { return F->codelen; } static int emitjump(JF, int opcode) { int inst; emit(J, F, opcode); inst = F->codelen; emitarg(J, F, 0); return inst; } static void emitjumpto(JF, int opcode, int dest) { emit(J, F, opcode); if (dest != (js_Instruction)dest) js_syntaxerror(J, "jump address integer overflow"); emitarg(J, F, dest); } static void labelto(JF, int inst, int addr) { if (addr != (js_Instruction)addr) js_syntaxerror(J, "jump address integer overflow"); F->code[inst] = addr; } static void label(JF, int inst) { labelto(J, F, inst, F->codelen); } /* Expressions */ static void ctypeof(JF, js_Ast *exp) { if (exp->a->type == EXP_IDENTIFIER) { emitline(J, F, exp->a); emitlocal(J, F, OP_GETLOCAL, OP_HASVAR, exp->a); } else { cexp(J, F, exp->a); } emitline(J, F, exp); emit(J, F, OP_TYPEOF); } static void cunary(JF, js_Ast *exp, int opcode) { cexp(J, F, exp->a); emitline(J, F, exp); emit(J, F, opcode); } static void cbinary(JF, js_Ast *exp, int opcode) { cexp(J, F, exp->a); cexp(J, F, exp->b); emitline(J, F, exp); emit(J, F, opcode); } static void carray(JF, js_Ast *list) { int i = 0; while (list) { if (list->a->type != EXP_UNDEF) { emitline(J, F, list->a); emitnumber(J, F, i++); cexp(J, F, list->a); emitline(J, F, list->a); emit(J, F, OP_INITPROP); } else { ++i; } list = list->b; } } static void checkdup(JF, js_Ast *list, js_Ast *end) { char nbuf[32], sbuf[32]; const char *needle, *straw; if (end->a->type == EXP_NUMBER) needle = jsV_numbertostring(J, nbuf, end->a->number); else needle = end->a->string; while (list->a != end) { if (list->a->type == end->type) { js_Ast *prop = list->a->a; if (prop->type == EXP_NUMBER) straw = jsV_numbertostring(J, sbuf, prop->number); else straw = prop->string; if (!strcmp(needle, straw)) jsC_error(J, list, "duplicate property '%s' in object literal", needle); } list = list->b; } } static void cobject(JF, js_Ast *list) { js_Ast *head = list; while (list) { js_Ast *kv = list->a; js_Ast *prop = kv->a; if (prop->type == AST_IDENTIFIER || prop->type == EXP_STRING) { emitline(J, F, prop); emitstring(J, F, OP_STRING, prop->string); } else if (prop->type == EXP_NUMBER) { emitline(J, F, prop); emitnumber(J, F, prop->number); } else { jsC_error(J, prop, "invalid property name in object initializer"); } if (F->strict) checkdup(J, F, head, kv); switch (kv->type) { default: /* impossible */ break; case EXP_PROP_VAL: cexp(J, F, kv->b); emitline(J, F, kv); emit(J, F, OP_INITPROP); break; case EXP_PROP_GET: emitfunction(J, F, newfun(J, prop->line, NULL, NULL, kv->c, 0, F->strict)); emitline(J, F, kv); emit(J, F, OP_INITGETTER); break; case EXP_PROP_SET: emitfunction(J, F, newfun(J, prop->line, NULL, kv->b, kv->c, 0, F->strict)); emitline(J, F, kv); emit(J, F, OP_INITSETTER); break; } list = list->b; } } static int cargs(JF, js_Ast *list) { int n = 0; while (list) { cexp(J, F, list->a); list = list->b; ++n; } return n; } static void cassign(JF, js_Ast *exp) { js_Ast *lhs = exp->a; js_Ast *rhs = exp->b; switch (lhs->type) { case EXP_IDENTIFIER: cexp(J, F, rhs); emitline(J, F, exp); emitlocal(J, F, OP_SETLOCAL, OP_SETVAR, lhs); break; case EXP_INDEX: cexp(J, F, lhs->a); cexp(J, F, lhs->b); cexp(J, F, rhs); emitline(J, F, exp); emit(J, F, OP_SETPROP); break; case EXP_MEMBER: cexp(J, F, lhs->a); cexp(J, F, rhs); emitline(J, F, exp); emitstring(J, F, OP_SETPROP_S, lhs->b->string); break; default: jsC_error(J, lhs, "invalid l-value in assignment"); } } static void cassignforin(JF, js_Ast *stm) { js_Ast *lhs = stm->a; if (stm->type == STM_FOR_IN_VAR) { if (lhs->b) jsC_error(J, lhs->b, "more than one loop variable in for-in statement"); emitline(J, F, lhs->a); emitlocal(J, F, OP_SETLOCAL, OP_SETVAR, lhs->a->a); /* list(var-init(ident)) */ emit(J, F, OP_POP); return; } switch (lhs->type) { case EXP_IDENTIFIER: emitline(J, F, lhs); emitlocal(J, F, OP_SETLOCAL, OP_SETVAR, lhs); emit(J, F, OP_POP); break; case EXP_INDEX: cexp(J, F, lhs->a); cexp(J, F, lhs->b); emitline(J, F, lhs); emit(J, F, OP_ROT3); emit(J, F, OP_SETPROP); emit(J, F, OP_POP); break; case EXP_MEMBER: cexp(J, F, lhs->a); emitline(J, F, lhs); emit(J, F, OP_ROT2); emitstring(J, F, OP_SETPROP_S, lhs->b->string); emit(J, F, OP_POP); break; default: jsC_error(J, lhs, "invalid l-value in for-in loop assignment"); } } static void cassignop1(JF, js_Ast *lhs) { switch (lhs->type) { case EXP_IDENTIFIER: emitline(J, F, lhs); emitlocal(J, F, OP_GETLOCAL, OP_GETVAR, lhs); break; case EXP_INDEX: cexp(J, F, lhs->a); cexp(J, F, lhs->b); emitline(J, F, lhs); emit(J, F, OP_DUP2); emit(J, F, OP_GETPROP); break; case EXP_MEMBER: cexp(J, F, lhs->a); emitline(J, F, lhs); emit(J, F, OP_DUP); emitstring(J, F, OP_GETPROP_S, lhs->b->string); break; default: jsC_error(J, lhs, "invalid l-value in assignment"); } } static void cassignop2(JF, js_Ast *lhs, int postfix) { switch (lhs->type) { case EXP_IDENTIFIER: emitline(J, F, lhs); if (postfix) emit(J, F, OP_ROT2); emitlocal(J, F, OP_SETLOCAL, OP_SETVAR, lhs); break; case EXP_INDEX: emitline(J, F, lhs); if (postfix) emit(J, F, OP_ROT4); emit(J, F, OP_SETPROP); break; case EXP_MEMBER: emitline(J, F, lhs); if (postfix) emit(J, F, OP_ROT3); emitstring(J, F, OP_SETPROP_S, lhs->b->string); break; default: jsC_error(J, lhs, "invalid l-value in assignment"); } } static void cassignop(JF, js_Ast *exp, int opcode) { js_Ast *lhs = exp->a; js_Ast *rhs = exp->b; cassignop1(J, F, lhs); cexp(J, F, rhs); emitline(J, F, exp); emit(J, F, opcode); cassignop2(J, F, lhs, 0); } static void cdelete(JF, js_Ast *exp) { js_Ast *arg = exp->a; switch (arg->type) { case EXP_IDENTIFIER: if (F->strict) jsC_error(J, exp, "delete on an unqualified name is not allowed in strict mode"); emitline(J, F, exp); emitlocal(J, F, OP_DELLOCAL, OP_DELVAR, arg); break; case EXP_INDEX: cexp(J, F, arg->a); cexp(J, F, arg->b); emitline(J, F, exp); emit(J, F, OP_DELPROP); break; case EXP_MEMBER: cexp(J, F, arg->a); emitline(J, F, exp); emitstring(J, F, OP_DELPROP_S, arg->b->string); break; default: jsC_error(J, exp, "invalid l-value in delete expression"); } } static void ceval(JF, js_Ast *fun, js_Ast *args) { int n = cargs(J, F, args); F->lightweight = 0; if (n == 0) emit(J, F, OP_UNDEF); else while (n-- > 1) emit(J, F, OP_POP); emit(J, F, OP_EVAL); } static void ccall(JF, js_Ast *fun, js_Ast *args) { int n; switch (fun->type) { case EXP_INDEX: cexp(J, F, fun->a); emit(J, F, OP_DUP); cexp(J, F, fun->b); emit(J, F, OP_GETPROP); emit(J, F, OP_ROT2); break; case EXP_MEMBER: cexp(J, F, fun->a); emit(J, F, OP_DUP); emitstring(J, F, OP_GETPROP_S, fun->b->string); emit(J, F, OP_ROT2); break; case EXP_IDENTIFIER: if (!strcmp(fun->string, "eval")) { ceval(J, F, fun, args); return; } /* fallthrough */ default: cexp(J, F, fun); emit(J, F, OP_UNDEF); break; } n = cargs(J, F, args); emit(J, F, OP_CALL); emitarg(J, F, n); } static void cexp(JF, js_Ast *exp) { int then, end; int n; switch (exp->type) { case EXP_STRING: emitline(J, F, exp); emitstring(J, F, OP_STRING, exp->string); break; case EXP_NUMBER: emitline(J, F, exp); emitnumber(J, F, exp->number); break; case EXP_UNDEF: emitline(J, F, exp); emit(J, F, OP_UNDEF); break; case EXP_NULL: emitline(J, F, exp); emit(J, F, OP_NULL); break; case EXP_TRUE: emitline(J, F, exp); emit(J, F, OP_TRUE); break; case EXP_FALSE: emitline(J, F, exp); emit(J, F, OP_FALSE); break; case EXP_THIS: emitline(J, F, exp); emit(J, F, OP_THIS); break; case EXP_REGEXP: emitline(J, F, exp); emit(J, F, OP_NEWREGEXP); emitarg(J, F, addstring(J, F, exp->string)); emitarg(J, F, exp->number); break; case EXP_OBJECT: emitline(J, F, exp); emit(J, F, OP_NEWOBJECT); cobject(J, F, exp->a); break; case EXP_ARRAY: emitline(J, F, exp); emit(J, F, OP_NEWARRAY); carray(J, F, exp->a); break; case EXP_FUN: emitline(J, F, exp); emitfunction(J, F, newfun(J, exp->line, exp->a, exp->b, exp->c, 0, F->strict)); break; case EXP_IDENTIFIER: emitline(J, F, exp); emitlocal(J, F, OP_GETLOCAL, OP_GETVAR, exp); break; case EXP_INDEX: cexp(J, F, exp->a); cexp(J, F, exp->b); emitline(J, F, exp); emit(J, F, OP_GETPROP); break; case EXP_MEMBER: cexp(J, F, exp->a); emitline(J, F, exp); emitstring(J, F, OP_GETPROP_S, exp->b->string); break; case EXP_CALL: ccall(J, F, exp->a, exp->b); break; case EXP_NEW: cexp(J, F, exp->a); n = cargs(J, F, exp->b); emitline(J, F, exp); emit(J, F, OP_NEW); emitarg(J, F, n); break; case EXP_DELETE: cdelete(J, F, exp); break; case EXP_PREINC: cassignop1(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_INC); cassignop2(J, F, exp->a, 0); break; case EXP_PREDEC: cassignop1(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_DEC); cassignop2(J, F, exp->a, 0); break; case EXP_POSTINC: cassignop1(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_POSTINC); cassignop2(J, F, exp->a, 1); emit(J, F, OP_POP); break; case EXP_POSTDEC: cassignop1(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_POSTDEC); cassignop2(J, F, exp->a, 1); emit(J, F, OP_POP); break; case EXP_VOID: cexp(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_POP); emit(J, F, OP_UNDEF); break; case EXP_TYPEOF: ctypeof(J, F, exp); break; case EXP_POS: cunary(J, F, exp, OP_POS); break; case EXP_NEG: cunary(J, F, exp, OP_NEG); break; case EXP_BITNOT: cunary(J, F, exp, OP_BITNOT); break; case EXP_LOGNOT: cunary(J, F, exp, OP_LOGNOT); break; case EXP_BITOR: cbinary(J, F, exp, OP_BITOR); break; case EXP_BITXOR: cbinary(J, F, exp, OP_BITXOR); break; case EXP_BITAND: cbinary(J, F, exp, OP_BITAND); break; case EXP_EQ: cbinary(J, F, exp, OP_EQ); break; case EXP_NE: cbinary(J, F, exp, OP_NE); break; case EXP_STRICTEQ: cbinary(J, F, exp, OP_STRICTEQ); break; case EXP_STRICTNE: cbinary(J, F, exp, OP_STRICTNE); break; case EXP_LT: cbinary(J, F, exp, OP_LT); break; case EXP_GT: cbinary(J, F, exp, OP_GT); break; case EXP_LE: cbinary(J, F, exp, OP_LE); break; case EXP_GE: cbinary(J, F, exp, OP_GE); break; case EXP_INSTANCEOF: cbinary(J, F, exp, OP_INSTANCEOF); break; case EXP_IN: cbinary(J, F, exp, OP_IN); break; case EXP_SHL: cbinary(J, F, exp, OP_SHL); break; case EXP_SHR: cbinary(J, F, exp, OP_SHR); break; case EXP_USHR: cbinary(J, F, exp, OP_USHR); break; case EXP_ADD: cbinary(J, F, exp, OP_ADD); break; case EXP_SUB: cbinary(J, F, exp, OP_SUB); break; case EXP_MUL: cbinary(J, F, exp, OP_MUL); break; case EXP_DIV: cbinary(J, F, exp, OP_DIV); break; case EXP_MOD: cbinary(J, F, exp, OP_MOD); break; case EXP_ASS: cassign(J, F, exp); break; case EXP_ASS_MUL: cassignop(J, F, exp, OP_MUL); break; case EXP_ASS_DIV: cassignop(J, F, exp, OP_DIV); break; case EXP_ASS_MOD: cassignop(J, F, exp, OP_MOD); break; case EXP_ASS_ADD: cassignop(J, F, exp, OP_ADD); break; case EXP_ASS_SUB: cassignop(J, F, exp, OP_SUB); break; case EXP_ASS_SHL: cassignop(J, F, exp, OP_SHL); break; case EXP_ASS_SHR: cassignop(J, F, exp, OP_SHR); break; case EXP_ASS_USHR: cassignop(J, F, exp, OP_USHR); break; case EXP_ASS_BITAND: cassignop(J, F, exp, OP_BITAND); break; case EXP_ASS_BITXOR: cassignop(J, F, exp, OP_BITXOR); break; case EXP_ASS_BITOR: cassignop(J, F, exp, OP_BITOR); break; case EXP_COMMA: cexp(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_POP); cexp(J, F, exp->b); break; case EXP_LOGOR: cexp(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_DUP); end = emitjump(J, F, OP_JTRUE); emit(J, F, OP_POP); cexp(J, F, exp->b); label(J, F, end); break; case EXP_LOGAND: cexp(J, F, exp->a); emitline(J, F, exp); emit(J, F, OP_DUP); end = emitjump(J, F, OP_JFALSE); emit(J, F, OP_POP); cexp(J, F, exp->b); label(J, F, end); break; case EXP_COND: cexp(J, F, exp->a); emitline(J, F, exp); then = emitjump(J, F, OP_JTRUE); cexp(J, F, exp->c); end = emitjump(J, F, OP_JUMP); label(J, F, then); cexp(J, F, exp->b); label(J, F, end); break; default: jsC_error(J, exp, "unknown expression: (%s)", jsP_aststring(exp->type)); } } /* Patch break and continue statements */ static void addjump(JF, enum js_AstType type, js_Ast *target, int inst) { js_JumpList *jump = js_malloc(J, sizeof *jump); jump->type = type; jump->inst = inst; jump->next = target->jumps; target->jumps = jump; } static void labeljumps(JF, js_JumpList *jump, int baddr, int caddr) { while (jump) { if (jump->type == STM_BREAK) labelto(J, F, jump->inst, baddr); if (jump->type == STM_CONTINUE) labelto(J, F, jump->inst, caddr); jump = jump->next; } } static int isloop(enum js_AstType T) { return T == STM_DO || T == STM_WHILE || T == STM_FOR || T == STM_FOR_VAR || T == STM_FOR_IN || T == STM_FOR_IN_VAR; } static int isfun(enum js_AstType T) { return T == AST_FUNDEC || T == EXP_FUN || T == EXP_PROP_GET || T == EXP_PROP_SET; } static int matchlabel(js_Ast *node, const char *label) { while (node && node->type == STM_LABEL) { if (!strcmp(node->a->string, label)) return 1; node = node->parent; } return 0; } static js_Ast *breaktarget(JF, js_Ast *node, const char *label) { while (node) { if (isfun(node->type)) break; if (!label) { if (isloop(node->type) || node->type == STM_SWITCH) return node; } else { if (matchlabel(node->parent, label)) return node; } node = node->parent; } return NULL; } static js_Ast *continuetarget(JF, js_Ast *node, const char *label) { while (node) { if (isfun(node->type)) break; if (isloop(node->type)) { if (!label) return node; else if (matchlabel(node->parent, label)) return node; } node = node->parent; } return NULL; } static js_Ast *returntarget(JF, js_Ast *node) { while (node) { if (isfun(node->type)) return node; node = node->parent; } return NULL; } /* Emit code to rebalance stack and scopes during an abrupt exit */ static void cexit(JF, enum js_AstType T, js_Ast *node, js_Ast *target) { js_Ast *prev; do { prev = node, node = node->parent; switch (node->type) { default: /* impossible */ break; case STM_WITH: emitline(J, F, node); emit(J, F, OP_ENDWITH); break; case STM_FOR_IN: case STM_FOR_IN_VAR: emitline(J, F, node); /* pop the iterator if leaving the loop */ if (F->script) { if (T == STM_RETURN || T == STM_BREAK || (T == STM_CONTINUE && target != node)) { /* pop the iterator, save the return or exp value */ emit(J, F, OP_ROT2); emit(J, F, OP_POP); } if (T == STM_CONTINUE) emit(J, F, OP_ROT2); /* put the iterator back on top */ } else { if (T == STM_RETURN) { /* pop the iterator, save the return value */ emit(J, F, OP_ROT2); emit(J, F, OP_POP); } if (T == STM_BREAK || (T == STM_CONTINUE && target != node)) emit(J, F, OP_POP); /* pop the iterator */ } break; case STM_TRY: emitline(J, F, node); /* came from try block */ if (prev == node->a) { emit(J, F, OP_ENDTRY); if (node->d) cstm(J, F, node->d); /* finally */ } /* came from catch block */ if (prev == node->c) { /* ... with finally */ if (node->d) { emit(J, F, OP_ENDCATCH); emit(J, F, OP_ENDTRY); cstm(J, F, node->d); /* finally */ } else { emit(J, F, OP_ENDCATCH); } } break; } } while (node != target); } /* Try/catch/finally */ static void ctryfinally(JF, js_Ast *trystm, js_Ast *finallystm) { int L1; L1 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the try block */ cstm(J, F, finallystm); /* inline finally block */ emit(J, F, OP_THROW); /* rethrow exception */ } label(J, F, L1); cstm(J, F, trystm); emit(J, F, OP_ENDTRY); cstm(J, F, finallystm); } static void ctrycatch(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm) { int L1, L2; L1 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the try block */ checkfutureword(J, F, catchvar); if (F->strict) { if (!strcmp(catchvar->string, "arguments")) jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode"); if (!strcmp(catchvar->string, "eval")) jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode"); } emitline(J, F, catchvar); emitstring(J, F, OP_CATCH, catchvar->string); cstm(J, F, catchstm); emit(J, F, OP_ENDCATCH); L2 = emitjump(J, F, OP_JUMP); /* skip past the try block */ } label(J, F, L1); cstm(J, F, trystm); emit(J, F, OP_ENDTRY); label(J, F, L2); } static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm) { int L1, L2, L3; L1 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the try block */ L2 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the catch block */ cstm(J, F, finallystm); /* inline finally block */ emit(J, F, OP_THROW); /* rethrow exception */ } label(J, F, L2); if (F->strict) { checkfutureword(J, F, catchvar); if (!strcmp(catchvar->string, "arguments")) jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode"); if (!strcmp(catchvar->string, "eval")) jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode"); } emitline(J, F, catchvar); emitstring(J, F, OP_CATCH, catchvar->string); cstm(J, F, catchstm); emit(J, F, OP_ENDCATCH); L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */ } label(J, F, L1); cstm(J, F, trystm); emit(J, F, OP_ENDTRY); label(J, F, L3); cstm(J, F, finallystm); } /* Switch */ static void cswitch(JF, js_Ast *ref, js_Ast *head) { js_Ast *node, *clause, *def = NULL; int end; cexp(J, F, ref); /* emit an if-else chain of tests for the case clause expressions */ for (node = head; node; node = node->b) { clause = node->a; if (clause->type == STM_DEFAULT) { if (def) jsC_error(J, clause, "more than one default label in switch"); def = clause; } else { cexp(J, F, clause->a); emitline(J, F, clause); clause->casejump = emitjump(J, F, OP_JCASE); } } emit(J, F, OP_POP); if (def) { emitline(J, F, def); def->casejump = emitjump(J, F, OP_JUMP); end = 0; } else { end = emitjump(J, F, OP_JUMP); } /* emit the case clause bodies */ for (node = head; node; node = node->b) { clause = node->a; label(J, F, clause->casejump); if (clause->type == STM_DEFAULT) cstmlist(J, F, clause->a); else cstmlist(J, F, clause->b); } if (end) label(J, F, end); } /* Statements */ static void cvarinit(JF, js_Ast *list) { while (list) { js_Ast *var = list->a; if (var->b) { cexp(J, F, var->b); emitline(J, F, var); emitlocal(J, F, OP_SETLOCAL, OP_SETVAR, var->a); emit(J, F, OP_POP); } list = list->b; } } static void cstm(JF, js_Ast *stm) { js_Ast *target; int loop, cont, then, end; emitline(J, F, stm); switch (stm->type) { case AST_FUNDEC: break; case STM_BLOCK: cstmlist(J, F, stm->a); break; case STM_EMPTY: if (F->script) { emitline(J, F, stm); emit(J, F, OP_POP); emit(J, F, OP_UNDEF); } break; case STM_VAR: cvarinit(J, F, stm->a); break; case STM_IF: if (stm->c) { cexp(J, F, stm->a); emitline(J, F, stm); then = emitjump(J, F, OP_JTRUE); cstm(J, F, stm->c); emitline(J, F, stm); end = emitjump(J, F, OP_JUMP); label(J, F, then); cstm(J, F, stm->b); label(J, F, end); } else { cexp(J, F, stm->a); emitline(J, F, stm); end = emitjump(J, F, OP_JFALSE); cstm(J, F, stm->b); label(J, F, end); } break; case STM_DO: loop = here(J, F); cstm(J, F, stm->a); cont = here(J, F); cexp(J, F, stm->b); emitline(J, F, stm); emitjumpto(J, F, OP_JTRUE, loop); labeljumps(J, F, stm->jumps, here(J,F), cont); break; case STM_WHILE: loop = here(J, F); cexp(J, F, stm->a); emitline(J, F, stm); end = emitjump(J, F, OP_JFALSE); cstm(J, F, stm->b); emitline(J, F, stm); emitjumpto(J, F, OP_JUMP, loop); label(J, F, end); labeljumps(J, F, stm->jumps, here(J,F), loop); break; case STM_FOR: case STM_FOR_VAR: if (stm->type == STM_FOR_VAR) { cvarinit(J, F, stm->a); } else { if (stm->a) { cexp(J, F, stm->a); emit(J, F, OP_POP); } } loop = here(J, F); if (stm->b) { cexp(J, F, stm->b); emitline(J, F, stm); end = emitjump(J, F, OP_JFALSE); } else { end = 0; } cstm(J, F, stm->d); cont = here(J, F); if (stm->c) { cexp(J, F, stm->c); emit(J, F, OP_POP); } emitline(J, F, stm); emitjumpto(J, F, OP_JUMP, loop); if (end) label(J, F, end); labeljumps(J, F, stm->jumps, here(J,F), cont); break; case STM_FOR_IN: case STM_FOR_IN_VAR: cexp(J, F, stm->b); emitline(J, F, stm); emit(J, F, OP_ITERATOR); loop = here(J, F); { emitline(J, F, stm); emit(J, F, OP_NEXTITER); end = emitjump(J, F, OP_JFALSE); cassignforin(J, F, stm); if (F->script) { emit(J, F, OP_ROT2); cstm(J, F, stm->c); emit(J, F, OP_ROT2); } else { cstm(J, F, stm->c); } emitline(J, F, stm); emitjumpto(J, F, OP_JUMP, loop); } label(J, F, end); labeljumps(J, F, stm->jumps, here(J,F), loop); break; case STM_SWITCH: cswitch(J, F, stm->a, stm->b); labeljumps(J, F, stm->jumps, here(J,F), 0); break; case STM_LABEL: cstm(J, F, stm->b); /* skip consecutive labels */ while (stm->type == STM_LABEL) stm = stm->b; /* loops and switches have already been labelled */ if (!isloop(stm->type) && stm->type != STM_SWITCH) labeljumps(J, F, stm->jumps, here(J,F), 0); break; case STM_BREAK: if (stm->a) { checkfutureword(J, F, stm->a); target = breaktarget(J, F, stm->parent, stm->a->string); if (!target) jsC_error(J, stm, "break label '%s' not found", stm->a->string); } else { target = breaktarget(J, F, stm->parent, NULL); if (!target) jsC_error(J, stm, "unlabelled break must be inside loop or switch"); } cexit(J, F, STM_BREAK, stm, target); emitline(J, F, stm); addjump(J, F, STM_BREAK, target, emitjump(J, F, OP_JUMP)); break; case STM_CONTINUE: if (stm->a) { checkfutureword(J, F, stm->a); target = continuetarget(J, F, stm->parent, stm->a->string); if (!target) jsC_error(J, stm, "continue label '%s' not found", stm->a->string); } else { target = continuetarget(J, F, stm->parent, NULL); if (!target) jsC_error(J, stm, "continue must be inside loop"); } cexit(J, F, STM_CONTINUE, stm, target); emitline(J, F, stm); addjump(J, F, STM_CONTINUE, target, emitjump(J, F, OP_JUMP)); break; case STM_RETURN: if (stm->a) cexp(J, F, stm->a); else emit(J, F, OP_UNDEF); target = returntarget(J, F, stm->parent); if (!target) jsC_error(J, stm, "return not in function"); cexit(J, F, STM_RETURN, stm, target); emitline(J, F, stm); emit(J, F, OP_RETURN); break; case STM_THROW: cexp(J, F, stm->a); emitline(J, F, stm); emit(J, F, OP_THROW); break; case STM_WITH: F->lightweight = 0; if (F->strict) jsC_error(J, stm->a, "'with' statements are not allowed in strict mode"); cexp(J, F, stm->a); emitline(J, F, stm); emit(J, F, OP_WITH); cstm(J, F, stm->b); emitline(J, F, stm); emit(J, F, OP_ENDWITH); break; case STM_TRY: emitline(J, F, stm); if (stm->b && stm->c) { F->lightweight = 0; if (stm->d) ctrycatchfinally(J, F, stm->a, stm->b, stm->c, stm->d); else ctrycatch(J, F, stm->a, stm->b, stm->c); } else { ctryfinally(J, F, stm->a, stm->d); } break; case STM_DEBUGGER: emitline(J, F, stm); emit(J, F, OP_DEBUGGER); break; default: if (F->script) { emitline(J, F, stm); emit(J, F, OP_POP); cexp(J, F, stm); } else { cexp(J, F, stm); emitline(J, F, stm); emit(J, F, OP_POP); } break; } } static void cstmlist(JF, js_Ast *list) { while (list) { cstm(J, F, list->a); list = list->b; } } /* Declarations and programs */ static int listlength(js_Ast *list) { int n = 0; while (list) ++n, list = list->b; return n; } static void cparams(JF, js_Ast *list, js_Ast *fname) { F->numparams = listlength(list); while (list) { checkfutureword(J, F, list->a); addlocal(J, F, list->a, 0); list = list->b; } } static void cvardecs(JF, js_Ast *node) { if (node->type == AST_LIST) { while (node) { cvardecs(J, F, node->a); node = node->b; } return; } if (isfun(node->type)) return; /* stop at inner functions */ if (node->type == EXP_VAR) { checkfutureword(J, F, node->a); addlocal(J, F, node->a, 1); } if (node->a) cvardecs(J, F, node->a); if (node->b) cvardecs(J, F, node->b); if (node->c) cvardecs(J, F, node->c); if (node->d) cvardecs(J, F, node->d); } static void cfundecs(JF, js_Ast *list) { while (list) { js_Ast *stm = list->a; if (stm->type == AST_FUNDEC) { emitline(J, F, stm); emitfunction(J, F, newfun(J, stm->line, stm->a, stm->b, stm->c, 0, F->strict)); emitline(J, F, stm); emit(J, F, OP_SETLOCAL); emitarg(J, F, addlocal(J, F, stm->a, 0)); emit(J, F, OP_POP); } list = list->b; } } static void cfunbody(JF, js_Ast *name, js_Ast *params, js_Ast *body) { F->lightweight = 1; F->arguments = 0; if (F->script) F->lightweight = 0; /* Check if first statement is 'use strict': */ if (body && body->type == AST_LIST && body->a && body->a->type == EXP_STRING) if (!strcmp(body->a->string, "use strict")) F->strict = 1; F->lastline = F->line; cparams(J, F, params, name); if (body) { cvardecs(J, F, body); cfundecs(J, F, body); } if (name) { checkfutureword(J, F, name); if (findlocal(J, F, name->string) < 0) { emit(J, F, OP_CURRENT); emit(J, F, OP_SETLOCAL); emitarg(J, F, addlocal(J, F, name, 0)); emit(J, F, OP_POP); } } if (F->script) { emit(J, F, OP_UNDEF); cstmlist(J, F, body); emit(J, F, OP_RETURN); } else { cstmlist(J, F, body); emit(J, F, OP_UNDEF); emit(J, F, OP_RETURN); } } js_Function *jsC_compilefunction(js_State *J, js_Ast *prog) { return newfun(J, prog->line, prog->a, prog->b, prog->c, 0, J->default_strict); } js_Function *jsC_compilescript(js_State *J, js_Ast *prog, int default_strict) { return newfun(J, prog ? prog->line : 0, NULL, NULL, prog, 1, default_strict); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_811_0
crossvul-cpp_data_bad_2511_0
/* * Copyright 2015, Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #define _GNU_SOURCE #include <errno.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <scsi/scsi.h> #include <glusterfs/api/glfs.h> #include "darray.h" #include "tcmu-runner.h" #define ALLOWED_BSOFLAGS (O_SYNC | O_DIRECT | O_RDWR | O_LARGEFILE) #define GLUSTER_PORT "24007" #define TCMU_GLFS_LOG_FILENAME "tcmu-runner-glfs.log" /* MAX 32 CHAR */ #define TCMU_GLFS_DEBUG_LEVEL 4 /* tcmu log dir path */ extern char *tcmu_log_dir; typedef enum gluster_transport { GLUSTER_TRANSPORT_TCP, GLUSTER_TRANSPORT_UNIX, GLUSTER_TRANSPORT_RDMA, GLUSTER_TRANSPORT__MAX, } gluster_transport; typedef struct unix_sockaddr { char *socket; } unix_sockaddr; typedef struct inet_sockaddr { char *addr; char *port; } inet_sockaddr; typedef struct gluster_hostdef { gluster_transport type; union { /* union tag is @type */ unix_sockaddr uds; inet_sockaddr inet; } u; } gluster_hostdef; typedef struct gluster_server { char *volname; /* volume name*/ char *path; /* path of file in the volume */ gluster_hostdef *server; /* gluster server definition */ } gluster_server; struct glfs_state { glfs_t *fs; glfs_fd_t *gfd; gluster_server *hosts; /* * Current tcmu helper API reports WCE=1, but doesn't * implement inquiry VPD 0xb2, so clients will not know UNMAP * or WRITE_SAME are supported. TODO: fix this */ }; typedef struct glfs_cbk_cookie { struct tcmu_device *dev; struct tcmulib_cmd *cmd; size_t length; enum { TCMU_GLFS_READ = 1, TCMU_GLFS_WRITE = 2, TCMU_GLFS_FLUSH = 3 } op; } glfs_cbk_cookie; struct gluster_cacheconn { char *volname; gluster_hostdef *server; glfs_t *fs; darray(char *) cfgstring; } gluster_cacheconn; static darray(struct gluster_cacheconn *) cache = darray_new(); const char *const gluster_transport_lookup[] = { [GLUSTER_TRANSPORT_TCP] = "tcp", [GLUSTER_TRANSPORT_UNIX] = "unix", [GLUSTER_TRANSPORT_RDMA] = "rdma", [GLUSTER_TRANSPORT__MAX] = NULL, }; static void gluster_free_host(gluster_hostdef *host) { if(!host) return; switch (host->type) { case GLUSTER_TRANSPORT_UNIX: free(host->u.uds.socket); break; case GLUSTER_TRANSPORT_TCP: case GLUSTER_TRANSPORT_RDMA: free(host->u.inet.addr); free(host->u.inet.port); break; case GLUSTER_TRANSPORT__MAX: break; } } static bool gluster_compare_hosts(gluster_hostdef *src_server, gluster_hostdef *dst_server) { if (src_server->type != dst_server->type) return false; switch (src_server->type) { case GLUSTER_TRANSPORT_UNIX: if (!strcmp(src_server->u.uds.socket, dst_server->u.uds.socket)) return true; break; case GLUSTER_TRANSPORT_TCP: case GLUSTER_TRANSPORT_RDMA: if (!strcmp(src_server->u.inet.addr, dst_server->u.inet.addr) && !strcmp(src_server->u.inet.port, dst_server->u.inet.port)) return true; break; case GLUSTER_TRANSPORT__MAX: break; } return false; } static int gluster_cache_add(gluster_server *dst, glfs_t *fs, char* cfgstring) { struct gluster_cacheconn *entry; char* cfg_copy = NULL; entry = calloc(1, sizeof(gluster_cacheconn)); if (!entry) goto error; entry->volname = strdup(dst->volname); entry->server = calloc(1, sizeof(gluster_hostdef)); if (!entry->server) goto error; entry->server->type = dst->server->type; if (entry->server->type == GLUSTER_TRANSPORT_UNIX) { entry->server->u.uds.socket = strdup(dst->server->u.uds.socket); } else { entry->server->u.inet.addr = strdup(dst->server->u.inet.addr); entry->server->u.inet.port = strdup(dst->server->u.inet.port); } entry->fs = fs; cfg_copy = strdup(cfgstring); darray_init(entry->cfgstring); darray_append(entry->cfgstring, cfg_copy); darray_append(cache, entry); return 0; error: return -1; } static glfs_t* gluster_cache_query(gluster_server *dst, char *cfgstring) { struct gluster_cacheconn **entry; char** config; char* cfg_copy = NULL; bool cfgmatch = false; darray_foreach(entry, cache) { if (strcmp((*entry)->volname, dst->volname)) continue; if (gluster_compare_hosts((*entry)->server, dst->server)) { darray_foreach(config, (*entry)->cfgstring) { if (!strcmp(*config, cfgstring)) { cfgmatch = true; break; } } if (!cfgmatch) { cfg_copy = strdup(cfgstring); darray_append((*entry)->cfgstring, cfg_copy); } return (*entry)->fs; } } return NULL; } static void gluster_cache_refresh(glfs_t *fs, const char *cfgstring) { struct gluster_cacheconn **entry; char** config; size_t i = 0; size_t j = 0; if (!fs) return; darray_foreach(entry, cache) { if ((*entry)->fs == fs) { if (cfgstring) { darray_foreach(config, (*entry)->cfgstring) { if (!strcmp(*config, cfgstring)) { free(*config); darray_remove((*entry)->cfgstring, j); break; } j++; } } if (darray_size((*entry)->cfgstring)) return; free((*entry)->volname); glfs_fini((*entry)->fs); (*entry)->fs = NULL; gluster_free_host((*entry)->server); free((*entry)->server); (*entry)->server = NULL; free((*entry)); darray_remove(cache, i); return; } else { i++; } } } static void gluster_free_server(gluster_server **hosts) { if (!*hosts) return; free((*hosts)->volname); free((*hosts)->path); gluster_free_host((*hosts)->server); free((*hosts)->server); (*hosts)->server = NULL; free(*hosts); *hosts = NULL; } /* * Break image string into server, volume, and path components. * Returns -1 on failure. */ static int parse_imagepath(char *cfgstring, gluster_server **hosts) { gluster_server *entry = NULL; char *origp = strdup(cfgstring); char *p, *sep; if (!origp) goto fail; /* part before '@' is the volume name */ p = origp; sep = strchr(p, '@'); if (!sep) goto fail; *hosts = calloc(1, sizeof(gluster_server)); if (!hosts) goto fail; entry = *hosts; entry->server = calloc(1, sizeof(gluster_hostdef)); if (!entry->server) goto fail; *sep = '\0'; entry->volname = strdup(p); if (!entry->volname) goto fail; /* part between '@' and 1st '/' is the server name */ p = sep + 1; sep = strchr(p, '/'); if (!sep) goto fail; *sep = '\0'; entry->server->type = GLUSTER_TRANSPORT_TCP; /* FIXME: Get type dynamically */ entry->server->u.inet.addr = strdup(p); if (!entry->server->u.inet.addr) goto fail; entry->server->u.inet.port = strdup(GLUSTER_PORT); /* FIXME: Get port dynamically */ /* The rest is the path name */ p = sep + 1; entry->path = strdup(p); if (!entry->path) goto fail; if (entry->server->type == GLUSTER_TRANSPORT_UNIX) { if (!strlen(entry->server->u.uds.socket) || !strlen(entry->volname) || !strlen(entry->path)) goto fail; } else { if (!strlen(entry->server->u.inet.addr) || !strlen(entry->volname) || !strlen(entry->path)) goto fail; } free(origp); return 0; fail: gluster_free_server(hosts); free(origp); return -1; } static glfs_t* tcmu_create_glfs_object(char *config, gluster_server **hosts) { gluster_server *entry = NULL; char logfilepath[PATH_MAX]; glfs_t *fs = NULL; int ret = -1; if (parse_imagepath(config, hosts) == -1) { tcmu_err("hostaddr, volname, or path missing\n"); goto fail; } entry = *hosts; fs = gluster_cache_query(entry, config); if (fs) return fs; fs = glfs_new(entry->volname); if (!fs) { tcmu_err("glfs_new failed\n"); goto fail; } ret = gluster_cache_add(entry, fs, config); if (ret) { tcmu_err("gluster_cache_add failed: %m\n"); goto fail; } ret = glfs_set_volfile_server(fs, gluster_transport_lookup[entry->server->type], entry->server->u.inet.addr, atoi(entry->server->u.inet.port)); if (ret) { tcmu_err("glfs_set_volfile_server failed: %m\n"); goto unref; } ret = tcmu_make_absolute_logfile(logfilepath, TCMU_GLFS_LOG_FILENAME); if (ret < 0) { tcmu_err("tcmu_make_absolute_logfile failed: %m\n"); goto unref; } ret = glfs_set_logging(fs, logfilepath, TCMU_GLFS_DEBUG_LEVEL); if (ret < 0) { tcmu_err("glfs_set_logging failed: %m\n"); goto unref; } ret = glfs_init(fs); if (ret) { tcmu_err("glfs_init failed: %m\n"); goto unref; } return fs; unref: gluster_cache_refresh(fs, config); fail: gluster_free_server(hosts); return NULL; } static char* tcmu_get_path( struct tcmu_device *dev) { char *config; config = strchr(tcmu_get_dev_cfgstring(dev), '/'); if (!config) { tcmu_err("no configuration found in cfgstring\n"); return NULL; } config += 1; /* get past '/' */ return config; } static bool glfs_check_config(const char *cfgstring, char **reason) { char *path; glfs_t *fs = NULL; glfs_fd_t *gfd = NULL; gluster_server *hosts = NULL; /* gluster server defination */ bool result = true; path = strchr(cfgstring, '/'); if (!path) { if (asprintf(reason, "No path found") == -1) *reason = NULL; result = false; goto done; } path += 1; /* get past '/' */ fs = tcmu_create_glfs_object(path, &hosts); if (!fs) { tcmu_err("tcmu_create_glfs_object failed\n"); goto done; } gfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS); if (!gfd) { if (asprintf(reason, "glfs_open failed: %m") == -1) *reason = NULL; result = false; goto unref; } if (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) { if (asprintf(reason, "glfs_access file not present, or not writable") == -1) *reason = NULL; result = false; goto unref; } goto done; unref: gluster_cache_refresh(fs, path); done: if (gfd) glfs_close(gfd); gluster_free_server(&hosts); return result; } static int tcmu_glfs_open(struct tcmu_device *dev) { struct glfs_state *gfsp; int ret = 0; char *config; struct stat st; gfsp = calloc(1, sizeof(*gfsp)); if (!gfsp) return -ENOMEM; tcmu_set_dev_private(dev, gfsp); config = tcmu_get_path(dev); if (!config) { goto fail; } gfsp->fs = tcmu_create_glfs_object(config, &gfsp->hosts); if (!gfsp->fs) { tcmu_err("tcmu_create_glfs_object failed\n"); goto fail; } gfsp->gfd = glfs_open(gfsp->fs, gfsp->hosts->path, ALLOWED_BSOFLAGS); if (!gfsp->gfd) { tcmu_err("glfs_open failed: %m\n"); goto unref; } ret = glfs_lstat(gfsp->fs, gfsp->hosts->path, &st); if (ret) { tcmu_err("glfs_lstat failed: %m\n"); goto unref; } if (st.st_size != tcmu_get_device_size(dev)) { tcmu_err("device size and backing size disagree: " "device %lld backing %lld\n", tcmu_get_device_size(dev), (long long) st.st_size); goto unref; } return 0; unref: gluster_cache_refresh(gfsp->fs, tcmu_get_path(dev)); fail: if (gfsp->gfd) glfs_close(gfsp->gfd); gluster_free_server(&gfsp->hosts); free(gfsp); return -EIO; } static void tcmu_glfs_close(struct tcmu_device *dev) { struct glfs_state *gfsp = tcmu_get_dev_private(dev); glfs_close(gfsp->gfd); gluster_cache_refresh(gfsp->fs, tcmu_get_path(dev)); gluster_free_server(&gfsp->hosts); free(gfsp); } static void glfs_async_cbk(glfs_fd_t *fd, ssize_t ret, void *data) { glfs_cbk_cookie *cookie = data; struct tcmu_device *dev = cookie->dev; struct tcmulib_cmd *cmd = cookie->cmd; size_t length = cookie->length; if (ret < 0 || ret != length) { /* Read/write/flush failed */ switch (cookie->op) { case TCMU_GLFS_READ: ret = tcmu_set_sense_data(cmd->sense_buf, MEDIUM_ERROR, ASC_READ_ERROR, NULL); break; case TCMU_GLFS_WRITE: case TCMU_GLFS_FLUSH: ret = tcmu_set_sense_data(cmd->sense_buf, MEDIUM_ERROR, ASC_WRITE_ERROR, NULL); break; } } else { ret = SAM_STAT_GOOD; } cmd->done(dev, cmd, ret); free(cookie); } static int tcmu_glfs_read(struct tcmu_device *dev, struct tcmulib_cmd *cmd, struct iovec *iov, size_t iov_cnt, size_t length, off_t offset) { struct glfs_state *state = tcmu_get_dev_private(dev); glfs_cbk_cookie *cookie; cookie = calloc(1, sizeof(*cookie)); if (!cookie) { tcmu_err("Could not allocate cookie: %m\n"); goto out; } cookie->dev = dev; cookie->cmd = cmd; cookie->length = length; cookie->op = TCMU_GLFS_READ; if (glfs_preadv_async(state->gfd, iov, iov_cnt, offset, SEEK_SET, glfs_async_cbk, cookie) < 0) { tcmu_err("glfs_preadv_async failed: %m\n"); goto out; } return 0; out: free(cookie); return SAM_STAT_TASK_SET_FULL; } static int tcmu_glfs_write(struct tcmu_device *dev, struct tcmulib_cmd *cmd, struct iovec *iov, size_t iov_cnt, size_t length, off_t offset) { struct glfs_state *state = tcmu_get_dev_private(dev); glfs_cbk_cookie *cookie; cookie = calloc(1, sizeof(*cookie)); if (!cookie) { tcmu_err("Could not allocate cookie: %m\n"); goto out; } cookie->dev = dev; cookie->cmd = cmd; cookie->length = length; cookie->op = TCMU_GLFS_WRITE; if (glfs_pwritev_async(state->gfd, iov, iov_cnt, offset, ALLOWED_BSOFLAGS, glfs_async_cbk, cookie) < 0) { tcmu_err("glfs_pwritev_async failed: %m\n"); goto out; } return 0; out: free(cookie); return SAM_STAT_TASK_SET_FULL; } static int tcmu_glfs_flush(struct tcmu_device *dev, struct tcmulib_cmd *cmd) { struct glfs_state *state = tcmu_get_dev_private(dev); glfs_cbk_cookie *cookie; cookie = calloc(1, sizeof(*cookie)); if (!cookie) { tcmu_err("Could not allocate cookie: %m\n"); goto out; } cookie->dev = dev; cookie->cmd = cmd; cookie->length = 0; cookie->op = TCMU_GLFS_FLUSH; if (glfs_fdatasync_async(state->gfd, glfs_async_cbk, cookie) < 0) { tcmu_err("glfs_fdatasync_async failed: %m\n"); goto out; } return 0; out: free(cookie); return SAM_STAT_TASK_SET_FULL; } static const char glfs_cfg_desc[] = "glfs config string is of the form:\n" "\"volume@hostname/filename\"\n" "where:\n" " volume: The volume on the Gluster server\n" " hostname: The server's hostname\n" " filename: The backing file"; struct tcmur_handler glfs_handler = { .name = "Gluster glfs handler", .subtype = "glfs", .cfg_desc = glfs_cfg_desc, .check_config = glfs_check_config, .open = tcmu_glfs_open, .close = tcmu_glfs_close, .read = tcmu_glfs_read, .write = tcmu_glfs_write, .flush = tcmu_glfs_flush, }; /* Entry point must be named "handler_init". */ int handler_init(void) { return tcmur_register_handler(&glfs_handler); }
./CrossVul/dataset_final_sorted/CWE-119/c/bad_2511_0
crossvul-cpp_data_good_5512_0
/* $Id$ */ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gd_intern.h" /* 2.03: don't include zlib here or we can't build without PNG */ #include "gd.h" #include "gdhelpers.h" #include "gd_color.h" #include "gd_errors.h" /* 2.0.12: this now checks the clipping rectangle */ #define gdImageBoundsSafeMacro(im, x, y) (!((((y) < (im)->cy1) || ((y) > (im)->cy2)) || (((x) < (im)->cx1) || ((x) > (im)->cx2)))) #ifdef _OSD_POSIX /* BS2000 uses the EBCDIC char set instead of ASCII */ #define CHARSET_EBCDIC #define __attribute__(any) /*nothing */ #endif /*_OSD_POSIX*/ #ifndef CHARSET_EBCDIC #define ASC(ch) ch #else /*CHARSET_EBCDIC */ #define ASC(ch) gd_toascii[(unsigned char)ch] static const unsigned char gd_toascii[256] = { /*00 */ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, 0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /*................ */ /*10 */ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, 0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /*................ */ /*20 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /*................ */ /*30 */ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /*................ */ /*40 */ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */ /*50 */ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /*&.........!$*);. */ /*60 */ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, 0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /*-/........^,%_>?*/ /*70 */ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, 0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /*..........:#@'=" */ /*80 */ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /*.abcdefghi...... */ /*90 */ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /*.jklmnopqr...... */ /*a0 */ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /*..stuvwxyz...... */ /*b0 */ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, 0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /*...........[\].. */ /*c0 */ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /*.ABCDEFGHI...... */ /*d0 */ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /*.JKLMNOPQR...... */ /*e0 */ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /*..STUVWXYZ...... */ /*f0 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /*0123456789.{.}.~ */ }; #endif /*CHARSET_EBCDIC */ extern const int gdCosT[]; extern const int gdSinT[]; void gd_stderr_error(int priority, const char *format, va_list args) { switch (priority) { case GD_ERROR: fputs("GD Error: ", stderr); break; case GD_WARNING: fputs("GD Warning: ", stderr); break; case GD_NOTICE: fputs("GD Notice: ", stderr); break; case GD_INFO: fputs("GD Info: ", stderr); break; case GD_DEBUG: fputs("GD Debug: ", stderr); break; } vfprintf(stderr, format, args); fflush(stderr); } static gdErrorMethod gd_error_method = gd_stderr_error; void gd_error(const char *format, ...) { va_list args; va_start(args, format); gd_error_ex(GD_WARNING, format, args); va_end(args); } void gd_error_ex(int priority, const char *format, ...) { va_list args; va_start(args, format); if (gd_error_method) { gd_error_method(priority, format, args); } va_end(args); } BGD_DECLARE(void) gdSetErrorMethod(gdErrorMethod error_method) { gd_error_method = error_method; } BGD_DECLARE(void) gdClearErrorMethod(void) { gd_error_method = gd_stderr_error; } static void gdImageBrushApply (gdImagePtr im, int x, int y); static void gdImageTileApply (gdImagePtr im, int x, int y); BGD_DECLARE(int) gdImageGetTrueColorPixel (gdImagePtr im, int x, int y); /* Function: gdImageCreate gdImageCreate is called to create palette-based images, with no more than 256 colors. The image must eventually be destroyed using gdImageDestroy(). Parameters: sx - The image width. sy - The image height. Returns: A pointer to the new image or NULL if an error occurred. Example: > gdImagePtr im; > im = gdImageCreate(64, 64); > // ... Use the image ... > gdImageDestroy(im); See Also: <gdImageCreateTrueColor> */ BGD_DECLARE(gdImagePtr) gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sizeof (unsigned char *), sy)) { return NULL; } if (overflow2(sizeof (unsigned char *), sx)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); if (!im) { return NULL; } /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc (sizeof (unsigned char *) * sy); if (!im->pixels) { gdFree(im); return NULL; } im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; (i < sy); i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc (sx, sizeof (unsigned char)); if (!im->pixels[i]) { for (--i ; i >= 0; i--) { gdFree(im->pixels[i]); } gdFree(im->pixels); gdFree(im); return NULL; } } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; for (i = 0; (i < gdMaxColors); i++) { im->open[i] = 1; }; im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->res_x = GD_RESOLUTION; im->res_y = GD_RESOLUTION; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } /* Function: gdImageCreateTrueColor <gdImageCreateTrueColor> is called to create truecolor images, with an essentially unlimited number of colors. Invoke <gdImageCreateTrueColor> with the x and y dimensions of the desired image. <gdImageCreateTrueColor> returns a <gdImagePtr> to the new image, or NULL if unable to allocate the image. The image must eventually be destroyed using <gdImageDestroy>(). Truecolor images are always filled with black at creation time. There is no concept of a "background" color index. Parameters: sx - The image width. sy - The image height. Returns: A pointer to the new image or NULL if an error occurred. Example: > gdImagePtr im; > im = gdImageCreateTrueColor(64, 64); > // ... Use the image ... > gdImageDestroy(im); See Also: <gdImageCreateTrueColor> */ BGD_DECLARE(gdImagePtr) gdImageCreateTrueColor (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof (int *), sy)) { return 0; } if (overflow2(sizeof(int), sx)) { return NULL; } im = (gdImage *) gdMalloc (sizeof (gdImage)); if (!im) { return 0; } memset (im, 0, sizeof (gdImage)); im->tpixels = (int **) gdMalloc (sizeof (int *) * sy); if (!im->tpixels) { gdFree(im); return 0; } im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; (i < sy); i++) { im->tpixels[i] = (int *) gdCalloc (sx, sizeof (int)); if (!im->tpixels[i]) { /* 2.0.34 */ i--; while (i >= 0) { gdFree(im->tpixels[i]); i--; } gdFree(im->tpixels); gdFree(im); return 0; } } im->sx = sx; im->sy = sy; im->transparent = (-1); im->interlace = 0; im->trueColor = 1; /* 2.0.2: alpha blending is now on by default, and saving of alpha is off by default. This allows font antialiasing to work as expected on the first try in JPEGs -- quite important -- and also allows for smaller PNGs when saving of alpha channel is not really desired, which it usually isn't! */ im->saveAlphaFlag = 0; im->alphaBlendingFlag = 1; im->thick = 1; im->AA = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->res_x = GD_RESOLUTION; im->res_y = GD_RESOLUTION; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } /* Function: gdImageDestroy <gdImageDestroy> is used to free the memory associated with an image. It is important to invoke <gdImageDestroy> before exiting your program or assigning a new image to a <gdImagePtr> variable. Parameters: im - Pointer to the gdImage to delete. Returns: Nothing. Example: > gdImagePtr im; > im = gdImageCreate(10, 10); > // ... Use the image ... > // Now destroy it > gdImageDestroy(im); */ BGD_DECLARE(void) gdImageDestroy (gdImagePtr im) { int i; if (im->pixels) { for (i = 0; (i < im->sy); i++) { gdFree (im->pixels[i]); } gdFree (im->pixels); } if (im->tpixels) { for (i = 0; (i < im->sy); i++) { gdFree (im->tpixels[i]); } gdFree (im->tpixels); } if (im->polyInts) { gdFree (im->polyInts); } if (im->style) { gdFree (im->style); } gdFree (im); } BGD_DECLARE(int) gdImageColorClosest (gdImagePtr im, int r, int g, int b) { return gdImageColorClosestAlpha (im, r, g, b, gdAlphaOpaque); } BGD_DECLARE(int) gdImageColorClosestAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; long rd, gd, bd, ad; int ct = (-1); int first = 1; long mindist = 0; if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (i = 0; (i < (im->colorsTotal)); i++) { long dist; if (im->open[i]) { continue; } rd = (im->red[i] - r); gd = (im->green[i] - g); bd = (im->blue[i] - b); /* gd 2.02: whoops, was - b (thanks to David Marwood) */ /* gd 2.16: was blue rather than alpha! Geez! Thanks to Artur Jakub Jerzak */ ad = (im->alpha[i] - a); dist = rd * rd + gd * gd + bd * bd + ad * ad; if (first || (dist < mindist)) { mindist = dist; ct = i; first = 0; } } return ct; } /* This code is taken from http://www.acm.org/jgt/papers/SmithLyons96/hwb_rgb.html, an article * on colour conversion to/from RBG and HWB colour systems. * It has been modified to return the converted value as a * parameter. */ #define RETURN_HWB(h, w, b) {HWB->H = h; HWB->W = w; HWB->B = b; return HWB;} #define RETURN_RGB(r, g, b) {RGB->R = r; RGB->G = g; RGB->B = b; return RGB;} #define HWB_UNDEFINED -1 #define SETUP_RGB(s, r, g, b) {s.R = r/255.0; s.G = g/255.0; s.B = b/255.0;} #define MIN(a,b) ((a)<(b)?(a):(b)) #define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c))) #define MAX(a,b) ((a)<(b)?(b):(a)) #define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c))) /* * Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure * red always maps to 6 in this implementation. Therefore UNDEFINED can be * defined as 0 in situations where only unsigned numbers are desired. */ typedef struct { float R, G, B; } RGBType; typedef struct { float H, W, B; } HWBType; static HWBType * RGB_to_HWB (RGBType RGB, HWBType * HWB) { /* * RGB are each on [0, 1]. W and B are returned on [0, 1] and H is * returned on [0, 6]. Exception: H is returned UNDEFINED if W == 1 - B. */ float R = RGB.R, G = RGB.G, B = RGB.B, w, v, b, f; int i; w = MIN3 (R, G, B); v = MAX3 (R, G, B); b = 1 - v; if (v == w) RETURN_HWB (HWB_UNDEFINED, w, b); f = (R == w) ? G - B : ((G == w) ? B - R : R - G); i = (R == w) ? 3 : ((G == w) ? 5 : 1); RETURN_HWB (i - f / (v - w), w, b); } static float HWB_Diff (int r1, int g1, int b1, int r2, int g2, int b2) { RGBType RGB1, RGB2; HWBType HWB1, HWB2; float diff; SETUP_RGB (RGB1, r1, g1, b1); SETUP_RGB (RGB2, r2, g2, b2); RGB_to_HWB (RGB1, &HWB1); RGB_to_HWB (RGB2, &HWB2); /* * I made this bit up; it seems to produce OK results, and it is certainly * more visually correct than the current RGB metric. (PJW) */ if ((HWB1.H == HWB_UNDEFINED) || (HWB2.H == HWB_UNDEFINED)) { diff = 0; /* Undefined hues always match... */ } else { diff = fabs (HWB1.H - HWB2.H); if (diff > 3) { diff = 6 - diff; /* Remember, it's a colour circle */ } } diff = diff * diff + (HWB1.W - HWB2.W) * (HWB1.W - HWB2.W) + (HWB1.B - HWB2.B) * (HWB1.B - HWB2.B); return diff; } #if 0 /* * This is not actually used, but is here for completeness, in case someone wants to * use the HWB stuff for anything else... */ static RGBType * HWB_to_RGB (HWBType HWB, RGBType * RGB) { /* * H is given on [0, 6] or UNDEFINED. W and B are given on [0, 1]. * RGB are each returned on [0, 1]. */ float h = HWB.H, w = HWB.W, b = HWB.B, v, n, f; int i; v = 1 - b; if (h == HWB_UNDEFINED) RETURN_RGB (v, v, v); i = floor (h); f = h - i; if (i & 1) f = 1 - f; /* if i is odd */ n = w + f * (v - w); /* linear interpolation between w and v */ switch (i) { case 6: case 0: RETURN_RGB (v, n, w); case 1: RETURN_RGB (n, v, w); case 2: RETURN_RGB (w, v, n); case 3: RETURN_RGB (w, n, v); case 4: RETURN_RGB (n, w, v); case 5: RETURN_RGB (v, w, n); } return RGB; } #endif BGD_DECLARE(int) gdImageColorClosestHWB (gdImagePtr im, int r, int g, int b) { int i; /* long rd, gd, bd; */ int ct = (-1); int first = 1; float mindist = 0; if (im->trueColor) { return gdTrueColor (r, g, b); } for (i = 0; (i < (im->colorsTotal)); i++) { float dist; if (im->open[i]) { continue; } dist = HWB_Diff (im->red[i], im->green[i], im->blue[i], r, g, b); if (first || (dist < mindist)) { mindist = dist; ct = i; first = 0; } } return ct; } BGD_DECLARE(int) gdImageColorExact (gdImagePtr im, int r, int g, int b) { return gdImageColorExactAlpha (im, r, g, b, gdAlphaOpaque); } BGD_DECLARE(int) gdImageColorExactAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (i = 0; (i < (im->colorsTotal)); i++) { if (im->open[i]) { continue; } if ((im->red[i] == r) && (im->green[i] == g) && (im->blue[i] == b) && (im->alpha[i] == a)) { return i; } } return -1; } BGD_DECLARE(int) gdImageColorAllocate (gdImagePtr im, int r, int g, int b) { return gdImageColorAllocateAlpha (im, r, g, b, gdAlphaOpaque); } BGD_DECLARE(int) gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; int ct = (-1); if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (i = 0; (i < (im->colorsTotal)); i++) { if (im->open[i]) { ct = i; break; } } if (ct == (-1)) { ct = im->colorsTotal; if (ct == gdMaxColors) { return -1; } im->colorsTotal++; } im->red[ct] = r; im->green[ct] = g; im->blue[ct] = b; im->alpha[ct] = a; im->open[ct] = 0; return ct; } /* * gdImageColorResolve is an alternative for the code fragment: * * if ((color=gdImageColorExact(im,R,G,B)) < 0) * if ((color=gdImageColorAllocate(im,R,G,B)) < 0) * color=gdImageColorClosest(im,R,G,B); * * in a single function. Its advantage is that it is guaranteed to * return a color index in one search over the color table. */ BGD_DECLARE(int) gdImageColorResolve (gdImagePtr im, int r, int g, int b) { return gdImageColorResolveAlpha (im, r, g, b, gdAlphaOpaque); } BGD_DECLARE(int) gdImageColorResolveAlpha (gdImagePtr im, int r, int g, int b, int a) { int c; int ct = -1; int op = -1; long rd, gd, bd, ad, dist; long mindist = 4 * 255 * 255; /* init to max poss dist */ if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (c = 0; c < im->colorsTotal; c++) { if (im->open[c]) { op = c; /* Save open slot */ continue; /* Color not in use */ } if (c == im->transparent) { /* don't ever resolve to the color that has * been designated as the transparent color */ continue; } rd = (long) (im->red[c] - r); gd = (long) (im->green[c] - g); bd = (long) (im->blue[c] - b); ad = (long) (im->alpha[c] - a); dist = rd * rd + gd * gd + bd * bd + ad * ad; if (dist < mindist) { if (dist == 0) { return c; /* Return exact match color */ } mindist = dist; ct = c; } } /* no exact match. We now know closest, but first try to allocate exact */ if (op == -1) { op = im->colorsTotal; if (op == gdMaxColors) { /* No room for more colors */ return ct; /* Return closest available color */ } im->colorsTotal++; } im->red[op] = r; im->green[op] = g; im->blue[op] = b; im->alpha[op] = a; im->open[op] = 0; return op; /* Return newly allocated color */ } BGD_DECLARE(void) gdImageColorDeallocate (gdImagePtr im, int color) { if (im->trueColor || (color >= gdMaxColors) || (color < 0)) { return; } /* Mark it open. */ im->open[color] = 1; } BGD_DECLARE(void) gdImageColorTransparent (gdImagePtr im, int color) { if (!im->trueColor) { if((color < -1) || (color >= gdMaxColors)) { return; } if (im->transparent != -1) { im->alpha[im->transparent] = gdAlphaOpaque; } if (color != -1) { im->alpha[color] = gdAlphaTransparent; } } im->transparent = color; } BGD_DECLARE(void) gdImagePaletteCopy (gdImagePtr to, gdImagePtr from) { int i; int x, y, p; int xlate[256]; if (to->trueColor) { return; } if (from->trueColor) { return; } for (i = 0; i < 256; i++) { xlate[i] = -1; }; for (y = 0; y < (to->sy); y++) { for (x = 0; x < (to->sx); x++) { /* Optimization: no gdImageGetPixel */ p = to->pixels[y][x]; if (xlate[p] == -1) { /* This ought to use HWB, but we don't have an alpha-aware version of that yet. */ xlate[p] = gdImageColorClosestAlpha (from, to->red[p], to->green[p], to->blue[p], to->alpha[p]); /*printf("Mapping %d (%d, %d, %d, %d) to %d (%d, %d, %d, %d)\n", */ /* p, to->red[p], to->green[p], to->blue[p], to->alpha[p], */ /* xlate[p], from->red[xlate[p]], from->green[xlate[p]], from->blue[xlate[p]], from->alpha[xlate[p]]); */ }; /* Optimization: no gdImageSetPixel */ to->pixels[y][x] = xlate[p]; }; }; for (i = 0; (i < (from->colorsTotal)); i++) { /*printf("Copying color %d (%d, %d, %d, %d)\n", i, from->red[i], from->blue[i], from->green[i], from->alpha[i]); */ to->red[i] = from->red[i]; to->blue[i] = from->blue[i]; to->green[i] = from->green[i]; to->alpha[i] = from->alpha[i]; to->open[i] = 0; }; for (i = from->colorsTotal; (i < to->colorsTotal); i++) { to->open[i] = 1; }; to->colorsTotal = from->colorsTotal; } BGD_DECLARE(int) gdImageColorReplace (gdImagePtr im, int src, int dst) { register int x, y; int n = 0; if (src == dst) { return 0; } #define REPLACING_LOOP(pixel) do { \ for (y = im->cy1; y <= im->cy2; y++) { \ for (x = im->cx1; x <= im->cx2; x++) { \ if (pixel(im, x, y) == src) { \ gdImageSetPixel(im, x, y, dst); \ n++; \ } \ } \ } \ } while (0) if (im->trueColor) { REPLACING_LOOP(gdImageTrueColorPixel); } else { REPLACING_LOOP(gdImagePalettePixel); } #undef REPLACING_LOOP return n; } BGD_DECLARE(int) gdImageColorReplaceThreshold (gdImagePtr im, int src, int dst, float threshold) { register int x, y; int n = 0; if (src == dst) { return 0; } #define REPLACING_LOOP(pixel) do { \ for (y = im->cy1; y <= im->cy2; y++) { \ for (x = im->cx1; x <= im->cx2; x++) { \ if (gdColorMatch(im, src, pixel(im, x, y), threshold)) { \ gdImageSetPixel(im, x, y, dst); \ n++; \ } \ } \ } \ } while (0) if (im->trueColor) { REPLACING_LOOP(gdImageTrueColorPixel); } else { REPLACING_LOOP(gdImagePalettePixel); } #undef REPLACING_LOOP return n; } static int colorCmp (const void *x, const void *y) { int a = *(int const *)x; int b = *(int const *)y; return (a > b) - (a < b); } BGD_DECLARE(int) gdImageColorReplaceArray (gdImagePtr im, int len, int *src, int *dst) { register int x, y; int c, *d, *base; int i, n = 0; if (len <= 0 || src == dst) { return 0; } if (len == 1) { return gdImageColorReplace(im, src[0], dst[0]); } if (overflow2(len, sizeof(int)<<1)) { return -1; } base = (int *)gdMalloc(len * (sizeof(int)<<1)); if (!base) { return -1; } for (i = 0; i < len; i++) { base[(i<<1)] = src[i]; base[(i<<1)+1] = dst[i]; } qsort(base, len, sizeof(int)<<1, colorCmp); #define REPLACING_LOOP(pixel) do { \ for (y = im->cy1; y <= im->cy2; y++) { \ for (x = im->cx1; x <= im->cx2; x++) { \ c = pixel(im, x, y); \ if ( (d = (int *)bsearch(&c, base, len, sizeof(int)<<1, colorCmp)) ) { \ gdImageSetPixel(im, x, y, d[1]); \ n++; \ } \ } \ } \ } while (0) if (im->trueColor) { REPLACING_LOOP(gdImageTrueColorPixel); } else { REPLACING_LOOP(gdImagePalettePixel); } #undef REPLACING_LOOP gdFree(base); return n; } BGD_DECLARE(int) gdImageColorReplaceCallback (gdImagePtr im, gdCallbackImageColor callback) { int c, d, n = 0; if (!callback) { return 0; } if (im->trueColor) { register int x, y; for (y = im->cy1; y <= im->cy2; y++) { for (x = im->cx1; x <= im->cx2; x++) { c = gdImageTrueColorPixel(im, x, y); if ( (d = callback(im, c)) != c) { gdImageSetPixel(im, x, y, d); n++; } } } } else { /* palette */ int *sarr, *darr; int k, len = 0; sarr = (int *)gdCalloc(im->colorsTotal, sizeof(int)); if (!sarr) { return -1; } for (c = 0; c < im->colorsTotal; c++) { if (!im->open[c]) { sarr[len++] = c; } } darr = (int *)gdCalloc(len, sizeof(int)); if (!darr) { gdFree(sarr); return -1; } for (k = 0; k < len; k++) { darr[k] = callback(im, sarr[k]); } n = gdImageColorReplaceArray(im, k, sarr, darr); gdFree(darr); gdFree(sarr); } return n; } /* 2.0.10: before the drawing routines, some code to clip points that are * outside the drawing window. Nick Atty (nick@canalplan.org.uk) * * This is the Sutherland Hodgman Algorithm, as implemented by * Duvanenko, Robbins and Gyurcsik - SH(DRG) for short. See Dr Dobb's * Journal, January 1996, pp107-110 and 116-117 * * Given the end points of a line, and a bounding rectangle (which we * know to be from (0,0) to (SX,SY)), adjust the endpoints to be on * the edges of the rectangle if the line should be drawn at all, * otherwise return a failure code */ /* this does "one-dimensional" clipping: note that the second time it is called, all the x parameters refer to height and the y to width - the comments ignore this (if you can understand it when it's looking at the X parameters, it should become clear what happens on the second call!) The code is simplified from that in the article, as we know that gd images always start at (0,0) */ /* 2.0.26, TBB: we now have to respect a clipping rectangle, it won't necessarily start at 0. */ static int clip_1d (int *x0, int *y0, int *x1, int *y1, int mindim, int maxdim) { double m; /* gradient of line */ if (*x0 < mindim) { /* start of line is left of window */ if (*x1 < mindim) /* as is the end, so the line never cuts the window */ return 0; m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ /* adjust x0 to be on the left boundary (ie to be zero), and y0 to match */ *y0 -= (int)(m * (*x0 - mindim)); *x0 = mindim; /* now, perhaps, adjust the far end of the line as well */ if (*x1 > maxdim) { *y1 += m * (maxdim - *x1); *x1 = maxdim; } return 1; } if (*x0 > maxdim) { /* start of line is right of window - complement of above */ if (*x1 > maxdim) /* as is the end, so the line misses the window */ return 0; m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ *y0 += (int)(m * (maxdim - *x0)); /* adjust so point is on the right boundary */ *x0 = maxdim; /* now, perhaps, adjust the end of the line */ if (*x1 < mindim) { *y1 -= (int)(m * (*x1 - mindim)); *x1 = mindim; } return 1; } /* the final case - the start of the line is inside the window */ if (*x1 > maxdim) { /* other end is outside to the right */ m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ *y1 += (int)(m * (maxdim - *x1)); *x1 = maxdim; return 1; } if (*x1 < mindim) { /* other end is outside to the left */ m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ *y1 -= (int)(m * (*x1 - mindim)); *x1 = mindim; return 1; } /* only get here if both points are inside the window */ return 1; } /* end of line clipping code */ BGD_DECLARE(void) gdImageSetPixel (gdImagePtr im, int x, int y, int color) { int p; switch (color) { case gdStyled: if (!im->style) { /* Refuse to draw if no style is set. */ return; } else { p = im->style[im->stylePos++]; } if (p != (gdTransparent)) { gdImageSetPixel (im, x, y, p); } im->stylePos = im->stylePos % im->styleLength; break; case gdStyledBrushed: if (!im->style) { /* Refuse to draw if no style is set. */ return; } p = im->style[im->stylePos++]; if ((p != gdTransparent) && (p != 0)) { gdImageSetPixel (im, x, y, gdBrushed); } im->stylePos = im->stylePos % im->styleLength; break; case gdBrushed: gdImageBrushApply (im, x, y); break; case gdTiled: gdImageTileApply (im, x, y); break; case gdAntiAliased: /* This shouldn't happen (2.0.26) because we just call gdImageAALine now, but do something sane. */ gdImageSetPixel(im, x, y, im->AA_color); break; default: if (gdImageBoundsSafeMacro (im, x, y)) { if (im->trueColor) { switch (im->alphaBlendingFlag) { default: case gdEffectReplace: im->tpixels[y][x] = color; break; case gdEffectAlphaBlend: case gdEffectNormal: im->tpixels[y][x] = gdAlphaBlend(im->tpixels[y][x], color); break; case gdEffectOverlay : im->tpixels[y][x] = gdLayerOverlay(im->tpixels[y][x], color); break; case gdEffectMultiply : im->tpixels[y][x] = gdLayerMultiply(im->tpixels[y][x], color); break; } } else { im->pixels[y][x] = color; } } break; } } static void gdImageBrushApply (gdImagePtr im, int x, int y) { int lx, ly; int hy; int hx; int x1, y1, x2, y2; int srcx, srcy; if (!im->brush) { return; } hy = gdImageSY (im->brush) / 2; y1 = y - hy; y2 = y1 + gdImageSY (im->brush); hx = gdImageSX (im->brush) / 2; x1 = x - hx; x2 = x1 + gdImageSX (im->brush); srcy = 0; if (im->trueColor) { if (im->brush->trueColor) { for (ly = y1; (ly < y2); ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p; p = gdImageGetTrueColorPixel (im->brush, srcx, srcy); /* 2.0.9, Thomas Winzig: apply simple full transparency */ if (p != gdImageGetTransparent (im->brush)) { gdImageSetPixel (im, lx, ly, p); } srcx++; } srcy++; } } else { /* 2.0.12: Brush palette, image truecolor (thanks to Thorben Kundinger for pointing out the issue) */ for (ly = y1; (ly < y2); ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p, tc; p = gdImageGetPixel (im->brush, srcx, srcy); tc = gdImageGetTrueColorPixel (im->brush, srcx, srcy); /* 2.0.9, Thomas Winzig: apply simple full transparency */ if (p != gdImageGetTransparent (im->brush)) { gdImageSetPixel (im, lx, ly, tc); } srcx++; } srcy++; } } } else { for (ly = y1; (ly < y2); ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p; p = gdImageGetPixel (im->brush, srcx, srcy); /* Allow for non-square brushes! */ if (p != gdImageGetTransparent (im->brush)) { /* Truecolor brush. Very slow on a palette destination. */ if (im->brush->trueColor) { gdImageSetPixel (im, lx, ly, gdImageColorResolveAlpha (im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p))); } else { gdImageSetPixel (im, lx, ly, im->brushColorMap[p]); } } srcx++; } srcy++; } } } static void gdImageTileApply (gdImagePtr im, int x, int y) { gdImagePtr tile = im->tile; int srcx, srcy; int p; if (!tile) { return; } srcx = x % gdImageSX (tile); srcy = y % gdImageSY (tile); if (im->trueColor) { p = gdImageGetPixel (tile, srcx, srcy); if (p != gdImageGetTransparent (tile)) { if (!tile->trueColor) { p = gdTrueColorAlpha(tile->red[p], tile->green[p], tile->blue[p], tile->alpha[p]); } gdImageSetPixel (im, x, y, p); } } else { p = gdImageGetPixel (tile, srcx, srcy); /* Allow for transparency */ if (p != gdImageGetTransparent (tile)) { if (tile->trueColor) { /* Truecolor tile. Very slow on a palette destination. */ gdImageSetPixel (im, x, y, gdImageColorResolveAlpha (im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p))); } else { gdImageSetPixel (im, x, y, im->tileColorMap[p]); } } } } BGD_DECLARE(int) gdImageGetPixel (gdImagePtr im, int x, int y) { if (gdImageBoundsSafeMacro (im, x, y)) { if (im->trueColor) { return im->tpixels[y][x]; } else { return im->pixels[y][x]; } } else { return 0; } } BGD_DECLARE(int) gdImageGetTrueColorPixel (gdImagePtr im, int x, int y) { int p = gdImageGetPixel (im, x, y); if (!im->trueColor) { return gdTrueColorAlpha (im->red[p], im->green[p], im->blue[p], (im->transparent == p) ? gdAlphaTransparent : im->alpha[p]); } else { return p; } } BGD_DECLARE(void) gdImageAABlend (gdImagePtr im) { /* NO-OP, kept for library compatibility. */ (void)im; } static void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col); static void gdImageHLine(gdImagePtr im, int y, int x1, int x2, int col) { if (im->thick > 1) { int thickhalf = im->thick >> 1; gdImageFilledRectangle(im, x1, y - thickhalf, x2, y + im->thick - thickhalf - 1, col); } else { if (x2 < x1) { int t = x2; x2 = x1; x1 = t; } for (; x1 <= x2; x1++) { gdImageSetPixel(im, x1, y, col); } } return; } static void gdImageVLine(gdImagePtr im, int x, int y1, int y2, int col) { if (im->thick > 1) { int thickhalf = im->thick >> 1; gdImageFilledRectangle(im, x - thickhalf, y1, x + im->thick - thickhalf - 1, y2, col); } else { if (y2 < y1) { int t = y1; y1 = y2; y2 = t; } for (; y1 <= y2; y1++) { gdImageSetPixel(im, x, y1, col); } } return; } /* Bresenham as presented in Foley & Van Dam */ BGD_DECLARE(void) gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int wid; int w, wstart; int thick; if (color == gdAntiAliased) { /* gdAntiAliased passed as color: use the much faster, much cheaper and equally attractive gdImageAALine implementation. That clips too, so don't clip twice. */ gdImageAALine(im, x1, y1, x2, y2, im->AA_color); return; } /* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn. 2.0.26, TBB: clip to edges of clipping rectangle. We were getting away with this because gdImageSetPixel is used for actual drawing, but this is still more efficient and opens the way to skip per-pixel bounds checking in the future. */ if (clip_1d (&x1, &y1, &x2, &y2, im->cx1, im->cx2) == 0) return; if (clip_1d (&y1, &x1, &y2, &x2, im->cy1, im->cy2) == 0) return; thick = im->thick; dx = abs (x2 - x1); dy = abs (y2 - y1); if (dx == 0) { gdImageVLine(im, x1, y1, y2, color); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, color); return; } if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* Doug Claar: watch out for NaN in atan2 (2.0.5) */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double ac = cos (atan2 (dy, dx)); if (ac != 0) { wid = thick / ac; } else { wid = 1; } if (wid == 0) { wid = 1; } d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } /* Set up line thickness */ wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); } } } else { /* More-or-less vertical. use wid for horizontal stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } if (wid == 0) wid = 1; d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } /* Set up line thickness */ wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); } } } } static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert); BGD_DECLARE(void) gdImageDashedLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int dashStep = 0; int on = 1; int wid; int vert; int thick = im->thick; dx = abs (x2 - x1); dy = abs (y2 - y1); if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } vert = 1; d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } vert = 0; d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } } } static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert) { int dashStep = *dashStepP; int on = *onP; int w, wstart; dashStep++; if (dashStep == gdDashSize) { dashStep = 0; on = !on; } if (on) { if (vert) { wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); } else { wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); } } *dashStepP = dashStep; *onP = on; } BGD_DECLARE(int) gdImageBoundsSafe (gdImagePtr im, int x, int y) { return gdImageBoundsSafeMacro (im, x, y); } BGD_DECLARE(void) gdImageChar (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy; int px, py; int fline; cx = 0; cy = 0; #ifdef CHARSET_EBCDIC c = ASC (c); #endif /*CHARSET_EBCDIC */ if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py < (y + f->h)); py++) { for (px = x; (px < (x + f->w)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel (im, px, py, color); } cx++; } cx = 0; cy++; } } BGD_DECLARE(void) gdImageCharUp (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy; int px, py; int fline; cx = 0; cy = 0; #ifdef CHARSET_EBCDIC c = ASC (c); #endif /*CHARSET_EBCDIC */ if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel (im, px, py, color); } cy++; } cy = 0; cx++; } } BGD_DECLARE(void) gdImageString (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color) { int i; int l; l = strlen ((char *) s); for (i = 0; (i < l); i++) { gdImageChar (im, f, x, y, s[i], color); x += f->w; } } BGD_DECLARE(void) gdImageStringUp (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color) { int i; int l; l = strlen ((char *) s); for (i = 0; (i < l); i++) { gdImageCharUp (im, f, x, y, s[i], color); y -= f->w; } } static int strlen16 (unsigned short *s); BGD_DECLARE(void) gdImageString16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color) { int i; int l; l = strlen16 (s); for (i = 0; (i < l); i++) { gdImageChar (im, f, x, y, s[i], color); x += f->w; } } BGD_DECLARE(void) gdImageStringUp16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color) { int i; int l; l = strlen16 (s); for (i = 0; (i < l); i++) { gdImageCharUp (im, f, x, y, s[i], color); y -= f->w; } } static int strlen16 (unsigned short *s) { int len = 0; while (*s) { s++; len++; } return len; } #ifndef HAVE_LSQRT /* If you don't have a nice square root function for longs, you can use ** this hack */ long lsqrt (long n) { long result = (long) sqrt ((double) n); return result; } #endif /* s and e are integers modulo 360 (degrees), with 0 degrees being the rightmost extreme and degrees changing clockwise. cx and cy are the center in pixels; w and h are the horizontal and vertical diameter in pixels. Nice interface, but slow. See gd_arc_f_buggy.c for a better version that doesn't seem to be bug-free yet. */ BGD_DECLARE(void) gdImageArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color) { gdImageFilledArc (im, cx, cy, w, h, s, e, color, gdNoFill); } BGD_DECLARE(void) gdImageFilledArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color, int style) { gdPoint pts[3]; int i; int lx = 0, ly = 0; int fx = 0, fy = 0; if ((s % 360) == (e % 360)) { s = 0; e = 360; } else { if (s > 360) { s = s % 360; } if (e > 360) { e = e % 360; } while (s < 0) { s += 360; } while (e < s) { e += 360; } if (s == e) { s = 0; e = 360; } } for (i = s; (i <= e); i++) { int x, y; x = ((long) gdCosT[i % 360] * (long) w / (2 * 1024)) + cx; y = ((long) gdSinT[i % 360] * (long) h / (2 * 1024)) + cy; if (i != s) { if (!(style & gdChord)) { if (style & gdNoFill) { gdImageLine (im, lx, ly, x, y, color); } else { /* This is expensive! */ pts[0].x = lx; pts[0].y = ly; pts[1].x = x; pts[1].y = y; pts[2].x = cx; pts[2].y = cy; gdImageFilledPolygon (im, pts, 3, color); } } } else { fx = x; fy = y; } lx = x; ly = y; } if (style & gdChord) { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine (im, cx, cy, lx, ly, color); gdImageLine (im, cx, cy, fx, fy, color); } gdImageLine (im, fx, fy, lx, ly, color); } else { pts[0].x = fx; pts[0].y = fy; pts[1].x = lx; pts[1].y = ly; pts[2].x = cx; pts[2].y = cy; gdImageFilledPolygon (im, pts, 3, color); } } else { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine (im, cx, cy, lx, ly, color); gdImageLine (im, cx, cy, fx, fy, color); } } } } BGD_DECLARE(void) gdImageEllipse(gdImagePtr im, int mx, int my, int w, int h, int c) { int x=0,mx1=0,mx2=0,my1=0,my2=0; long aq,bq,dx,dy,r,rx,ry,a,b; a=w>>1; b=h>>1; gdImageSetPixel(im,mx+a, my, c); gdImageSetPixel(im,mx-a, my, c); mx1 = mx-a; my1 = my; mx2 = mx+a; my2 = my; aq = a * a; bq = b * b; dx = aq << 1; dy = bq << 1; r = a * bq; rx = r << 1; ry = 0; x = a; while (x > 0) { if (r > 0) { my1++; my2--; ry +=dx; r -=ry; } if (r <= 0) { x--; mx1++; mx2--; rx -=dy; r +=rx; } gdImageSetPixel(im,mx1, my1, c); gdImageSetPixel(im,mx1, my2, c); gdImageSetPixel(im,mx2, my1, c); gdImageSetPixel(im,mx2, my2, c); } } BGD_DECLARE(void) gdImageFilledEllipse (gdImagePtr im, int mx, int my, int w, int h, int c) { int x=0,mx1=0,mx2=0,my1=0,my2=0; long aq,bq,dx,dy,r,rx,ry,a,b; int i; int old_y2; a=w>>1; b=h>>1; for (x = mx-a; x <= mx+a; x++) { gdImageSetPixel(im, x, my, c); } mx1 = mx-a; my1 = my; mx2 = mx+a; my2 = my; aq = a * a; bq = b * b; dx = aq << 1; dy = bq << 1; r = a * bq; rx = r << 1; ry = 0; x = a; old_y2=-2; while (x > 0) { if (r > 0) { my1++; my2--; ry +=dx; r -=ry; } if (r <= 0) { x--; mx1++; mx2--; rx -=dy; r +=rx; } if(old_y2!=my2) { for(i=mx1; i<=mx2; i++) { gdImageSetPixel(im,i,my1,c); } } if(old_y2!=my2) { for(i=mx1; i<=mx2; i++) { gdImageSetPixel(im,i,my2,c); } } old_y2 = my2; } } BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit, rightLimit; int i; int restoreAlphaBleding; if (border < 0 || color < 0) { /* Refuse to fill to a non-solid border */ return; } if (!im->trueColor) { if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1))) { return; } } leftLimit = (-1); restoreAlphaBleding = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; (i >= 0); i--) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); leftLimit = i; } if (leftLimit == (-1)) { im->alphaBlendingFlag = restoreAlphaBleding; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); (i < im->sx); i++) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c = gdImageGetPixel (im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBleding; } /* * set the pixel at (x,y) and its 4-connected neighbors * with the same pixel value to the new pixel value nc (new color). * A 4-connected neighbor: pixel above, below, left, or right of a pixel. * ideas from comp.graphics discussions. * For tiled fill, the use of a flag buffer is mandatory. As the tile image can * contain the same color as the color to fill. To do not bloat normal filling * code I added a 2nd private function. */ static int gdImageTileGet (gdImagePtr im, int x, int y) { int srcx, srcy; int tileColor,p; if (!im->tile) { return -1; } srcx = x % gdImageSX(im->tile); srcy = y % gdImageSY(im->tile); p = gdImageGetPixel(im->tile, srcx, srcy); if (p == im->tile->transparent) { tileColor = im->transparent; } else if (im->trueColor) { if (im->tile->trueColor) { tileColor = p; } else { tileColor = gdTrueColorAlpha( gdImageRed(im->tile,p), gdImageGreen(im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p)); } } else { if (im->tile->trueColor) { tileColor = gdImageColorResolveAlpha(im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p)); } else { tileColor = gdImageColorResolveAlpha(im, gdImageRed (im->tile,p), gdImageGreen (im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p)); } } return tileColor; } /* horizontal segment of scan line y */ struct seg { int y, xl, xr, dy; }; /* max depth of stack */ #define FILL_MAX ((int)(im->sy*im->sx)/4) #define FILL_PUSH(Y, XL, XR, DY) \ if (sp<stack+FILL_MAX && Y+(DY)>=0 && Y+(DY)<wy2) \ {sp->y = Y; sp->xl = XL; sp->xr = XR; sp->dy = DY; sp++;} #define FILL_POP(Y, XL, XR, DY) \ {sp--; Y = sp->y+(DY = sp->dy); XL = sp->xl; XR = sp->xr;} static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc); BGD_DECLARE(void) gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack; */ struct seg *stack; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal - 1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled) { _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx; wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } if(overflow2(im->sy, im->sx)) { return; } if(overflow2(sizeof(struct seg), ((im->sy * im->sx) / 4))) { return; } stack = (struct seg *)gdMalloc(sizeof(struct seg) * ((int)(im->sy*im->sx)/4)); if (!stack) { return; } sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } gdFree(stack); done: im->alphaBlendingFlag = alphablending_bak; } static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; /* stack of filled segments */ struct seg *stack; struct seg *sp; char *pts; if (!im->tile) { return; } wx2=im->sx; wy2=im->sy; if(overflow2(im->sy, im->sx)) { return; } if(overflow2(sizeof(struct seg), ((im->sy * im->sx) / 4))) { return; } pts = (char *) gdCalloc(im->sy * im->sx, sizeof(char)); if (!pts) { return; } stack = (struct seg *)gdMalloc(sizeof(struct seg) * ((int)(im->sy*im->sx)/4)); if (!stack) { gdFree(pts); return; } sp = stack; oc = gdImageGetPixel(im, x, y); /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && (!pts[y + x*wy2] && gdImageGetPixel(im,x,y)==oc); x--) { nc = gdImageTileGet(im,x,y); pts[y + x*wy2]=1; gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<wx2 && (!pts[y + x*wy2] && gdImageGetPixel(im,x, y)==oc) ; x++) { if (pts[y + x*wy2]) { /* we should never be here */ break; } nc = gdImageTileGet(im,x,y); pts[y + x*wy2]=1; gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (pts[y + x*wy2] || gdImageGetPixel(im,x, y)!=oc); x++); l = x; } while (x<=x2); } gdFree(pts); gdFree(stack); } BGD_DECLARE(void) gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int thick = im->thick; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { int t; t = y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { gdImageLine(im, x1, y1, x2, y1, color); gdImageLine(im, x1, y2, x2, y2, color); gdImageLine(im, x1, y1 + 1, x1, y2 - 1, color); gdImageLine(im, x2, y1 + 1, x2, y2 - 1, color); } } BGD_DECLARE(void) gdImageFilledRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x, y; if (x1 == x2 && y1 == y2) { gdImageSetPixel(im, x1, y1, color); return; } if (x1 > x2) { x = x1; x1 = x2; x2 = x; } if (y1 > y2) { y = y1; y1 = y2; y2 = y; } if (x1 < 0) { x1 = 0; } if (x2 >= gdImageSX(im)) { x2 = gdImageSX(im) - 1; } if (y1 < 0) { y1 = 0; } if (y2 >= gdImageSY(im)) { y2 = gdImageSY(im) - 1; } for (y = y1; (y <= y2); y++) { for (x = x1; (x <= x2); x++) { gdImageSetPixel (im, x, y, color); } } } BGD_DECLARE(gdImagePtr) gdImageClone (gdImagePtr src) { gdImagePtr dst; register int i, x; if (src->trueColor) { dst = gdImageCreateTrueColor(src->sx , src->sy); } else { dst = gdImageCreate(src->sx , src->sy); } if (dst == NULL) { return NULL; } if (src->trueColor == 0) { dst->colorsTotal = src->colorsTotal; for (i = 0; i < gdMaxColors; i++) { dst->red[i] = src->red[i]; dst->green[i] = src->green[i]; dst->blue[i] = src->blue[i]; dst->alpha[i] = src->alpha[i]; dst->open[i] = src->open[i]; } for (i = 0; i < src->sy; i++) { for (x = 0; x < src->sx; x++) { dst->pixels[i][x] = src->pixels[i][x]; } } } else { for (i = 0; i < src->sy; i++) { for (x = 0; x < src->sx; x++) { dst->tpixels[i][x] = src->tpixels[i][x]; } } } if (src->styleLength > 0) { dst->styleLength = src->styleLength; dst->stylePos = src->stylePos; for (i = 0; i < src->styleLength; i++) { dst->style[i] = src->style[i]; } } dst->interlace = src->interlace; dst->alphaBlendingFlag = src->alphaBlendingFlag; dst->saveAlphaFlag = src->saveAlphaFlag; dst->AA = src->AA; dst->AA_color = src->AA_color; dst->AA_dont_blend = src->AA_dont_blend; dst->cx1 = src->cx1; dst->cy1 = src->cy1; dst->cx2 = src->cx2; dst->cy2 = src->cy2; dst->res_x = src->res_x; dst->res_y = src->res_x; dst->paletteQuantizationMethod = src->paletteQuantizationMethod; dst->paletteQuantizationSpeed = src->paletteQuantizationSpeed; dst->paletteQuantizationMinQuality = src->paletteQuantizationMinQuality; dst->paletteQuantizationMinQuality = src->paletteQuantizationMinQuality; dst->interpolation_id = src->interpolation_id; dst->interpolation = src->interpolation; if (src->brush) { dst->brush = gdImageClone(src->brush); } if (src->tile) { dst->tile = gdImageClone(src->tile); } if (src->style) { gdImageSetStyle(dst, src->style, src->styleLength); } for (i = 0; i < gdMaxColors; i++) { dst->brushColorMap[i] = src->brushColorMap[i]; dst->tileColorMap[i] = src->tileColorMap[i]; } if (src->polyAllocated > 0) { dst->polyAllocated = src->polyAllocated; for (i = 0; i < src->polyAllocated; i++) { dst->polyInts[i] = src->polyInts[i]; } } return dst; } BGD_DECLARE(void) gdImageCopy (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h) { int c; int x, y; int tox, toy; int i; int colorMap[gdMaxColors]; if (dst->trueColor) { /* 2.0: much easier when the destination is truecolor. */ /* 2.0.10: needs a transparent-index check that is still valid if * * the source is not truecolor. Thanks to Frank Warmerdam. */ if (src->trueColor) { for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetTrueColorPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel (dst, dstX + x, dstY + y, c); } } } } else { /* source is palette based */ for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel(dst, dstX + x, dstY + y, gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c])); } } } } return; } for (i = 0; (i < gdMaxColors); i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; int mapTo; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* Have we established a mapping for this color? */ if (src->trueColor) { /* 2.05: remap to the palette available in the destination image. This is slow and works badly, but it beats crashing! Thanks to Padhrig McCarthy. */ mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c)); } else if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Get best match possible. This function never returns error. */ nc = gdImageColorResolveAlpha (dst, src->red[c], src->green[c], src->blue[c], src->alpha[c]); } colorMap[c] = nc; mapTo = colorMap[c]; } else { mapTo = colorMap[c]; } gdImageSetPixel (dst, tox, toy, mapTo); tox++; } toy++; } } /* This function is a substitute for real alpha channel operations, so it doesn't pay attention to the alpha channel. */ BGD_DECLARE(void) gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel (dst, tox, toy); ncR = gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0); ncG = gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0); ncB = gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } /* This function is a substitute for real alpha channel operations, so it doesn't pay attention to the alpha channel. */ BGD_DECLARE(void) gdImageCopyMergeGray (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; float g; toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* * If it's the same image, mapping is NOT trivial since we * merge with greyscale target, but if pct is 100, the grey * value is not used, so it becomes trivial. pjw 2.0.12. */ if (dst == src && pct == 100) { nc = c; } else { dc = gdImageGetPixel (dst, tox, toy); g = 0.29900 * gdImageRed(dst, dc) + 0.58700 * gdImageGreen(dst, dc) + 0.11400 * gdImageBlue(dst, dc); ncR = gdImageRed (src, c) * (pct / 100.0) + g * ((100 - pct) / 100.0); ncG = gdImageGreen (src, c) * (pct / 100.0) + g * ((100 - pct) / 100.0); ncB = gdImageBlue (src, c) * (pct / 100.0) + g * ((100 - pct) / 100.0); /* First look for an exact match */ nc = gdImageColorExact (dst, ncR, ncG, ncB); if (nc == (-1)) { /* No, so try to allocate it */ nc = gdImageColorAllocate (dst, ncR, ncG, ncB); /* If we're out of colors, go for the closest color */ if (nc == (-1)) { nc = gdImageColorClosest (dst, ncR, ncG, ncB); } } } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } BGD_DECLARE(void) gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int c; int x, y; int tox, toy; int ydest; int i; int colorMap[gdMaxColors]; /* Stretch vectors */ int *stx; int *sty; /* We only need to use floating point to determine the correct stretch vector for one line's worth. */ if (overflow2(sizeof (int), srcW)) { return; } if (overflow2(sizeof (int), srcH)) { return; } stx = (int *) gdMalloc (sizeof (int) * srcW); if (!stx) { return; } sty = (int *) gdMalloc (sizeof (int) * srcH); if (!sty) { gdFree(stx); return; } /* Fixed by Mao Morimoto 2.0.16 */ for (i = 0; (i < srcW); i++) { stx[i] = dstW * (i + 1) / srcW - dstW * i / srcW; } for (i = 0; (i < srcH); i++) { sty[i] = dstH * (i + 1) / srcH - dstH * i / srcH; } for (i = 0; (i < gdMaxColors); i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; (y < (srcY + srcH)); y++) { for (ydest = 0; (ydest < sty[y - srcY]); ydest++) { tox = dstX; for (x = srcX; (x < (srcX + srcW)); x++) { int nc = 0; int mapTo; if (!stx[x - srcX]) { continue; } if (dst->trueColor) { /* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */ if (!src->trueColor) { int tmp = gdImageGetPixel (src, x, y); mapTo = gdImageGetTrueColorPixel (src, x, y); if (gdImageGetTransparent (src) == tmp) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } else { /* TK: old code follows */ mapTo = gdImageGetTrueColorPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == mapTo) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } } else { c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox += stx[x - srcX]; continue; } if (src->trueColor) { /* Remap to the palette available in the destination image. This is slow and works badly. */ mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c)); } else { /* Have we established a mapping for this color? */ if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Find or create the best match */ /* 2.0.5: can't use gdTrueColorGetRed, etc with palette */ nc = gdImageColorResolveAlpha (dst, gdImageRed (src, c), gdImageGreen (src, c), gdImageBlue (src, c), gdImageAlpha (src, c)); } colorMap[c] = nc; } mapTo = colorMap[c]; } } for (i = 0; (i < stx[x - srcX]); i++) { gdImageSetPixel (dst, tox, toy, mapTo); tox++; } } toy++; } } gdFree (stx); gdFree (sty); } /* gd 2.0.8: gdImageCopyRotated is added. Source is a rectangle, with its upper left corner at srcX and srcY. Destination is the *center* of the rotated copy. Angle is in degrees, same as gdImageArc. Floating point destination center coordinates allow accurate rotation of objects of odd-numbered width or height. */ BGD_DECLARE(void) gdImageCopyRotated (gdImagePtr dst, gdImagePtr src, double dstX, double dstY, int srcX, int srcY, int srcWidth, int srcHeight, int angle) { double dx, dy; double radius = sqrt (srcWidth * srcWidth + srcHeight * srcHeight); double aCos = cos (angle * .0174532925); double aSin = sin (angle * .0174532925); double scX = srcX + ((double) srcWidth) / 2; double scY = srcY + ((double) srcHeight) / 2; int cmap[gdMaxColors]; int i; /* 2.0.34: transparency preservation. The transparentness of the transparent color is more important than its hue. */ if (src->transparent != -1) { if (dst->transparent == -1) { dst->transparent = src->transparent; } } for (i = 0; (i < gdMaxColors); i++) { cmap[i] = (-1); } for (dy = dstY - radius; (dy <= dstY + radius); dy++) { for (dx = dstX - radius; (dx <= dstX + radius); dx++) { double sxd = (dx - dstX) * aCos - (dy - dstY) * aSin; double syd = (dy - dstY) * aCos + (dx - dstX) * aSin; int sx = sxd + scX; int sy = syd + scY; if ((sx >= srcX) && (sx < srcX + srcWidth) && (sy >= srcY) && (sy < srcY + srcHeight)) { int c = gdImageGetPixel (src, sx, sy); /* 2.0.34: transparency wins */ if (c == src->transparent) { gdImageSetPixel (dst, dx, dy, dst->transparent); } else if (!src->trueColor) { /* Use a table to avoid an expensive lookup on every single pixel */ if (cmap[c] == -1) { cmap[c] = gdImageColorResolveAlpha (dst, gdImageRed (src, c), gdImageGreen (src, c), gdImageBlue (src, c), gdImageAlpha (src, c)); } gdImageSetPixel (dst, dx, dy, cmap[c]); } else { gdImageSetPixel (dst, dx, dy, gdImageColorResolveAlpha (dst, gdImageRed (src, c), gdImageGreen (src, c), gdImageBlue (src, c), gdImageAlpha (src, c))); } } } } } /* When gd 1.x was first created, floating point was to be avoided. These days it is often faster than table lookups or integer arithmetic. The routine below is shamelessly, gloriously floating point. TBB */ /* 2.0.10: cast instead of floor() yields 35% performance improvement. Thanks to John Buckman. */ #define floor2(exp) ((long) exp) /*#define floor2(exp) floor(exp)*/ BGD_DECLARE(void) gdImageCopyResampled (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int x, y; double sy1, sy2, sx1, sx2; if (!dst->trueColor) { gdImageCopyResized (dst, src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); return; } for (y = dstY; (y < dstY + dstH); y++) { sy1 = ((double) y - (double) dstY) * (double) srcH / (double) dstH; sy2 = ((double) (y + 1) - (double) dstY) * (double) srcH / (double) dstH; for (x = dstX; (x < dstX + dstW); x++) { double sx, sy; double spixels = 0; double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; double alpha_sum = 0.0, contrib_sum = 0.0; sx1 = ((double) x - (double) dstX) * (double) srcW / dstW; sx2 = ((double) (x + 1) - (double) dstX) * (double) srcW / dstW; sy = sy1; do { double yportion; if (floor2 (sy) == floor2 (sy1)) { yportion = 1.0 - (sy - floor2 (sy)); if (yportion > sy2 - sy1) { yportion = sy2 - sy1; } sy = floor2 (sy); } else if (sy == floor2 (sy2)) { yportion = sy2 - floor2 (sy2); } else { yportion = 1.0; } sx = sx1; do { double xportion; double pcontribution; int p; if (floor2 (sx) == floor2 (sx1)) { xportion = 1.0 - (sx - floor2 (sx)); if (xportion > sx2 - sx1) { xportion = sx2 - sx1; } sx = floor2 (sx); } else if (sx == floor2 (sx2)) { xportion = sx2 - floor2 (sx2); } else { xportion = 1.0; } pcontribution = xportion * yportion; /* 2.08: previously srcX and srcY were ignored. Andrew Pattison */ p = gdImageGetTrueColorPixel (src, (int) sx + srcX, (int) sy + srcY); red += gdTrueColorGetRed (p) * pcontribution; green += gdTrueColorGetGreen (p) * pcontribution; blue += gdTrueColorGetBlue (p) * pcontribution; alpha += gdTrueColorGetAlpha (p) * pcontribution; spixels += xportion * yportion; sx += 1.0; } while (sx < sx2); sy += 1.0; } while (sy < sy2); if (spixels != 0.0) { red /= spixels; green /= spixels; blue /= spixels; alpha /= spixels; alpha += 0.5; } if ( alpha_sum != 0.0f) { if( contrib_sum != 0.0f) { alpha_sum /= contrib_sum; } red /= alpha_sum; green /= alpha_sum; blue /= alpha_sum; } /* Clamping to allow for rounding errors above */ if (red > 255.0) { red = 255.0; } if (green > 255.0) { green = 255.0; } if (blue > 255.0) { blue = 255.0; } if (alpha > gdAlphaMax) { alpha = gdAlphaMax; } gdImageSetPixel (dst, x, y, gdTrueColorAlpha ((int) red, (int) green, (int) blue, (int) alpha)); } } } BGD_DECLARE(void) gdImagePolygon (gdImagePtr im, gdPointPtr p, int n, int c) { if (n <= 0) { return; } gdImageLine (im, p->x, p->y, p[n - 1].x, p[n - 1].y, c); gdImageOpenPolygon (im, p, n, c); } BGD_DECLARE(void) gdImageOpenPolygon (gdImagePtr im, gdPointPtr p, int n, int c) { int i; int lx, ly; if (n <= 0) { return; } lx = p->x; ly = p->y; for (i = 1; (i < n); i++) { p++; gdImageLine (im, lx, ly, p->x, p->y, c); lx = p->x; ly = p->y; } } /* THANKS to Kirsten Schulz for the polygon fixes! */ /* The intersection finding technique of this code could be improved */ /* by remembering the previous intertersection, and by using the slope. */ /* That could help to adjust intersections to produce a nice */ /* interior_extrema. */ BGD_DECLARE(void) gdImageFilledPolygon (gdImagePtr im, gdPointPtr p, int n, int c) { int i; int j; int index; int y; int miny, maxy, pmaxy; int x1, y1; int x2, y2; int ind1, ind2; int ints; int fill_color; if (n <= 0) { return; } if (c == gdAntiAliased) { fill_color = im->AA_color; } else { fill_color = c; } if (!im->polyAllocated) { if (overflow2(sizeof (int), n)) { return; } im->polyInts = (int *) gdMalloc (sizeof (int) * n); if (!im->polyInts) { return; } im->polyAllocated = n; } if (im->polyAllocated < n) { while (im->polyAllocated < n) { im->polyAllocated *= 2; } if (overflow2(sizeof (int), im->polyAllocated)) { return; } im->polyInts = (int *) gdReallocEx (im->polyInts, sizeof (int) * im->polyAllocated); if (!im->polyInts) { return; } } miny = p[0].y; maxy = p[0].y; for (i = 1; (i < n); i++) { if (p[i].y < miny) { miny = p[i].y; } if (p[i].y > maxy) { maxy = p[i].y; } } pmaxy = maxy; /* 2.0.16: Optimization by Ilia Chipitsine -- don't waste time offscreen */ /* 2.0.26: clipping rectangle is even better */ if (miny < im->cy1) { miny = im->cy1; } if (maxy > im->cy2) { maxy = im->cy2; } /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = p[ind1].y; y2 = p[ind2].y; if (y1 < y2) { x1 = p[ind1].x; x2 = p[ind2].x; } else if (y1 > y2) { y2 = p[ind1].y; y1 = p[ind2].y; x2 = p[ind1].x; x1 = p[ind2].x; } else { continue; } /* Do the following math as float intermediately, and round to ensure * that Polygon and FilledPolygon for the same set of points have the * same footprint. */ if ((y >= y1) && (y < y2)) { im->polyInts[ints++] = (int) ((float) ((y - y1) * (x2 - x1)) / (float) (y2 - y1) + 0.5 + x1); } else if ((y == pmaxy) && (y == y2)) { im->polyInts[ints++] = x2; } } /* 2.0.26: polygons pretty much always have less than 100 points, and most of the time they have considerably less. For such trivial cases, insertion sort is a good choice. Also a good choice for future implementations that may wish to indirect through a table. */ for (i = 1; (i < ints); i++) { index = im->polyInts[i]; j = i; while ((j > 0) && (im->polyInts[j - 1] > index)) { im->polyInts[j] = im->polyInts[j - 1]; j--; } im->polyInts[j] = index; } for (i = 0; (i < (ints-1)); i += 2) { /* 2.0.29: back to gdImageLine to prevent segfaults when performing a pattern fill */ gdImageLine (im, im->polyInts[i], y, im->polyInts[i + 1], y, fill_color); } } /* If we are drawing this AA, then redraw the border with AA lines. */ /* This doesn't work as well as I'd like, but it doesn't clash either. */ if (c == gdAntiAliased) { gdImagePolygon (im, p, n, c); } } static void gdImageSetAAPixelColor(gdImagePtr im, int x, int y, int color, int t); BGD_DECLARE(void) gdImageSetStyle (gdImagePtr im, int *style, int noOfPixels) { if (im->style) { gdFree (im->style); } if (overflow2(sizeof (int), noOfPixels)) { return; } im->style = (int *) gdMalloc (sizeof (int) * noOfPixels); if (!im->style) { return; } memcpy (im->style, style, sizeof (int) * noOfPixels); im->styleLength = noOfPixels; im->stylePos = 0; } BGD_DECLARE(void) gdImageSetThickness (gdImagePtr im, int thickness) { im->thick = thickness; } BGD_DECLARE(void) gdImageSetBrush (gdImagePtr im, gdImagePtr brush) { int i; im->brush = brush; if ((!im->trueColor) && (!im->brush->trueColor)) { for (i = 0; (i < gdImageColorsTotal (brush)); i++) { int index; index = gdImageColorResolveAlpha (im, gdImageRed (brush, i), gdImageGreen (brush, i), gdImageBlue (brush, i), gdImageAlpha (brush, i)); im->brushColorMap[i] = index; } } } BGD_DECLARE(void) gdImageSetTile (gdImagePtr im, gdImagePtr tile) { int i; im->tile = tile; if ((!im->trueColor) && (!im->tile->trueColor)) { for (i = 0; (i < gdImageColorsTotal (tile)); i++) { int index; index = gdImageColorResolveAlpha (im, gdImageRed (tile, i), gdImageGreen (tile, i), gdImageBlue (tile, i), gdImageAlpha (tile, i)); im->tileColorMap[i] = index; } } } BGD_DECLARE(void) gdImageSetAntiAliased (gdImagePtr im, int c) { im->AA = 1; im->AA_color = c; im->AA_dont_blend = -1; } BGD_DECLARE(void) gdImageSetAntiAliasedDontBlend (gdImagePtr im, int c, int dont_blend) { im->AA = 1; im->AA_color = c; im->AA_dont_blend = dont_blend; } BGD_DECLARE(void) gdImageInterlace (gdImagePtr im, int interlaceArg) { im->interlace = interlaceArg; } BGD_DECLARE(int) gdImageCompare (gdImagePtr im1, gdImagePtr im2) { int x, y; int p1, p2; int cmpStatus = 0; int sx, sy; if (im1->interlace != im2->interlace) { cmpStatus |= GD_CMP_INTERLACE; } if (im1->transparent != im2->transparent) { cmpStatus |= GD_CMP_TRANSPARENT; } if (im1->trueColor != im2->trueColor) { cmpStatus |= GD_CMP_TRUECOLOR; } sx = im1->sx; if (im1->sx != im2->sx) { cmpStatus |= GD_CMP_SIZE_X + GD_CMP_IMAGE; if (im2->sx < im1->sx) { sx = im2->sx; } } sy = im1->sy; if (im1->sy != im2->sy) { cmpStatus |= GD_CMP_SIZE_Y + GD_CMP_IMAGE; if (im2->sy < im1->sy) { sy = im2->sy; } } if (im1->colorsTotal != im2->colorsTotal) { cmpStatus |= GD_CMP_NUM_COLORS; } for (y = 0; (y < sy); y++) { for (x = 0; (x < sx); x++) { p1 = im1->trueColor ? gdImageTrueColorPixel (im1, x, y) : gdImagePalettePixel (im1, x, y); p2 = im2->trueColor ? gdImageTrueColorPixel (im2, x, y) : gdImagePalettePixel (im2, x, y); if (gdImageRed (im1, p1) != gdImageRed (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } if (gdImageGreen (im1, p1) != gdImageGreen (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } if (gdImageBlue (im1, p1) != gdImageBlue (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } #if 0 /* Soon we'll add alpha channel to palettes */ if (gdImageAlpha (im1, p1) != gdImageAlpha (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } #endif } if (cmpStatus & GD_CMP_COLOR) { break; }; } return cmpStatus; } /* Thanks to Frank Warmerdam for this superior implementation of gdAlphaBlend(), which merges alpha in the destination color much better. */ BGD_DECLARE(int) gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); } static int gdAlphaOverlayColor (int src, int dst, int max ); BGD_DECLARE(int) gdLayerOverlay (int dst, int src) { int a1, a2; a1 = gdAlphaMax - gdTrueColorGetAlpha(dst); a2 = gdAlphaMax - gdTrueColorGetAlpha(src); return ( ((gdAlphaMax - a1*a2/gdAlphaMax) << 24) + (gdAlphaOverlayColor( gdTrueColorGetRed(src), gdTrueColorGetRed(dst), gdRedMax ) << 16) + (gdAlphaOverlayColor( gdTrueColorGetGreen(src), gdTrueColorGetGreen(dst), gdGreenMax ) << 8) + (gdAlphaOverlayColor( gdTrueColorGetBlue(src), gdTrueColorGetBlue(dst), gdBlueMax )) ); } /* Apply 'overlay' effect - background pixels are colourised by the foreground colour */ static int gdAlphaOverlayColor (int src, int dst, int max ) { dst = dst << 1; if( dst > max ) { /* in the "light" zone */ return dst + (src << 1) - (dst * src / max) - max; } else { /* in the "dark" zone */ return dst * src / max; } } /* Apply 'multiply' effect */ BGD_DECLARE(int) gdLayerMultiply (int dst, int src) { int a1, a2, r1, r2, g1, g2, b1, b2; a1 = gdAlphaMax - gdTrueColorGetAlpha(src); a2 = gdAlphaMax - gdTrueColorGetAlpha(dst); r1 = gdRedMax - (a1 * (gdRedMax - gdTrueColorGetRed(src))) / gdAlphaMax; r2 = gdRedMax - (a2 * (gdRedMax - gdTrueColorGetRed(dst))) / gdAlphaMax; g1 = gdGreenMax - (a1 * (gdGreenMax - gdTrueColorGetGreen(src))) / gdAlphaMax; g2 = gdGreenMax - (a2 * (gdGreenMax - gdTrueColorGetGreen(dst))) / gdAlphaMax; b1 = gdBlueMax - (a1 * (gdBlueMax - gdTrueColorGetBlue(src))) / gdAlphaMax; b2 = gdBlueMax - (a2 * (gdBlueMax - gdTrueColorGetBlue(dst))) / gdAlphaMax ; a1 = gdAlphaMax - a1; a2 = gdAlphaMax - a2; return ( ((a1*a2/gdAlphaMax) << 24) + ((r1*r2/gdRedMax) << 16) + ((g1*g2/gdGreenMax) << 8) + ((b1*b2/gdBlueMax)) ); } BGD_DECLARE(void) gdImageAlphaBlending (gdImagePtr im, int alphaBlendingArg) { im->alphaBlendingFlag = alphaBlendingArg; } BGD_DECLARE(void) gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg) { im->saveAlphaFlag = saveAlphaArg; } BGD_DECLARE(void) gdImageSetClip (gdImagePtr im, int x1, int y1, int x2, int y2) { if (x1 < 0) { x1 = 0; } if (x1 >= im->sx) { x1 = im->sx - 1; } if (x2 < 0) { x2 = 0; } if (x2 >= im->sx) { x2 = im->sx - 1; } if (y1 < 0) { y1 = 0; } if (y1 >= im->sy) { y1 = im->sy - 1; } if (y2 < 0) { y2 = 0; } if (y2 >= im->sy) { y2 = im->sy - 1; } im->cx1 = x1; im->cy1 = y1; im->cx2 = x2; im->cy2 = y2; } BGD_DECLARE(void) gdImageGetClip (gdImagePtr im, int *x1P, int *y1P, int *x2P, int *y2P) { *x1P = im->cx1; *y1P = im->cy1; *x2P = im->cx2; *y2P = im->cy2; } BGD_DECLARE(void) gdImageSetResolution(gdImagePtr im, const unsigned int res_x, const unsigned int res_y) { if (res_x > 0) im->res_x = res_x; if (res_y > 0) im->res_y = res_y; } /* * Added on 2003/12 by Pierre-Alain Joye (pajoye@pearfr.org) * */ #define BLEND_COLOR(a, nc, c, cc) \ nc = (cc) + (((((c) - (cc)) * (a)) + ((((c) - (cc)) * (a)) >> 8) + 0x80) >> 8); static void gdImageSetAAPixelColor(gdImagePtr im, int x, int y, int color, int t) { int dr,dg,db,p,r,g,b; /* 2.0.34: watch out for out of range calls */ if (!gdImageBoundsSafeMacro(im, x, y)) { return; } p = gdImageGetPixel(im,x,y); /* TBB: we have to implement the dont_blend stuff to provide the full feature set of the old implementation */ if ((p == color) || ((p == im->AA_dont_blend) && (t != 0x00))) { return; } dr = gdTrueColorGetRed(color); dg = gdTrueColorGetGreen(color); db = gdTrueColorGetBlue(color); r = gdTrueColorGetRed(p); g = gdTrueColorGetGreen(p); b = gdTrueColorGetBlue(p); BLEND_COLOR(t, dr, r, dr); BLEND_COLOR(t, dg, g, dg); BLEND_COLOR(t, db, b, db); im->tpixels[y][x] = gdTrueColorAlpha(dr, dg, db, gdAlphaOpaque); } static void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col) { /* keep them as 32bits */ long x, y, inc, frac; long dx, dy,tmp; int w, wid, wstart; int thick = im->thick; if (!im->trueColor) { /* TBB: don't crash when the image is of the wrong type */ gdImageLine(im, x1, y1, x2, y2, col); return; } /* TBB: use the clipping rectangle */ if (clip_1d (&x1, &y1, &x2, &y2, im->cx1, im->cx2) == 0) return; if (clip_1d (&y1, &x1, &y2, &x2, im->cy1, im->cy2) == 0) return; dx = x2 - x1; dy = y2 - y1; if (dx == 0 && dy == 0) { /* TBB: allow setting points */ gdImageSetAAPixelColor(im, x1, y1, col, 0xFF); return; } else { double ag; /* Cast the long to an int to avoid compiler warnings about truncation. * This isn't a problem as computed dy/dx values came from ints above. */ ag = fabs(abs((int)dy) < abs((int)dx) ? cos(atan2(dy, dx)) : sin(atan2(dy, dx))); if (ag != 0) { wid = thick / ag; } else { wid = 1; } if (wid == 0) { wid = 1; } } /* Axis aligned lines */ if (dx == 0) { gdImageVLine(im, x1, y1, y2, col); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, col); return; } if (abs((int)dx) > abs((int)dy)) { if (dx < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } y = y1; inc = (dy * 65536) / dx; frac = 0; /* TBB: set the last pixel for consistency (<=) */ for (x = x1 ; x <= x2 ; x++) { wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetAAPixelColor(im, x , w , col , (frac >> 8) & 0xFF); gdImageSetAAPixelColor(im, x , w + 1 , col, (~frac >> 8) & 0xFF); } frac += inc; if (frac >= 65536) { frac -= 65536; y++; } else if (frac < 0) { frac += 65536; y--; } } } else { if (dy < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } x = x1; inc = (dx * 65536) / dy; frac = 0; /* TBB: set the last pixel for consistency (<=) */ for (y = y1 ; y <= y2 ; y++) { wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetAAPixelColor(im, w , y , col, (frac >> 8) & 0xFF); gdImageSetAAPixelColor(im, w + 1, y, col, (~frac >> 8) & 0xFF); } frac += inc; if (frac >= 65536) { frac -= 65536; x++; } else if (frac < 0) { frac += 65536; x--; } } } } /* convert a palette image to true color */ BGD_DECLARE(int) gdImagePaletteToTrueColor(gdImagePtr src) { unsigned int y; unsigned int yy; if (src == NULL) { return 0; } if (src->trueColor == 1) { return 1; } else { unsigned int x; const unsigned int sy = gdImageSY(src); const unsigned int sx = gdImageSX(src); src->tpixels = (int **) gdMalloc(sizeof(int *) * sy); if (src->tpixels == NULL) { return 0; } for (y = 0; y < sy; y++) { const unsigned char *src_row = src->pixels[y]; int * dst_row; /* no need to calloc it, we overwrite all pxl anyway */ src->tpixels[y] = (int *) gdMalloc(sx * sizeof(int)); if (src->tpixels[y] == NULL) { goto clean_on_error; } dst_row = src->tpixels[y]; for (x = 0; x < sx; x++) { const unsigned char c = *(src_row + x); if (c == src->transparent) { *(dst_row + x) = gdTrueColorAlpha(0, 0, 0, 127); } else { *(dst_row + x) = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]); } } } } /* free old palette buffer (y is sy) */ for (yy = 0; yy < y; yy++) { gdFree(src->pixels[yy]); } gdFree(src->pixels); src->trueColor = 1; src->pixels = NULL; src->alphaBlendingFlag = 0; src->saveAlphaFlag = 1; return 1; clean_on_error: /* free new true color buffer (y is not allocated, have failed) */ for (yy = 0; yy < y; yy++) { gdFree(src->tpixels[yy]); } gdFree(src->tpixels); return 0; }
./CrossVul/dataset_final_sorted/CWE-119/c/good_5512_0
crossvul-cpp_data_good_5816_0
/* * JPEG 2000 image decoder * Copyright (c) 2007 Kamil Nowosad * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * JPEG 2000 image decoder */ #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "thread.h" #include "jpeg2000.h" #define JP2_SIG_TYPE 0x6A502020 #define JP2_SIG_VALUE 0x0D0A870A #define JP2_CODESTREAM 0x6A703263 #define JP2_HEADER 0x6A703268 #define HAD_COC 0x01 #define HAD_QCC 0x02 typedef struct Jpeg2000TilePart { uint8_t tile_index; // Tile index who refers the tile-part const uint8_t *tp_end; GetByteContext tpg; // bit stream in tile-part } Jpeg2000TilePart; /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile * one per component, so tile_part elements have a size of 3 */ typedef struct Jpeg2000Tile { Jpeg2000Component *comp; uint8_t properties[4]; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; Jpeg2000TilePart tile_part[4]; uint16_t tp_idx; // Tile-part index } Jpeg2000Tile; typedef struct Jpeg2000DecoderContext { AVClass *class; AVCodecContext *avctx; GetByteContext g; int width, height; int image_offset_x, image_offset_y; int tile_offset_x, tile_offset_y; uint8_t cbps[4]; // bits per sample in particular components uint8_t sgnd[4]; // if a component is signed uint8_t properties[4]; int cdx[4], cdy[4]; int precision; int ncomponents; int colour_space; uint32_t palette[256]; int8_t pal8; int cdef[4]; int tile_width, tile_height; unsigned numXtiles, numYtiles; int maxtilelen; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; int bit_index; int curtileno; Jpeg2000Tile *tile; /*options parameters*/ int reduction_factor; } Jpeg2000DecoderContext; /* get_bits functions for JPEG2000 packet bitstream * It is a get_bit function with a bit-stuffing routine. If the value of the * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB. * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */ static int get_bits(Jpeg2000DecoderContext *s, int n) { int res = 0; while (--n >= 0) { res <<= 1; if (s->bit_index == 0) { s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu); } s->bit_index--; res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1; } return res; } static void jpeg2000_flush(Jpeg2000DecoderContext *s) { if (bytestream2_get_byte(&s->g) == 0xff) bytestream2_skip(&s->g, 1); s->bit_index = 8; } /* decode the value stored in node */ static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node, int threshold) { Jpeg2000TgtNode *stack[30]; int sp = -1, curval = 0; if (!node) return AVERROR_INVALIDDATA; while (node && !node->vis) { stack[++sp] = node; node = node->parent; } if (node) curval = node->val; else curval = stack[sp]->val; while (curval < threshold && sp >= 0) { if (curval < stack[sp]->val) curval = stack[sp]->val; while (curval < threshold) { int ret; if ((ret = get_bits(s, 1)) > 0) { stack[sp]->vis++; break; } else if (!ret) curval++; else return ret; } stack[sp]->val = curval; sp--; } return curval; } static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components, int bpc, uint32_t log2_chroma_wh, int pal8) { int match = 1; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc->nb_components != components) { return 0; } switch (components) { case 4: match = match && desc->comp[3].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 14 & 3) == 0 && (log2_chroma_wh >> 12 & 3) == 0; case 3: match = match && desc->comp[2].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h; case 2: match = match && desc->comp[1].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h; case 1: match = match && desc->comp[0].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 2 & 3) == 0 && (log2_chroma_wh & 3) == 0 && (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL; } return match; } // pix_fmts with lower bpp have to be listed before // similar pix_fmts with higher bpp. #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \ AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \ AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \ AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \ AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \ AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \ AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \ AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \ AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \ AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \ AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12 static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS}; static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS}; static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS}; static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS}; static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS}; /* marker segments */ /* get sizes and offsets of image, tiles; number of components */ static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (s->image_offset_x || s->image_offset_y) { avpriv_request_sample(s->avctx, "Support for image offsets"); return AVERROR_PATCHWELCOME; } if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } /* get common part for COD and COC segments */ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } if (c->nreslevels <= s->reduction_factor) { /* we are forced to update reduction_factor as its requested value is not compatible with this bitstream, and as we might have used it already in setup earlier we have to fail this frame until reinitialization is implemented */ av_log(s->avctx, AV_LOG_ERROR, "reduction_factor too large for this bitstream, max is %d\n", c->nreslevels - 1); s->reduction_factor = c->nreslevels - 1; return AVERROR(EINVAL); } /* compute number of resolution levels to decode */ c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } /* get coding parameters for a particular tile or whole image*/ static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { Jpeg2000CodingStyle tmp; int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; tmp.csty = bytestream2_get_byteu(&s->g); // get progression order tmp.prog_order = bytestream2_get_byteu(&s->g); tmp.nlayers = bytestream2_get_be16u(&s->g); tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation if (tmp.mct && s->ncomponents < 3) { av_log(s->avctx, AV_LOG_ERROR, "MCT %d with too few components (%d)\n", tmp.mct, s->ncomponents); return AVERROR_INVALIDDATA; } if ((ret = get_cox(s, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_COC)) memcpy(c + compno, &tmp, sizeof(tmp)); return 0; } /* Get coding parameters for a component in the whole image or a * particular tile. */ static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } c += compno; c->csty = bytestream2_get_byteu(&s->g); if ((ret = get_cox(s, c)) < 0) return ret; properties[compno] |= HAD_COC; return 0; } /* Get common part for QCD and QCC segments. */ static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q) { int i, x; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; x = bytestream2_get_byteu(&s->g); // Sqcd q->nguardbits = x >> 5; q->quantsty = x & 0x1f; if (q->quantsty == JPEG2000_QSTY_NONE) { n -= 3; if (bytestream2_get_bytes_left(&s->g) < n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) q->expn[i] = bytestream2_get_byteu(&s->g) >> 3; } else if (q->quantsty == JPEG2000_QSTY_SI) { if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; x = bytestream2_get_be16u(&s->g); q->expn[0] = x >> 11; q->mant[0] = x & 0x7ff; for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) { int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3); q->expn[i] = curexpn; q->mant[i] = q->mant[0]; } } else { n = (n - 3) >> 1; if (bytestream2_get_bytes_left(&s->g) < 2 * n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) { x = bytestream2_get_be16u(&s->g); q->expn[i] = x >> 11; q->mant[i] = x & 0x7ff; } } return 0; } /* Get quantization parameters for a particular tile or a whole image. */ static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { Jpeg2000QuantStyle tmp; int compno, ret; if ((ret = get_qcx(s, n, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_QCC)) memcpy(q + compno, &tmp, sizeof(tmp)); return 0; } /* Get quantization parameters for a component in the whole image * on in a particular tile. */ static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { int compno; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } properties[compno] |= HAD_QCC; return get_qcx(s, n - 1, q + compno); } /* Get start of tile segment. */ static int get_sot(Jpeg2000DecoderContext *s, int n) { Jpeg2000TilePart *tp; uint16_t Isot; uint32_t Psot; uint8_t TPsot; if (bytestream2_get_bytes_left(&s->g) < 8) return AVERROR_INVALIDDATA; s->curtileno = 0; Isot = bytestream2_get_be16u(&s->g); // Isot if (Isot >= s->numXtiles * s->numYtiles) return AVERROR_INVALIDDATA; s->curtileno = Isot; Psot = bytestream2_get_be32u(&s->g); // Psot TPsot = bytestream2_get_byteu(&s->g); // TPsot /* Read TNSot but not used */ bytestream2_get_byteu(&s->g); // TNsot if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) { av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot); return AVERROR_INVALIDDATA; } if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) { avpriv_request_sample(s->avctx, "Support for %d components", TPsot); return AVERROR_PATCHWELCOME; } s->tile[Isot].tp_idx = TPsot; tp = s->tile[Isot].tile_part + TPsot; tp->tile_index = Isot; tp->tp_end = s->g.buffer + Psot - n - 2; if (!TPsot) { Jpeg2000Tile *tile = s->tile + s->curtileno; /* copy defaults */ memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle)); memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle)); } return 0; } /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1 * Used to know the number of tile parts and lengths. * There may be multiple TLMs in the header. * TODO: The function is not used for tile-parts management, nor anywhere else. * It can be useful to allocate memory for tile parts, before managing the SOT * markers. Parsing the TLM header is needed to increment the input header * buffer. * This marker is mandatory for DCI. */ static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n) { uint8_t Stlm, ST, SP, tile_tlm, i; bytestream2_get_byte(&s->g); /* Ztlm: skipped */ Stlm = bytestream2_get_byte(&s->g); // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02); ST = (Stlm >> 4) & 0x03; // TODO: Manage case of ST = 0b11 --> raise error SP = (Stlm >> 6) & 0x01; tile_tlm = (n - 4) / ((SP + 1) * 2 + ST); for (i = 0; i < tile_tlm; i++) { switch (ST) { case 0: break; case 1: bytestream2_get_byte(&s->g); break; case 2: bytestream2_get_be16(&s->g); break; case 3: bytestream2_get_be32(&s->g); break; } if (SP == 0) { bytestream2_get_be16(&s->g); } else { bytestream2_get_be32(&s->g); } } return 0; } static int init_tile(Jpeg2000DecoderContext *s, int tileno) { int compno; int tilex = tileno % s->numXtiles; int tiley = tileno / s->numXtiles; Jpeg2000Tile *tile = s->tile + tileno; if (!tile->comp) return AVERROR(ENOMEM); for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; int ret; // global bandno comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x); comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width); comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y); comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height); comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor); comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor); comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor); comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor); if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx)) return ret; } return 0; } /* Read the number of coding passes. */ static int getnpasses(Jpeg2000DecoderContext *s) { int num; if (!get_bits(s, 1)) return 1; if (!get_bits(s, 1)) return 2; if ((num = get_bits(s, 2)) != 3) return num < 0 ? num : 3 + num; if ((num = get_bits(s, 5)) != 31) return num < 0 ? num : 6 + num; num = get_bits(s, 7); return num < 0 ? num : 37 + num; } static int getlblockinc(Jpeg2000DecoderContext *s) { int res = 0, ret; while (ret = get_bits(s, 1)) { if (ret < 0) return ret; res++; } return res; } static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkno, ret, nb_code_blocks; if (!(ret = get_bits(s, 1))) { jpeg2000_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); if (v < 0) { av_log(s->avctx, AV_LOG_ERROR, "nonzerobits %d invalid\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; } if ((newpasses = getnpasses(s)) < 0) return newpasses; if ((llen = getlblockinc(s)) < 0) return llen; cblk->lblock += llen; if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0) return ret; if (ret > sizeof(cblk->data)) { avpriv_request_sample(s->avctx, "Block with lengthinc greater than %zu", sizeof(cblk->data)); return AVERROR_PATCHWELCOME; } cblk->lengthinc = ret; cblk->npasses += newpasses; } } jpeg2000_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) bytestream2_skip(&s->g, 2); else av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n"); } for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2 ) { av_log(s->avctx, AV_LOG_ERROR, "Block length %d or lengthinc %d is too large\n", cblk->length, cblk->lengthinc); return AVERROR_INVALIDDATA; } bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc); cblk->length += cblk->lengthinc; cblk->lengthinc = 0; } } return 0; } static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int ret = 0; int layno, reslevelno, compno, precno, ok_reslevel; int x, y; s->bit_index = 8; switch (tile->codsty[0].prog_order) { case JPEG2000_PGOD_RLCP: avpriv_request_sample(s->avctx, "Progression order RLCP"); case JPEG2000_PGOD_LRCP: for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { ok_reslevel = 1; for (reslevelno = 0; ok_reslevel; reslevelno++) { ok_reslevel = 0; for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; if (reslevelno < codsty->nreslevels) { Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; ok_reslevel = 1; for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } break; case JPEG2000_PGOD_CPRL: for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; /* Set bit stream buffer address according to tile-part. * For DCinema one tile-part per component, so can be * indexed by component. */ s->g = tile->tile_part[compno].tpg; /* Position loop (y axis) * TODO: Automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (y = 0; y < s->height; y += 256) { /* Position loop (y axis) * TODO: automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (x = 0; x < s->width; x += 256) { for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) { uint16_t prcx, prcy; uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) || (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) || (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; // check if a precinct exists prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width; prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height; precno = prcx + rlevel->num_precincts_x * prcy; for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } } break; case JPEG2000_PGOD_RPCL: avpriv_request_sample(s->avctx, "Progression order RPCL"); ret = AVERROR_PATCHWELCOME; break; case JPEG2000_PGOD_PCRL: avpriv_request_sample(s->avctx, "Progression order PCRL"); ret = AVERROR_PATCHWELCOME; break; default: break; } /* EOC marker reached */ bytestream2_skip(&s->g, 2); return ret; } /* TIER-1 routines */ static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) { if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB) && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) { int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit); if (bpass_csty_symbol) t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask; else t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS; } } } static void decode_refpass(Jpeg2000T1Context *t1, int width, int height, int bpno) { int phalf, nhalf; int y0, x, y; phalf = 1 << (bpno - 1); nhalf = -phalf; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) { int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]); int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf; t1->data[y][x] += t1->data[y][x] < 0 ? -r : r; t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF; } } static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y, runlen, dec; for (y0 = 0; y0 < height; y0 += 4) { for (x = 0; x < width; x++) { if (y0 + 3 < height && !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) { if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL)) continue; runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); dec = 1; } else { runlen = 0; dec = 0; } for (y = y0 + runlen; y < y0 + 4 && y < height; y++) { if (!dec) { if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno)); } } if (dec) { int xorbit; int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1], &xorbit); t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } dec = 0; t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS; } } } if (seg_symbols) { int val; val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); if (val != 0xa) av_log(s->avctx, AV_LOG_ERROR, "Segmentation symbol value incorrect\n"); } } static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; av_assert0(width <= JPEG2000_MAX_CBLKW); av_assert0(height <= JPEG2000_MAX_CBLKH); for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } /* TODO: Verify dequantization for lossless case * comp->data can be float or int * band->stepsize can be float or int * depending on the type of DWT transformation. * see ISO/IEC 15444-1:2002 A.6.1 */ /* Float dequantization of a codeblock.*/ static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = src[i] * band->f_stepsize; } } /* Integer dequantization of a codeblock.*/ static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15; } } /* Inverse ICT parameters in float and integer. * int value = (float value) * (1<<16) */ static const float f_ict_params[4] = { 1.402f, 0.34413f, 0.71414f, 1.772f }; static const int i_ict_params[4] = { 91881, 22553, 46802, 116130 }; static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int i, csize = 1; int32_t *src[3], i0, i1, i2; float *srcf[3], i0f, i1f, i2f; for (i = 1; i < 3; i++) if (tile->codsty[0].transform != tile->codsty[i].transform) { av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n"); return; } for (i = 0; i < 3; i++) if (tile->codsty[0].transform == FF_DWT97) srcf[i] = tile->comp[i].f_data; else src [i] = tile->comp[i].i_data; for (i = 0; i < 2; i++) csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0]; switch (tile->codsty[0].transform) { case FF_DWT97: for (i = 0; i < csize; i++) { i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]); i1f = *srcf[0] - (f_ict_params[1] * *srcf[1]) - (f_ict_params[2] * *srcf[2]); i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]); *srcf[0]++ = i0f; *srcf[1]++ = i1f; *srcf[2]++ = i2f; } break; case FF_DWT97_INT: for (i = 0; i < csize; i++) { i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16); i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16) - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16); i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16); *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; case FF_DWT53: for (i = 0; i < csize; i++) { i1 = *src[0] - (*src[2] + *src[1] >> 2); i0 = i1 + *src[2]; i2 = i1 + *src[1]; *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; } } static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x / s->cdx[compno] * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s) { int tileno, compno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { if (s->tile[tileno].comp) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = s->tile[tileno].comp + compno; Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno; ff_jpeg2000_cleanup(comp, codsty); } av_freep(&s->tile[tileno].comp); } } av_freep(&s->tile); memset(s->codsty, 0, sizeof(s->codsty)); memset(s->qntsty, 0, sizeof(s->qntsty)); s->numXtiles = s->numYtiles = 0; } static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s) { Jpeg2000CodingStyle *codsty = s->codsty; Jpeg2000QuantStyle *qntsty = s->qntsty; uint8_t *properties = s->properties; for (;;) { int len, ret = 0; uint16_t marker; int oldpos; if (bytestream2_get_bytes_left(&s->g) < 2) { av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n"); break; } marker = bytestream2_get_be16u(&s->g); oldpos = bytestream2_tell(&s->g); if (marker == JPEG2000_SOD) { Jpeg2000Tile *tile; Jpeg2000TilePart *tp; if (!s->tile) { av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n"); return AVERROR_INVALIDDATA; } if (s->curtileno < 0) { av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n"); return AVERROR_INVALIDDATA; } tile = s->tile + s->curtileno; tp = tile->tile_part + tile->tp_idx; if (tp->tp_end < s->g.buffer) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n"); return AVERROR_INVALIDDATA; } bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer); bytestream2_skip(&s->g, tp->tp_end - s->g.buffer); continue; } if (marker == JPEG2000_EOC) break; len = bytestream2_get_be16(&s->g); if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) return AVERROR_INVALIDDATA; switch (marker) { case JPEG2000_SIZ: ret = get_siz(s); if (!s->tile) s->numXtiles = s->numYtiles = 0; break; case JPEG2000_COC: ret = get_coc(s, codsty, properties); break; case JPEG2000_COD: ret = get_cod(s, codsty, properties); break; case JPEG2000_QCC: ret = get_qcc(s, len, qntsty, properties); break; case JPEG2000_QCD: ret = get_qcd(s, len, qntsty, properties); break; case JPEG2000_SOT: if (!(ret = get_sot(s, len))) { av_assert1(s->curtileno >= 0); codsty = s->tile[s->curtileno].codsty; qntsty = s->tile[s->curtileno].qntsty; properties = s->tile[s->curtileno].properties; } break; case JPEG2000_COM: // the comment is ignored bytestream2_skip(&s->g, len - 2); break; case JPEG2000_TLM: // Tile-part lengths ret = get_tlm(s, len); break; default: av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%X\n", marker, bytestream2_tell(&s->g) - 4); bytestream2_skip(&s->g, len - 2); break; } if (bytestream2_tell(&s->g) - oldpos != len || ret) { av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker); return ret ? ret : -1; } } return 0; } /* Read bit stream packets --> T2 operation. */ static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s) { int ret = 0; int tileno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { Jpeg2000Tile *tile = s->tile + tileno; if (ret = init_tile(s, tileno)) return ret; s->g = tile->tile_part[0].tpg; if (ret = jpeg2000_decode_packets(s, tile)) return ret; } return 0; } static int jp2_find_codestream(Jpeg2000DecoderContext *s) { uint32_t atom_size, atom, atom_end; int search_range = 10; while (search_range && bytestream2_get_bytes_left(&s->g) >= 8) { atom_size = bytestream2_get_be32u(&s->g); atom = bytestream2_get_be32u(&s->g); atom_end = bytestream2_tell(&s->g) + atom_size - 8; if (atom == JP2_CODESTREAM) return 1; if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size) return 0; if (atom == JP2_HEADER && atom_size >= 16) { uint32_t atom2_size, atom2, atom2_end; do { atom2_size = bytestream2_get_be32u(&s->g); atom2 = bytestream2_get_be32u(&s->g); atom2_end = bytestream2_tell(&s->g) + atom2_size - 8; if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size) break; if (atom2 == JP2_CODESTREAM) { return 1; } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) { int method = bytestream2_get_byteu(&s->g); bytestream2_skipu(&s->g, 2); if (method == 1) { s->colour_space = bytestream2_get_be32u(&s->g); } } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) { int i, size, colour_count, colour_channels, colour_depth[3]; uint32_t r, g, b; colour_count = bytestream2_get_be16u(&s->g); colour_channels = bytestream2_get_byteu(&s->g); // FIXME: Do not ignore channel_sign colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; size = (colour_depth[0] + 7 >> 3) * colour_count + (colour_depth[1] + 7 >> 3) * colour_count + (colour_depth[2] + 7 >> 3) * colour_count; if (colour_count > 256 || colour_channels != 3 || colour_depth[0] > 16 || colour_depth[1] > 16 || colour_depth[2] > 16 || atom2_size < size) { avpriv_request_sample(s->avctx, "Unknown palette"); bytestream2_seek(&s->g, atom2_end, SEEK_SET); continue; } s->pal8 = 1; for (i = 0; i < colour_count; i++) { if (colour_depth[0] <= 8) { r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0]; r |= r >> colour_depth[0]; } else { r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8; } if (colour_depth[1] <= 8) { g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1]; r |= r >> colour_depth[1]; } else { g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8; } if (colour_depth[2] <= 8) { b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2]; r |= r >> colour_depth[2]; } else { b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8; } s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b; } } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) { int n = bytestream2_get_be16u(&s->g); for (; n>0; n--) { int cn = bytestream2_get_be16(&s->g); int av_unused typ = bytestream2_get_be16(&s->g); int asoc = bytestream2_get_be16(&s->g); if (cn < 4 || asoc < 4) s->cdef[cn] = asoc; } } bytestream2_seek(&s->g, atom2_end, SEEK_SET); } while (atom_end - atom2_end >= 8); } else { search_range--; } bytestream2_seek(&s->g, atom_end, SEEK_SET); } return 0; } static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { Jpeg2000DecoderContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; int tileno, ret; s->avctx = avctx; bytestream2_init(&s->g, avpkt->data, avpkt->size); s->curtileno = -1; memset(s->cdef, -1, sizeof(s->cdef)); if (bytestream2_get_bytes_left(&s->g) < 2) { ret = AVERROR_INVALIDDATA; goto end; } // check if the image is in jp2 format if (bytestream2_get_bytes_left(&s->g) >= 12 && (bytestream2_get_be32u(&s->g) == 12) && (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) && (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) { if (!jp2_find_codestream(s)) { av_log(avctx, AV_LOG_ERROR, "Could not find Jpeg2000 codestream atom.\n"); ret = AVERROR_INVALIDDATA; goto end; } } else { bytestream2_seek(&s->g, 0, SEEK_SET); } while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC) bytestream2_skip(&s->g, 1); if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) { av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n"); ret = AVERROR_INVALIDDATA; goto end; } if (ret = jpeg2000_read_main_headers(s)) goto end; /* get picture buffer */ if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) goto end; picture->pict_type = AV_PICTURE_TYPE_I; picture->key_frame = 1; if (ret = jpeg2000_read_bitstream_packets(s)) goto end; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture)) goto end; jpeg2000_dec_cleanup(s); *got_frame = 1; if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t)); return bytestream2_tell(&s->g); end: jpeg2000_dec_cleanup(s); return ret; } static void jpeg2000_init_static_data(AVCodec *codec) { ff_jpeg2000_init_tier1_luts(); ff_mqc_init_context_tables(); } #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "lowres", "Lower the decoding resolution by a power of two", OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD }, { NULL }, }; static const AVProfile profiles[] = { { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" }, { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" }, { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" }, { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" }, { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" }, { FF_PROFILE_UNKNOWN }, }; static const AVClass jpeg2000_class = { .class_name = "jpeg2000", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_jpeg2000_decoder = { .name = "jpeg2000", .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_JPEG2000, .capabilities = CODEC_CAP_FRAME_THREADS, .priv_data_size = sizeof(Jpeg2000DecoderContext), .init_static_data = jpeg2000_init_static_data, .decode = jpeg2000_decode_frame, .priv_class = &jpeg2000_class, .max_lowres = 5, .profiles = NULL_IF_CONFIG_SMALL(profiles) };
./CrossVul/dataset_final_sorted/CWE-119/c/good_5816_0
crossvul-cpp_data_good_1579_0
/* * 8253/8254 interval timer emulation * * Copyright (c) 2003-2004 Fabrice Bellard * Copyright (c) 2006 Intel Corporation * Copyright (c) 2007 Keir Fraser, XenSource Inc * Copyright (c) 2008 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Authors: * Sheng Yang <sheng.yang@intel.com> * Based on QEMU and Xen. */ #define pr_fmt(fmt) "pit: " fmt #include <linux/kvm_host.h> #include "irq.h" #include "i8254.h" #ifndef CONFIG_X86_64 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y)) #else #define mod_64(x, y) ((x) % (y)) #endif #define RW_STATE_LSB 1 #define RW_STATE_MSB 2 #define RW_STATE_WORD0 3 #define RW_STATE_WORD1 4 /* Compute with 96 bit intermediate result: (a*b)/c */ static u64 muldiv64(u64 a, u32 b, u32 c) { union { u64 ll; struct { u32 low, high; } l; } u, res; u64 rl, rh; u.ll = a; rl = (u64)u.l.low * (u64)b; rh = (u64)u.l.high * (u64)b; rh += (rl >> 32); res.l.high = div64_u64(rh, c); res.l.low = div64_u64(((mod_64(rh, c) << 32) + (rl & 0xffffffff)), c); return res.ll; } static void pit_set_gate(struct kvm *kvm, int channel, u32 val) { struct kvm_kpit_channel_state *c = &kvm->arch.vpit->pit_state.channels[channel]; WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock)); switch (c->mode) { default: case 0: case 4: /* XXX: just disable/enable counting */ break; case 1: case 2: case 3: case 5: /* Restart counting on rising edge. */ if (c->gate < val) c->count_load_time = ktime_get(); break; } c->gate = val; } static int pit_get_gate(struct kvm *kvm, int channel) { WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock)); return kvm->arch.vpit->pit_state.channels[channel].gate; } static s64 __kpit_elapsed(struct kvm *kvm) { s64 elapsed; ktime_t remaining; struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state; if (!ps->pit_timer.period) return 0; /* * The Counter does not stop when it reaches zero. In * Modes 0, 1, 4, and 5 the Counter ``wraps around'' to * the highest count, either FFFF hex for binary counting * or 9999 for BCD counting, and continues counting. * Modes 2 and 3 are periodic; the Counter reloads * itself with the initial count and continues counting * from there. */ remaining = hrtimer_get_remaining(&ps->pit_timer.timer); elapsed = ps->pit_timer.period - ktime_to_ns(remaining); elapsed = mod_64(elapsed, ps->pit_timer.period); return elapsed; } static s64 kpit_elapsed(struct kvm *kvm, struct kvm_kpit_channel_state *c, int channel) { if (channel == 0) return __kpit_elapsed(kvm); return ktime_to_ns(ktime_sub(ktime_get(), c->count_load_time)); } static int pit_get_count(struct kvm *kvm, int channel) { struct kvm_kpit_channel_state *c = &kvm->arch.vpit->pit_state.channels[channel]; s64 d, t; int counter; WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock)); t = kpit_elapsed(kvm, c, channel); d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC); switch (c->mode) { case 0: case 1: case 4: case 5: counter = (c->count - d) & 0xffff; break; case 3: /* XXX: may be incorrect for odd counts */ counter = c->count - (mod_64((2 * d), c->count)); break; default: counter = c->count - mod_64(d, c->count); break; } return counter; } static int pit_get_out(struct kvm *kvm, int channel) { struct kvm_kpit_channel_state *c = &kvm->arch.vpit->pit_state.channels[channel]; s64 d, t; int out; WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock)); t = kpit_elapsed(kvm, c, channel); d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC); switch (c->mode) { default: case 0: out = (d >= c->count); break; case 1: out = (d < c->count); break; case 2: out = ((mod_64(d, c->count) == 0) && (d != 0)); break; case 3: out = (mod_64(d, c->count) < ((c->count + 1) >> 1)); break; case 4: case 5: out = (d == c->count); break; } return out; } static void pit_latch_count(struct kvm *kvm, int channel) { struct kvm_kpit_channel_state *c = &kvm->arch.vpit->pit_state.channels[channel]; WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock)); if (!c->count_latched) { c->latched_count = pit_get_count(kvm, channel); c->count_latched = c->rw_mode; } } static void pit_latch_status(struct kvm *kvm, int channel) { struct kvm_kpit_channel_state *c = &kvm->arch.vpit->pit_state.channels[channel]; WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock)); if (!c->status_latched) { /* TODO: Return NULL COUNT (bit 6). */ c->status = ((pit_get_out(kvm, channel) << 7) | (c->rw_mode << 4) | (c->mode << 1) | c->bcd); c->status_latched = 1; } } int pit_has_pending_timer(struct kvm_vcpu *vcpu) { struct kvm_pit *pit = vcpu->kvm->arch.vpit; if (pit && kvm_vcpu_is_bsp(vcpu) && pit->pit_state.irq_ack) return atomic_read(&pit->pit_state.pit_timer.pending); return 0; } static void kvm_pit_ack_irq(struct kvm_irq_ack_notifier *kian) { struct kvm_kpit_state *ps = container_of(kian, struct kvm_kpit_state, irq_ack_notifier); spin_lock(&ps->inject_lock); if (atomic_dec_return(&ps->pit_timer.pending) < 0) atomic_inc(&ps->pit_timer.pending); ps->irq_ack = 1; spin_unlock(&ps->inject_lock); } void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu) { struct kvm_pit *pit = vcpu->kvm->arch.vpit; struct hrtimer *timer; if (!kvm_vcpu_is_bsp(vcpu) || !pit) return; timer = &pit->pit_state.pit_timer.timer; if (hrtimer_cancel(timer)) hrtimer_start_expires(timer, HRTIMER_MODE_ABS); } static void destroy_pit_timer(struct kvm_timer *pt) { pr_debug("execute del timer!\n"); hrtimer_cancel(&pt->timer); } static bool kpit_is_periodic(struct kvm_timer *ktimer) { struct kvm_kpit_state *ps = container_of(ktimer, struct kvm_kpit_state, pit_timer); return ps->is_periodic; } static struct kvm_timer_ops kpit_ops = { .is_periodic = kpit_is_periodic, }; static void create_pit_timer(struct kvm_kpit_state *ps, u32 val, int is_period) { struct kvm_timer *pt = &ps->pit_timer; s64 interval; interval = muldiv64(val, NSEC_PER_SEC, KVM_PIT_FREQ); pr_debug("create pit timer, interval is %llu nsec\n", interval); /* TODO The new value only affected after the retriggered */ hrtimer_cancel(&pt->timer); pt->period = interval; ps->is_periodic = is_period; pt->timer.function = kvm_timer_fn; pt->t_ops = &kpit_ops; pt->kvm = ps->pit->kvm; pt->vcpu = pt->kvm->bsp_vcpu; atomic_set(&pt->pending, 0); ps->irq_ack = 1; hrtimer_start(&pt->timer, ktime_add_ns(ktime_get(), interval), HRTIMER_MODE_ABS); } static void pit_load_count(struct kvm *kvm, int channel, u32 val) { struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state; WARN_ON(!mutex_is_locked(&ps->lock)); pr_debug("load_count val is %d, channel is %d\n", val, channel); /* * The largest possible initial count is 0; this is equivalent * to 216 for binary counting and 104 for BCD counting. */ if (val == 0) val = 0x10000; ps->channels[channel].count = val; if (channel != 0) { ps->channels[channel].count_load_time = ktime_get(); return; } /* Two types of timer * mode 1 is one shot, mode 2 is period, otherwise del timer */ switch (ps->channels[0].mode) { case 0: case 1: /* FIXME: enhance mode 4 precision */ case 4: if (!(ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)) { create_pit_timer(ps, val, 0); } break; case 2: case 3: if (!(ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)){ create_pit_timer(ps, val, 1); } break; default: destroy_pit_timer(&ps->pit_timer); } } void kvm_pit_load_count(struct kvm *kvm, int channel, u32 val, int hpet_legacy_start) { u8 saved_mode; if (hpet_legacy_start) { /* save existing mode for later reenablement */ saved_mode = kvm->arch.vpit->pit_state.channels[0].mode; kvm->arch.vpit->pit_state.channels[0].mode = 0xff; /* disable timer */ pit_load_count(kvm, channel, val); kvm->arch.vpit->pit_state.channels[0].mode = saved_mode; } else { pit_load_count(kvm, channel, val); } } static inline struct kvm_pit *dev_to_pit(struct kvm_io_device *dev) { return container_of(dev, struct kvm_pit, dev); } static inline struct kvm_pit *speaker_to_pit(struct kvm_io_device *dev) { return container_of(dev, struct kvm_pit, speaker_dev); } static inline int pit_in_range(gpa_t addr) { return ((addr >= KVM_PIT_BASE_ADDRESS) && (addr < KVM_PIT_BASE_ADDRESS + KVM_PIT_MEM_LENGTH)); } static int pit_ioport_write(struct kvm_io_device *this, gpa_t addr, int len, const void *data) { struct kvm_pit *pit = dev_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; int channel, access; struct kvm_kpit_channel_state *s; u32 val = *(u32 *) data; if (!pit_in_range(addr)) return -EOPNOTSUPP; val &= 0xff; addr &= KVM_PIT_CHANNEL_MASK; mutex_lock(&pit_state->lock); if (val != 0) pr_debug("write addr is 0x%x, len is %d, val is 0x%x\n", (unsigned int)addr, len, val); if (addr == 3) { channel = val >> 6; if (channel == 3) { /* Read-Back Command. */ for (channel = 0; channel < 3; channel++) { s = &pit_state->channels[channel]; if (val & (2 << channel)) { if (!(val & 0x20)) pit_latch_count(kvm, channel); if (!(val & 0x10)) pit_latch_status(kvm, channel); } } } else { /* Select Counter <channel>. */ s = &pit_state->channels[channel]; access = (val >> 4) & KVM_PIT_CHANNEL_MASK; if (access == 0) { pit_latch_count(kvm, channel); } else { s->rw_mode = access; s->read_state = access; s->write_state = access; s->mode = (val >> 1) & 7; if (s->mode > 5) s->mode -= 4; s->bcd = val & 1; } } } else { /* Write Count. */ s = &pit_state->channels[addr]; switch (s->write_state) { default: case RW_STATE_LSB: pit_load_count(kvm, addr, val); break; case RW_STATE_MSB: pit_load_count(kvm, addr, val << 8); break; case RW_STATE_WORD0: s->write_latch = val; s->write_state = RW_STATE_WORD1; break; case RW_STATE_WORD1: pit_load_count(kvm, addr, s->write_latch | (val << 8)); s->write_state = RW_STATE_WORD0; break; } } mutex_unlock(&pit_state->lock); return 0; } static int pit_ioport_read(struct kvm_io_device *this, gpa_t addr, int len, void *data) { struct kvm_pit *pit = dev_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; int ret, count; struct kvm_kpit_channel_state *s; if (!pit_in_range(addr)) return -EOPNOTSUPP; addr &= KVM_PIT_CHANNEL_MASK; if (addr == 3) return 0; s = &pit_state->channels[addr]; mutex_lock(&pit_state->lock); if (s->status_latched) { s->status_latched = 0; ret = s->status; } else if (s->count_latched) { switch (s->count_latched) { default: case RW_STATE_LSB: ret = s->latched_count & 0xff; s->count_latched = 0; break; case RW_STATE_MSB: ret = s->latched_count >> 8; s->count_latched = 0; break; case RW_STATE_WORD0: ret = s->latched_count & 0xff; s->count_latched = RW_STATE_MSB; break; } } else { switch (s->read_state) { default: case RW_STATE_LSB: count = pit_get_count(kvm, addr); ret = count & 0xff; break; case RW_STATE_MSB: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; break; case RW_STATE_WORD0: count = pit_get_count(kvm, addr); ret = count & 0xff; s->read_state = RW_STATE_WORD1; break; case RW_STATE_WORD1: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; s->read_state = RW_STATE_WORD0; break; } } if (len > sizeof(ret)) len = sizeof(ret); memcpy(data, (char *)&ret, len); mutex_unlock(&pit_state->lock); return 0; } static int speaker_ioport_write(struct kvm_io_device *this, gpa_t addr, int len, const void *data) { struct kvm_pit *pit = speaker_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; u32 val = *(u32 *) data; if (addr != KVM_SPEAKER_BASE_ADDRESS) return -EOPNOTSUPP; mutex_lock(&pit_state->lock); pit_state->speaker_data_on = (val >> 1) & 1; pit_set_gate(kvm, 2, val & 1); mutex_unlock(&pit_state->lock); return 0; } static int speaker_ioport_read(struct kvm_io_device *this, gpa_t addr, int len, void *data) { struct kvm_pit *pit = speaker_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; unsigned int refresh_clock; int ret; if (addr != KVM_SPEAKER_BASE_ADDRESS) return -EOPNOTSUPP; /* Refresh clock toggles at about 15us. We approximate as 2^14ns. */ refresh_clock = ((unsigned int)ktime_to_ns(ktime_get()) >> 14) & 1; mutex_lock(&pit_state->lock); ret = ((pit_state->speaker_data_on << 1) | pit_get_gate(kvm, 2) | (pit_get_out(kvm, 2) << 5) | (refresh_clock << 4)); if (len > sizeof(ret)) len = sizeof(ret); memcpy(data, (char *)&ret, len); mutex_unlock(&pit_state->lock); return 0; } void kvm_pit_reset(struct kvm_pit *pit) { int i; struct kvm_kpit_channel_state *c; mutex_lock(&pit->pit_state.lock); pit->pit_state.flags = 0; for (i = 0; i < 3; i++) { c = &pit->pit_state.channels[i]; c->mode = 0xff; c->gate = (i != 2); pit_load_count(pit->kvm, i, 0); } mutex_unlock(&pit->pit_state.lock); atomic_set(&pit->pit_state.pit_timer.pending, 0); pit->pit_state.irq_ack = 1; } static void pit_mask_notifer(struct kvm_irq_mask_notifier *kimn, bool mask) { struct kvm_pit *pit = container_of(kimn, struct kvm_pit, mask_notifier); if (!mask) { atomic_set(&pit->pit_state.pit_timer.pending, 0); pit->pit_state.irq_ack = 1; } } static const struct kvm_io_device_ops pit_dev_ops = { .read = pit_ioport_read, .write = pit_ioport_write, }; static const struct kvm_io_device_ops speaker_dev_ops = { .read = speaker_ioport_read, .write = speaker_ioport_write, }; /* Caller must have writers lock on slots_lock */ struct kvm_pit *kvm_create_pit(struct kvm *kvm, u32 flags) { struct kvm_pit *pit; struct kvm_kpit_state *pit_state; int ret; pit = kzalloc(sizeof(struct kvm_pit), GFP_KERNEL); if (!pit) return NULL; pit->irq_source_id = kvm_request_irq_source_id(kvm); if (pit->irq_source_id < 0) { kfree(pit); return NULL; } mutex_init(&pit->pit_state.lock); mutex_lock(&pit->pit_state.lock); spin_lock_init(&pit->pit_state.inject_lock); kvm->arch.vpit = pit; pit->kvm = kvm; pit_state = &pit->pit_state; pit_state->pit = pit; hrtimer_init(&pit_state->pit_timer.timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS); pit_state->irq_ack_notifier.gsi = 0; pit_state->irq_ack_notifier.irq_acked = kvm_pit_ack_irq; kvm_register_irq_ack_notifier(kvm, &pit_state->irq_ack_notifier); pit_state->pit_timer.reinject = true; mutex_unlock(&pit->pit_state.lock); kvm_pit_reset(pit); pit->mask_notifier.func = pit_mask_notifer; kvm_register_irq_mask_notifier(kvm, 0, &pit->mask_notifier); kvm_iodevice_init(&pit->dev, &pit_dev_ops); ret = __kvm_io_bus_register_dev(&kvm->pio_bus, &pit->dev); if (ret < 0) goto fail; if (flags & KVM_PIT_SPEAKER_DUMMY) { kvm_iodevice_init(&pit->speaker_dev, &speaker_dev_ops); ret = __kvm_io_bus_register_dev(&kvm->pio_bus, &pit->speaker_dev); if (ret < 0) goto fail_unregister; } return pit; fail_unregister: __kvm_io_bus_unregister_dev(&kvm->pio_bus, &pit->dev); fail: if (pit->irq_source_id >= 0) kvm_free_irq_source_id(kvm, pit->irq_source_id); kfree(pit); return NULL; } void kvm_free_pit(struct kvm *kvm) { struct hrtimer *timer; if (kvm->arch.vpit) { kvm_unregister_irq_mask_notifier(kvm, 0, &kvm->arch.vpit->mask_notifier); kvm_unregister_irq_ack_notifier(kvm, &kvm->arch.vpit->pit_state.irq_ack_notifier); mutex_lock(&kvm->arch.vpit->pit_state.lock); timer = &kvm->arch.vpit->pit_state.pit_timer.timer; hrtimer_cancel(timer); kvm_free_irq_source_id(kvm, kvm->arch.vpit->irq_source_id); mutex_unlock(&kvm->arch.vpit->pit_state.lock); kfree(kvm->arch.vpit); } } static void __inject_pit_timer_intr(struct kvm *kvm) { struct kvm_vcpu *vcpu; int i; kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 1); kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 0); /* * Provides NMI watchdog support via Virtual Wire mode. * The route is: PIT -> PIC -> LVT0 in NMI mode. * * Note: Our Virtual Wire implementation is simplified, only * propagating PIT interrupts to all VCPUs when they have set * LVT0 to NMI delivery. Other PIC interrupts are just sent to * VCPU0, and only if its LVT0 is in EXTINT mode. */ if (kvm->arch.vapics_in_nmi_mode > 0) kvm_for_each_vcpu(i, vcpu, kvm) kvm_apic_nmi_wd_deliver(vcpu); } void kvm_inject_pit_timer_irqs(struct kvm_vcpu *vcpu) { struct kvm_pit *pit = vcpu->kvm->arch.vpit; struct kvm *kvm = vcpu->kvm; struct kvm_kpit_state *ps; if (pit) { int inject = 0; ps = &pit->pit_state; /* Try to inject pending interrupts when * last one has been acked. */ spin_lock(&ps->inject_lock); if (atomic_read(&ps->pit_timer.pending) && ps->irq_ack) { ps->irq_ack = 0; inject = 1; } spin_unlock(&ps->inject_lock); if (inject) __inject_pit_timer_intr(kvm); } }
./CrossVul/dataset_final_sorted/CWE-119/c/good_1579_0
crossvul-cpp_data_good_3314_0
/* * CCM: Counter with CBC-MAC * * (C) Copyright IBM Corp. 2007 - Joy Latten <latten@us.ibm.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/aead.h> #include <crypto/internal/hash.h> #include <crypto/internal/skcipher.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include "internal.h" struct ccm_instance_ctx { struct crypto_skcipher_spawn ctr; struct crypto_ahash_spawn mac; }; struct crypto_ccm_ctx { struct crypto_ahash *mac; struct crypto_skcipher *ctr; }; struct crypto_rfc4309_ctx { struct crypto_aead *child; u8 nonce[3]; }; struct crypto_rfc4309_req_ctx { struct scatterlist src[3]; struct scatterlist dst[3]; struct aead_request subreq; }; struct crypto_ccm_req_priv_ctx { u8 odata[16]; u8 idata[16]; u8 auth_tag[16]; u32 flags; struct scatterlist src[3]; struct scatterlist dst[3]; struct skcipher_request skreq; }; struct cbcmac_tfm_ctx { struct crypto_cipher *child; }; struct cbcmac_desc_ctx { unsigned int len; }; static inline struct crypto_ccm_req_priv_ctx *crypto_ccm_reqctx( struct aead_request *req) { unsigned long align = crypto_aead_alignmask(crypto_aead_reqtfm(req)); return (void *)PTR_ALIGN((u8 *)aead_request_ctx(req), align + 1); } static int set_msg_len(u8 *block, unsigned int msglen, int csize) { __be32 data; memset(block, 0, csize); block += csize; if (csize >= 4) csize = 4; else if (msglen > (1 << (8 * csize))) return -EOVERFLOW; data = cpu_to_be32(msglen); memcpy(block - csize, (u8 *)&data + 4 - csize, csize); return 0; } static int crypto_ccm_setkey(struct crypto_aead *aead, const u8 *key, unsigned int keylen) { struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); struct crypto_skcipher *ctr = ctx->ctr; struct crypto_ahash *mac = ctx->mac; int err = 0; crypto_skcipher_clear_flags(ctr, CRYPTO_TFM_REQ_MASK); crypto_skcipher_set_flags(ctr, crypto_aead_get_flags(aead) & CRYPTO_TFM_REQ_MASK); err = crypto_skcipher_setkey(ctr, key, keylen); crypto_aead_set_flags(aead, crypto_skcipher_get_flags(ctr) & CRYPTO_TFM_RES_MASK); if (err) goto out; crypto_ahash_clear_flags(mac, CRYPTO_TFM_REQ_MASK); crypto_ahash_set_flags(mac, crypto_aead_get_flags(aead) & CRYPTO_TFM_REQ_MASK); err = crypto_ahash_setkey(mac, key, keylen); crypto_aead_set_flags(aead, crypto_ahash_get_flags(mac) & CRYPTO_TFM_RES_MASK); out: return err; } static int crypto_ccm_setauthsize(struct crypto_aead *tfm, unsigned int authsize) { switch (authsize) { case 4: case 6: case 8: case 10: case 12: case 14: case 16: break; default: return -EINVAL; } return 0; } static int format_input(u8 *info, struct aead_request *req, unsigned int cryptlen) { struct crypto_aead *aead = crypto_aead_reqtfm(req); unsigned int lp = req->iv[0]; unsigned int l = lp + 1; unsigned int m; m = crypto_aead_authsize(aead); memcpy(info, req->iv, 16); /* format control info per RFC 3610 and * NIST Special Publication 800-38C */ *info |= (8 * ((m - 2) / 2)); if (req->assoclen) *info |= 64; return set_msg_len(info + 16 - l, cryptlen, l); } static int format_adata(u8 *adata, unsigned int a) { int len = 0; /* add control info for associated data * RFC 3610 and NIST Special Publication 800-38C */ if (a < 65280) { *(__be16 *)adata = cpu_to_be16(a); len = 2; } else { *(__be16 *)adata = cpu_to_be16(0xfffe); *(__be32 *)&adata[2] = cpu_to_be32(a); len = 6; } return len; } static int crypto_ccm_auth(struct aead_request *req, struct scatterlist *plain, unsigned int cryptlen) { struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); AHASH_REQUEST_ON_STACK(ahreq, ctx->mac); unsigned int assoclen = req->assoclen; struct scatterlist sg[3]; u8 *odata = pctx->odata; u8 *idata = pctx->idata; int ilen, err; /* format control data for input */ err = format_input(odata, req, cryptlen); if (err) goto out; sg_init_table(sg, 3); sg_set_buf(&sg[0], odata, 16); /* format associated data and compute into mac */ if (assoclen) { ilen = format_adata(idata, assoclen); sg_set_buf(&sg[1], idata, ilen); sg_chain(sg, 3, req->src); } else { ilen = 0; sg_chain(sg, 2, req->src); } ahash_request_set_tfm(ahreq, ctx->mac); ahash_request_set_callback(ahreq, pctx->flags, NULL, NULL); ahash_request_set_crypt(ahreq, sg, NULL, assoclen + ilen + 16); err = crypto_ahash_init(ahreq); if (err) goto out; err = crypto_ahash_update(ahreq); if (err) goto out; /* we need to pad the MAC input to a round multiple of the block size */ ilen = 16 - (assoclen + ilen) % 16; if (ilen < 16) { memset(idata, 0, ilen); sg_init_table(sg, 2); sg_set_buf(&sg[0], idata, ilen); if (plain) sg_chain(sg, 2, plain); plain = sg; cryptlen += ilen; } ahash_request_set_crypt(ahreq, plain, pctx->odata, cryptlen); err = crypto_ahash_finup(ahreq); out: return err; } static void crypto_ccm_encrypt_done(struct crypto_async_request *areq, int err) { struct aead_request *req = areq->data; struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); u8 *odata = pctx->odata; if (!err) scatterwalk_map_and_copy(odata, req->dst, req->assoclen + req->cryptlen, crypto_aead_authsize(aead), 1); aead_request_complete(req, err); } static inline int crypto_ccm_check_iv(const u8 *iv) { /* 2 <= L <= 8, so 1 <= L' <= 7. */ if (1 > iv[0] || iv[0] > 7) return -EINVAL; return 0; } static int crypto_ccm_init_crypt(struct aead_request *req, u8 *tag) { struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct scatterlist *sg; u8 *iv = req->iv; int err; err = crypto_ccm_check_iv(iv); if (err) return err; pctx->flags = aead_request_flags(req); /* Note: rfc 3610 and NIST 800-38C require counter of * zero to encrypt auth tag. */ memset(iv + 15 - iv[0], 0, iv[0] + 1); sg_init_table(pctx->src, 3); sg_set_buf(pctx->src, tag, 16); sg = scatterwalk_ffwd(pctx->src + 1, req->src, req->assoclen); if (sg != pctx->src + 1) sg_chain(pctx->src, 2, sg); if (req->src != req->dst) { sg_init_table(pctx->dst, 3); sg_set_buf(pctx->dst, tag, 16); sg = scatterwalk_ffwd(pctx->dst + 1, req->dst, req->assoclen); if (sg != pctx->dst + 1) sg_chain(pctx->dst, 2, sg); } return 0; } static int crypto_ccm_encrypt(struct aead_request *req) { struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct skcipher_request *skreq = &pctx->skreq; struct scatterlist *dst; unsigned int cryptlen = req->cryptlen; u8 *odata = pctx->odata; u8 *iv = req->iv; int err; err = crypto_ccm_init_crypt(req, odata); if (err) return err; err = crypto_ccm_auth(req, sg_next(pctx->src), cryptlen); if (err) return err; dst = pctx->src; if (req->src != req->dst) dst = pctx->dst; skcipher_request_set_tfm(skreq, ctx->ctr); skcipher_request_set_callback(skreq, pctx->flags, crypto_ccm_encrypt_done, req); skcipher_request_set_crypt(skreq, pctx->src, dst, cryptlen + 16, iv); err = crypto_skcipher_encrypt(skreq); if (err) return err; /* copy authtag to end of dst */ scatterwalk_map_and_copy(odata, sg_next(dst), cryptlen, crypto_aead_authsize(aead), 1); return err; } static void crypto_ccm_decrypt_done(struct crypto_async_request *areq, int err) { struct aead_request *req = areq->data; struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct crypto_aead *aead = crypto_aead_reqtfm(req); unsigned int authsize = crypto_aead_authsize(aead); unsigned int cryptlen = req->cryptlen - authsize; struct scatterlist *dst; pctx->flags = 0; dst = sg_next(req->src == req->dst ? pctx->src : pctx->dst); if (!err) { err = crypto_ccm_auth(req, dst, cryptlen); if (!err && crypto_memneq(pctx->auth_tag, pctx->odata, authsize)) err = -EBADMSG; } aead_request_complete(req, err); } static int crypto_ccm_decrypt(struct aead_request *req) { struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct skcipher_request *skreq = &pctx->skreq; struct scatterlist *dst; unsigned int authsize = crypto_aead_authsize(aead); unsigned int cryptlen = req->cryptlen; u8 *authtag = pctx->auth_tag; u8 *odata = pctx->odata; u8 *iv = req->iv; int err; cryptlen -= authsize; err = crypto_ccm_init_crypt(req, authtag); if (err) return err; scatterwalk_map_and_copy(authtag, sg_next(pctx->src), cryptlen, authsize, 0); dst = pctx->src; if (req->src != req->dst) dst = pctx->dst; skcipher_request_set_tfm(skreq, ctx->ctr); skcipher_request_set_callback(skreq, pctx->flags, crypto_ccm_decrypt_done, req); skcipher_request_set_crypt(skreq, pctx->src, dst, cryptlen + 16, iv); err = crypto_skcipher_decrypt(skreq); if (err) return err; err = crypto_ccm_auth(req, sg_next(dst), cryptlen); if (err) return err; /* verify */ if (crypto_memneq(authtag, odata, authsize)) return -EBADMSG; return err; } static int crypto_ccm_init_tfm(struct crypto_aead *tfm) { struct aead_instance *inst = aead_alg_instance(tfm); struct ccm_instance_ctx *ictx = aead_instance_ctx(inst); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(tfm); struct crypto_ahash *mac; struct crypto_skcipher *ctr; unsigned long align; int err; mac = crypto_spawn_ahash(&ictx->mac); if (IS_ERR(mac)) return PTR_ERR(mac); ctr = crypto_spawn_skcipher(&ictx->ctr); err = PTR_ERR(ctr); if (IS_ERR(ctr)) goto err_free_mac; ctx->mac = mac; ctx->ctr = ctr; align = crypto_aead_alignmask(tfm); align &= ~(crypto_tfm_ctx_alignment() - 1); crypto_aead_set_reqsize( tfm, align + sizeof(struct crypto_ccm_req_priv_ctx) + crypto_skcipher_reqsize(ctr)); return 0; err_free_mac: crypto_free_ahash(mac); return err; } static void crypto_ccm_exit_tfm(struct crypto_aead *tfm) { struct crypto_ccm_ctx *ctx = crypto_aead_ctx(tfm); crypto_free_ahash(ctx->mac); crypto_free_skcipher(ctx->ctr); } static void crypto_ccm_free(struct aead_instance *inst) { struct ccm_instance_ctx *ctx = aead_instance_ctx(inst); crypto_drop_ahash(&ctx->mac); crypto_drop_skcipher(&ctx->ctr); kfree(inst); } static int crypto_ccm_create_common(struct crypto_template *tmpl, struct rtattr **tb, const char *full_name, const char *ctr_name, const char *mac_name) { struct crypto_attr_type *algt; struct aead_instance *inst; struct skcipher_alg *ctr; struct crypto_alg *mac_alg; struct hash_alg_common *mac; struct ccm_instance_ctx *ictx; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return PTR_ERR(algt); if ((algt->type ^ CRYPTO_ALG_TYPE_AEAD) & algt->mask) return -EINVAL; mac_alg = crypto_find_alg(mac_name, &crypto_ahash_type, CRYPTO_ALG_TYPE_HASH, CRYPTO_ALG_TYPE_AHASH_MASK | CRYPTO_ALG_ASYNC); if (IS_ERR(mac_alg)) return PTR_ERR(mac_alg); mac = __crypto_hash_alg_common(mac_alg); err = -EINVAL; if (mac->digestsize != 16) goto out_put_mac; inst = kzalloc(sizeof(*inst) + sizeof(*ictx), GFP_KERNEL); err = -ENOMEM; if (!inst) goto out_put_mac; ictx = aead_instance_ctx(inst); err = crypto_init_ahash_spawn(&ictx->mac, mac, aead_crypto_instance(inst)); if (err) goto err_free_inst; crypto_set_skcipher_spawn(&ictx->ctr, aead_crypto_instance(inst)); err = crypto_grab_skcipher(&ictx->ctr, ctr_name, 0, crypto_requires_sync(algt->type, algt->mask)); if (err) goto err_drop_mac; ctr = crypto_spawn_skcipher_alg(&ictx->ctr); /* Not a stream cipher? */ err = -EINVAL; if (ctr->base.cra_blocksize != 1) goto err_drop_ctr; /* We want the real thing! */ if (crypto_skcipher_alg_ivsize(ctr) != 16) goto err_drop_ctr; err = -ENAMETOOLONG; if (snprintf(inst->alg.base.cra_driver_name, CRYPTO_MAX_ALG_NAME, "ccm_base(%s,%s)", ctr->base.cra_driver_name, mac->base.cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_ctr; memcpy(inst->alg.base.cra_name, full_name, CRYPTO_MAX_ALG_NAME); inst->alg.base.cra_flags = ctr->base.cra_flags & CRYPTO_ALG_ASYNC; inst->alg.base.cra_priority = (mac->base.cra_priority + ctr->base.cra_priority) / 2; inst->alg.base.cra_blocksize = 1; inst->alg.base.cra_alignmask = mac->base.cra_alignmask | ctr->base.cra_alignmask; inst->alg.ivsize = 16; inst->alg.chunksize = crypto_skcipher_alg_chunksize(ctr); inst->alg.maxauthsize = 16; inst->alg.base.cra_ctxsize = sizeof(struct crypto_ccm_ctx); inst->alg.init = crypto_ccm_init_tfm; inst->alg.exit = crypto_ccm_exit_tfm; inst->alg.setkey = crypto_ccm_setkey; inst->alg.setauthsize = crypto_ccm_setauthsize; inst->alg.encrypt = crypto_ccm_encrypt; inst->alg.decrypt = crypto_ccm_decrypt; inst->free = crypto_ccm_free; err = aead_register_instance(tmpl, inst); if (err) goto err_drop_ctr; out_put_mac: crypto_mod_put(mac_alg); return err; err_drop_ctr: crypto_drop_skcipher(&ictx->ctr); err_drop_mac: crypto_drop_ahash(&ictx->mac); err_free_inst: kfree(inst); goto out_put_mac; } static int crypto_ccm_create(struct crypto_template *tmpl, struct rtattr **tb) { const char *cipher_name; char ctr_name[CRYPTO_MAX_ALG_NAME]; char mac_name[CRYPTO_MAX_ALG_NAME]; char full_name[CRYPTO_MAX_ALG_NAME]; cipher_name = crypto_attr_alg_name(tb[1]); if (IS_ERR(cipher_name)) return PTR_ERR(cipher_name); if (snprintf(ctr_name, CRYPTO_MAX_ALG_NAME, "ctr(%s)", cipher_name) >= CRYPTO_MAX_ALG_NAME) return -ENAMETOOLONG; if (snprintf(mac_name, CRYPTO_MAX_ALG_NAME, "cbcmac(%s)", cipher_name) >= CRYPTO_MAX_ALG_NAME) return -ENAMETOOLONG; if (snprintf(full_name, CRYPTO_MAX_ALG_NAME, "ccm(%s)", cipher_name) >= CRYPTO_MAX_ALG_NAME) return -ENAMETOOLONG; return crypto_ccm_create_common(tmpl, tb, full_name, ctr_name, mac_name); } static struct crypto_template crypto_ccm_tmpl = { .name = "ccm", .create = crypto_ccm_create, .module = THIS_MODULE, }; static int crypto_ccm_base_create(struct crypto_template *tmpl, struct rtattr **tb) { const char *ctr_name; const char *cipher_name; char full_name[CRYPTO_MAX_ALG_NAME]; ctr_name = crypto_attr_alg_name(tb[1]); if (IS_ERR(ctr_name)) return PTR_ERR(ctr_name); cipher_name = crypto_attr_alg_name(tb[2]); if (IS_ERR(cipher_name)) return PTR_ERR(cipher_name); if (snprintf(full_name, CRYPTO_MAX_ALG_NAME, "ccm_base(%s,%s)", ctr_name, cipher_name) >= CRYPTO_MAX_ALG_NAME) return -ENAMETOOLONG; return crypto_ccm_create_common(tmpl, tb, full_name, ctr_name, cipher_name); } static struct crypto_template crypto_ccm_base_tmpl = { .name = "ccm_base", .create = crypto_ccm_base_create, .module = THIS_MODULE, }; static int crypto_rfc4309_setkey(struct crypto_aead *parent, const u8 *key, unsigned int keylen) { struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(parent); struct crypto_aead *child = ctx->child; int err; if (keylen < 3) return -EINVAL; keylen -= 3; memcpy(ctx->nonce, key + keylen, 3); crypto_aead_clear_flags(child, CRYPTO_TFM_REQ_MASK); crypto_aead_set_flags(child, crypto_aead_get_flags(parent) & CRYPTO_TFM_REQ_MASK); err = crypto_aead_setkey(child, key, keylen); crypto_aead_set_flags(parent, crypto_aead_get_flags(child) & CRYPTO_TFM_RES_MASK); return err; } static int crypto_rfc4309_setauthsize(struct crypto_aead *parent, unsigned int authsize) { struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(parent); switch (authsize) { case 8: case 12: case 16: break; default: return -EINVAL; } return crypto_aead_setauthsize(ctx->child, authsize); } static struct aead_request *crypto_rfc4309_crypt(struct aead_request *req) { struct crypto_rfc4309_req_ctx *rctx = aead_request_ctx(req); struct aead_request *subreq = &rctx->subreq; struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(aead); struct crypto_aead *child = ctx->child; struct scatterlist *sg; u8 *iv = PTR_ALIGN((u8 *)(subreq + 1) + crypto_aead_reqsize(child), crypto_aead_alignmask(child) + 1); /* L' */ iv[0] = 3; memcpy(iv + 1, ctx->nonce, 3); memcpy(iv + 4, req->iv, 8); scatterwalk_map_and_copy(iv + 16, req->src, 0, req->assoclen - 8, 0); sg_init_table(rctx->src, 3); sg_set_buf(rctx->src, iv + 16, req->assoclen - 8); sg = scatterwalk_ffwd(rctx->src + 1, req->src, req->assoclen); if (sg != rctx->src + 1) sg_chain(rctx->src, 2, sg); if (req->src != req->dst) { sg_init_table(rctx->dst, 3); sg_set_buf(rctx->dst, iv + 16, req->assoclen - 8); sg = scatterwalk_ffwd(rctx->dst + 1, req->dst, req->assoclen); if (sg != rctx->dst + 1) sg_chain(rctx->dst, 2, sg); } aead_request_set_tfm(subreq, child); aead_request_set_callback(subreq, req->base.flags, req->base.complete, req->base.data); aead_request_set_crypt(subreq, rctx->src, req->src == req->dst ? rctx->src : rctx->dst, req->cryptlen, iv); aead_request_set_ad(subreq, req->assoclen - 8); return subreq; } static int crypto_rfc4309_encrypt(struct aead_request *req) { if (req->assoclen != 16 && req->assoclen != 20) return -EINVAL; req = crypto_rfc4309_crypt(req); return crypto_aead_encrypt(req); } static int crypto_rfc4309_decrypt(struct aead_request *req) { if (req->assoclen != 16 && req->assoclen != 20) return -EINVAL; req = crypto_rfc4309_crypt(req); return crypto_aead_decrypt(req); } static int crypto_rfc4309_init_tfm(struct crypto_aead *tfm) { struct aead_instance *inst = aead_alg_instance(tfm); struct crypto_aead_spawn *spawn = aead_instance_ctx(inst); struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(tfm); struct crypto_aead *aead; unsigned long align; aead = crypto_spawn_aead(spawn); if (IS_ERR(aead)) return PTR_ERR(aead); ctx->child = aead; align = crypto_aead_alignmask(aead); align &= ~(crypto_tfm_ctx_alignment() - 1); crypto_aead_set_reqsize( tfm, sizeof(struct crypto_rfc4309_req_ctx) + ALIGN(crypto_aead_reqsize(aead), crypto_tfm_ctx_alignment()) + align + 32); return 0; } static void crypto_rfc4309_exit_tfm(struct crypto_aead *tfm) { struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(tfm); crypto_free_aead(ctx->child); } static void crypto_rfc4309_free(struct aead_instance *inst) { crypto_drop_aead(aead_instance_ctx(inst)); kfree(inst); } static int crypto_rfc4309_create(struct crypto_template *tmpl, struct rtattr **tb) { struct crypto_attr_type *algt; struct aead_instance *inst; struct crypto_aead_spawn *spawn; struct aead_alg *alg; const char *ccm_name; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return PTR_ERR(algt); if ((algt->type ^ CRYPTO_ALG_TYPE_AEAD) & algt->mask) return -EINVAL; ccm_name = crypto_attr_alg_name(tb[1]); if (IS_ERR(ccm_name)) return PTR_ERR(ccm_name); inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL); if (!inst) return -ENOMEM; spawn = aead_instance_ctx(inst); crypto_set_aead_spawn(spawn, aead_crypto_instance(inst)); err = crypto_grab_aead(spawn, ccm_name, 0, crypto_requires_sync(algt->type, algt->mask)); if (err) goto out_free_inst; alg = crypto_spawn_aead_alg(spawn); err = -EINVAL; /* We only support 16-byte blocks. */ if (crypto_aead_alg_ivsize(alg) != 16) goto out_drop_alg; /* Not a stream cipher? */ if (alg->base.cra_blocksize != 1) goto out_drop_alg; err = -ENAMETOOLONG; if (snprintf(inst->alg.base.cra_name, CRYPTO_MAX_ALG_NAME, "rfc4309(%s)", alg->base.cra_name) >= CRYPTO_MAX_ALG_NAME || snprintf(inst->alg.base.cra_driver_name, CRYPTO_MAX_ALG_NAME, "rfc4309(%s)", alg->base.cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto out_drop_alg; inst->alg.base.cra_flags = alg->base.cra_flags & CRYPTO_ALG_ASYNC; inst->alg.base.cra_priority = alg->base.cra_priority; inst->alg.base.cra_blocksize = 1; inst->alg.base.cra_alignmask = alg->base.cra_alignmask; inst->alg.ivsize = 8; inst->alg.chunksize = crypto_aead_alg_chunksize(alg); inst->alg.maxauthsize = 16; inst->alg.base.cra_ctxsize = sizeof(struct crypto_rfc4309_ctx); inst->alg.init = crypto_rfc4309_init_tfm; inst->alg.exit = crypto_rfc4309_exit_tfm; inst->alg.setkey = crypto_rfc4309_setkey; inst->alg.setauthsize = crypto_rfc4309_setauthsize; inst->alg.encrypt = crypto_rfc4309_encrypt; inst->alg.decrypt = crypto_rfc4309_decrypt; inst->free = crypto_rfc4309_free; err = aead_register_instance(tmpl, inst); if (err) goto out_drop_alg; out: return err; out_drop_alg: crypto_drop_aead(spawn); out_free_inst: kfree(inst); goto out; } static struct crypto_template crypto_rfc4309_tmpl = { .name = "rfc4309", .create = crypto_rfc4309_create, .module = THIS_MODULE, }; static int crypto_cbcmac_digest_setkey(struct crypto_shash *parent, const u8 *inkey, unsigned int keylen) { struct cbcmac_tfm_ctx *ctx = crypto_shash_ctx(parent); return crypto_cipher_setkey(ctx->child, inkey, keylen); } static int crypto_cbcmac_digest_init(struct shash_desc *pdesc) { struct cbcmac_desc_ctx *ctx = shash_desc_ctx(pdesc); int bs = crypto_shash_digestsize(pdesc->tfm); u8 *dg = (u8 *)ctx + crypto_shash_descsize(pdesc->tfm) - bs; ctx->len = 0; memset(dg, 0, bs); return 0; } static int crypto_cbcmac_digest_update(struct shash_desc *pdesc, const u8 *p, unsigned int len) { struct crypto_shash *parent = pdesc->tfm; struct cbcmac_tfm_ctx *tctx = crypto_shash_ctx(parent); struct cbcmac_desc_ctx *ctx = shash_desc_ctx(pdesc); struct crypto_cipher *tfm = tctx->child; int bs = crypto_shash_digestsize(parent); u8 *dg = (u8 *)ctx + crypto_shash_descsize(parent) - bs; while (len > 0) { unsigned int l = min(len, bs - ctx->len); crypto_xor(dg + ctx->len, p, l); ctx->len +=l; len -= l; p += l; if (ctx->len == bs) { crypto_cipher_encrypt_one(tfm, dg, dg); ctx->len = 0; } } return 0; } static int crypto_cbcmac_digest_final(struct shash_desc *pdesc, u8 *out) { struct crypto_shash *parent = pdesc->tfm; struct cbcmac_tfm_ctx *tctx = crypto_shash_ctx(parent); struct cbcmac_desc_ctx *ctx = shash_desc_ctx(pdesc); struct crypto_cipher *tfm = tctx->child; int bs = crypto_shash_digestsize(parent); u8 *dg = (u8 *)ctx + crypto_shash_descsize(parent) - bs; if (ctx->len) crypto_cipher_encrypt_one(tfm, dg, dg); memcpy(out, dg, bs); return 0; } static int cbcmac_init_tfm(struct crypto_tfm *tfm) { struct crypto_cipher *cipher; struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_spawn *spawn = crypto_instance_ctx(inst); struct cbcmac_tfm_ctx *ctx = crypto_tfm_ctx(tfm); cipher = crypto_spawn_cipher(spawn); if (IS_ERR(cipher)) return PTR_ERR(cipher); ctx->child = cipher; return 0; }; static void cbcmac_exit_tfm(struct crypto_tfm *tfm) { struct cbcmac_tfm_ctx *ctx = crypto_tfm_ctx(tfm); crypto_free_cipher(ctx->child); } static int cbcmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; int err; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; alg = crypto_get_attr_alg(tb, CRYPTO_ALG_TYPE_CIPHER, CRYPTO_ALG_TYPE_MASK); if (IS_ERR(alg)) return PTR_ERR(alg); inst = shash_alloc_instance("cbcmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_spawn(shash_instance_ctx(inst), alg, shash_crypto_instance(inst), CRYPTO_ALG_TYPE_MASK); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = 1; inst->alg.digestsize = alg->cra_blocksize; inst->alg.descsize = ALIGN(sizeof(struct cbcmac_desc_ctx), alg->cra_alignmask + 1) + alg->cra_blocksize; inst->alg.base.cra_ctxsize = sizeof(struct cbcmac_tfm_ctx); inst->alg.base.cra_init = cbcmac_init_tfm; inst->alg.base.cra_exit = cbcmac_exit_tfm; inst->alg.init = crypto_cbcmac_digest_init; inst->alg.update = crypto_cbcmac_digest_update; inst->alg.final = crypto_cbcmac_digest_final; inst->alg.setkey = crypto_cbcmac_digest_setkey; err = shash_register_instance(tmpl, inst); out_free_inst: if (err) shash_free_instance(shash_crypto_instance(inst)); out_put_alg: crypto_mod_put(alg); return err; } static struct crypto_template crypto_cbcmac_tmpl = { .name = "cbcmac", .create = cbcmac_create, .free = shash_free_instance, .module = THIS_MODULE, }; static int __init crypto_ccm_module_init(void) { int err; err = crypto_register_template(&crypto_cbcmac_tmpl); if (err) goto out; err = crypto_register_template(&crypto_ccm_base_tmpl); if (err) goto out_undo_cbcmac; err = crypto_register_template(&crypto_ccm_tmpl); if (err) goto out_undo_base; err = crypto_register_template(&crypto_rfc4309_tmpl); if (err) goto out_undo_ccm; out: return err; out_undo_ccm: crypto_unregister_template(&crypto_ccm_tmpl); out_undo_base: crypto_unregister_template(&crypto_ccm_base_tmpl); out_undo_cbcmac: crypto_register_template(&crypto_cbcmac_tmpl); goto out; } static void __exit crypto_ccm_module_exit(void) { crypto_unregister_template(&crypto_rfc4309_tmpl); crypto_unregister_template(&crypto_ccm_tmpl); crypto_unregister_template(&crypto_ccm_base_tmpl); crypto_unregister_template(&crypto_cbcmac_tmpl); } module_init(crypto_ccm_module_init); module_exit(crypto_ccm_module_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Counter with CBC MAC"); MODULE_ALIAS_CRYPTO("ccm_base"); MODULE_ALIAS_CRYPTO("rfc4309"); MODULE_ALIAS_CRYPTO("ccm");
./CrossVul/dataset_final_sorted/CWE-119/c/good_3314_0