]> granicus.if.org Git - imagemagick/blob - coders/exr.c
Fix improper cast that could cause an overflow as demonstrated in #347.
[imagemagick] / coders / exr.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            EEEEE  X   X  RRRR                               %
7 %                            E       X X   R   R                              %
8 %                            EEE      X    RRRR                               %
9 %                            E       X X   R R                                %
10 %                            EEEEE  X   X  R  R                               %
11 %                                                                             %
12 %                                                                             %
13 %            Read/Write High Dynamic-Range (HDR) Image File Format            %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                                 April 2007                                  %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/blob.h"
44 #include "MagickCore/blob-private.h"
45 #include "MagickCore/cache.h"
46 #include "MagickCore/exception.h"
47 #include "MagickCore/exception-private.h"
48 #include "MagickCore/image.h"
49 #include "MagickCore/image-private.h"
50 #include "MagickCore/list.h"
51 #include "MagickCore/magick.h"
52 #include "MagickCore/memory_.h"
53 #include "MagickCore/option.h"
54 #include "MagickCore/pixel-accessor.h"
55 #include "MagickCore/property.h"
56 #include "MagickCore/quantum-private.h"
57 #include "MagickCore/static.h"
58 #include "MagickCore/string_.h"
59 #include "MagickCore/module.h"
60 #include "MagickCore/resource_.h"
61 #include "MagickCore/utility.h"
62 #if defined(MAGICKCORE_OPENEXR_DELEGATE)
63 #include <ImfCRgbaFile.h>
64 \f
65 /*
66   Typedef declaractions.
67 */
68 typedef struct _ExrWindow
69 {
70   int
71     max_x,
72     max_y,
73     min_x,
74     min_y;
75 } ExrWindow;
76
77 /*
78   Forward declarations.
79 */
80 static MagickBooleanType
81   WriteEXRImage(const ImageInfo *,Image *,ExceptionInfo *);
82 #endif
83 \f
84 /*
85 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
86 %                                                                             %
87 %                                                                             %
88 %                                                                             %
89 %   I s E X R                                                                 %
90 %                                                                             %
91 %                                                                             %
92 %                                                                             %
93 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
94 %
95 %  IsEXR() returns MagickTrue if the image format type, identified by the
96 %  magick string, is EXR.
97 %
98 %  The format of the IsEXR method is:
99 %
100 %      MagickBooleanType IsEXR(const unsigned char *magick,const size_t length)
101 %
102 %  A description of each parameter follows:
103 %
104 %    o magick: compare image format pattern against these bytes.
105 %
106 %    o length: Specifies the length of the magick string.
107 %
108 */
109 static MagickBooleanType IsEXR(const unsigned char *magick,const size_t length)
110 {
111   if (length < 4)
112     return(MagickFalse);
113   if (memcmp(magick,"\166\057\061\001",4) == 0)
114     return(MagickTrue);
115   return(MagickFalse);
116 }
117 \f
118 #if defined(MAGICKCORE_OPENEXR_DELEGATE)
119 /*
120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
121 %                                                                             %
122 %                                                                             %
123 %                                                                             %
124 %   R e a d E X R I m a g e                                                   %
125 %                                                                             %
126 %                                                                             %
127 %                                                                             %
128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
129 %
130 %  ReadEXRImage reads an image in the high dynamic-range (HDR) file format
131 %  developed by Industrial Light & Magic.  It allocates the memory necessary
132 %  for the new Image structure and returns a pointer to the new image.
133 %
134 %  The format of the ReadEXRImage method is:
135 %
136 %      Image *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception)
137 %
138 %  A description of each parameter follows:
139 %
140 %    o image_info: the image info.
141 %
142 %    o exception: return any errors or warnings in this structure.
143 %
144 */
145 static Image *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception)
146 {
147   ExrWindow
148     data_window,
149     display_window;
150
151   const ImfHeader
152     *hdr_info;
153
154   Image
155     *image;
156
157   ImageInfo
158     *read_info;
159
160   ImfInputFile
161     *file;
162
163   ImfRgba
164     *scanline;
165
166   MagickBooleanType
167     status;
168
169   register ssize_t
170     x;
171
172   register Quantum
173     *q;
174
175   ssize_t
176     columns,
177     y;
178
179   /*
180     Open image.
181   */
182   assert(image_info != (const ImageInfo *) NULL);
183   assert(image_info->signature == MagickCoreSignature);
184   if (image_info->debug != MagickFalse)
185     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
186       image_info->filename);
187   assert(exception != (ExceptionInfo *) NULL);
188   assert(exception->signature == MagickCoreSignature);
189   image=AcquireImage(image_info,exception);
190   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
191   if (status == MagickFalse)
192     {
193       image=DestroyImageList(image);
194       return((Image *) NULL);
195     }
196   read_info=CloneImageInfo(image_info);
197   if (IsPathAccessible(read_info->filename) == MagickFalse)
198     {
199       (void) AcquireUniqueFilename(read_info->filename);
200       (void) ImageToFile(image,read_info->filename,exception);
201     }
202   file=ImfOpenInputFile(read_info->filename);
203   if (file == (ImfInputFile *) NULL)
204     {
205       ThrowFileException(exception,BlobError,"UnableToOpenBlob",
206         ImfErrorMessage());
207       if (LocaleCompare(image_info->filename,read_info->filename) != 0)
208         (void) RelinquishUniqueFileResource(read_info->filename);
209       read_info=DestroyImageInfo(read_info);
210       return((Image *) NULL);
211     }
212   hdr_info=ImfInputHeader(file);
213   ImfHeaderDisplayWindow(hdr_info,&display_window.min_x,&display_window.min_y,
214     &display_window.max_x,&display_window.max_y);
215   image->columns=display_window.max_x-display_window.min_x+1UL;
216   image->rows=display_window.max_y-display_window.min_y+1UL;
217   image->alpha_trait=BlendPixelTrait;
218   SetImageColorspace(image,RGBColorspace,exception);
219   image->gamma=1.0;
220   if (image_info->ping != MagickFalse)
221     {
222       (void) ImfCloseInputFile(file);
223       if (LocaleCompare(image_info->filename,read_info->filename) != 0)
224         (void) RelinquishUniqueFileResource(read_info->filename);
225       read_info=DestroyImageInfo(read_info);
226       (void) CloseBlob(image);
227       return(GetFirstImageInList(image));
228     }
229   status=SetImageExtent(image,image->columns,image->rows,exception);
230   if (status == MagickFalse)
231     return(DestroyImageList(image));
232   ImfHeaderDataWindow(hdr_info,&data_window.min_x,&data_window.min_y,
233     &data_window.max_x,&data_window.max_y);
234   columns=(ssize_t) data_window.max_x-data_window.min_x+1UL;
235   if ((display_window.min_x > data_window.max_x) ||
236       (display_window.min_x+(int) image->columns <= data_window.min_x))
237     scanline=(ImfRgba *) NULL;
238   else
239     {
240       scanline=(ImfRgba *) AcquireQuantumMemory(columns,sizeof(*scanline));
241       if (scanline == (ImfRgba *) NULL)
242         {
243           (void) ImfCloseInputFile(file);
244           if (LocaleCompare(image_info->filename,read_info->filename) != 0)
245             (void) RelinquishUniqueFileResource(read_info->filename);
246           read_info=DestroyImageInfo(read_info);
247           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
248         }
249     }
250   for (y=0; y < (ssize_t) image->rows; y++)
251   {
252     int
253       yy;
254
255     q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
256     if (q == (Quantum *) NULL)
257       break;
258     yy=display_window.min_y+y;
259     if ((yy < data_window.min_y) || (yy > data_window.max_y) ||
260         (scanline == (ImfRgba *) NULL))
261     {
262       for (x=0; x < (ssize_t) image->columns; x++)
263       {
264         SetPixelViaPixelInfo(image,&image->background_color,q);
265         q+=GetPixelChannels(image);
266       }
267       continue;
268     }
269     ResetMagickMemory(scanline,0,columns*sizeof(*scanline));
270     ImfInputSetFrameBuffer(file,scanline-data_window.min_x-columns*yy,1,
271       columns);
272     ImfInputReadPixels(file,yy,yy);
273     for (x=0; x < (ssize_t) image->columns; x++)
274     {
275       int
276         xx;
277
278       xx=display_window.min_x+((int) x-data_window.min_x);
279       if ((xx < 0) || (display_window.min_x+(int) x > data_window.max_x))
280         SetPixelViaPixelInfo(image,&image->background_color,q);
281       else
282         {
283           SetPixelRed(image,ClampToQuantum((MagickRealType) QuantumRange*
284             ImfHalfToFloat(scanline[xx].r)),q);
285           SetPixelGreen(image,ClampToQuantum((MagickRealType) QuantumRange*
286             ImfHalfToFloat(scanline[xx].g)),q);
287           SetPixelBlue(image,ClampToQuantum((MagickRealType) QuantumRange*
288             ImfHalfToFloat(scanline[xx].b)),q);
289           SetPixelAlpha(image,ClampToQuantum((MagickRealType) QuantumRange*
290             ImfHalfToFloat(scanline[xx].a)),q);
291         }
292       q+=GetPixelChannels(image);
293     }
294     if (SyncAuthenticPixels(image,exception) == MagickFalse)
295       break;
296   }
297   scanline=(ImfRgba *) RelinquishMagickMemory(scanline);
298   (void) ImfCloseInputFile(file);
299   if (LocaleCompare(image_info->filename,read_info->filename) != 0)
300     (void) RelinquishUniqueFileResource(read_info->filename);
301   read_info=DestroyImageInfo(read_info);
302   (void) CloseBlob(image);
303   return(GetFirstImageInList(image));
304 }
305 #endif
306 \f
307 /*
308 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
309 %                                                                             %
310 %                                                                             %
311 %                                                                             %
312 %   R e g i s t e r E X R I m a g e                                           %
313 %                                                                             %
314 %                                                                             %
315 %                                                                             %
316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
317 %
318 %  RegisterEXRImage() adds properties for the EXR image format
319 %  to the list of supported formats.  The properties include the image format
320 %  tag, a method to read and/or write the format, whether the format
321 %  supports the saving of more than one frame to the same file or blob,
322 %  whether the format supports native in-memory I/O, and a brief
323 %  description of the format.
324 %
325 %  The format of the RegisterEXRImage method is:
326 %
327 %      size_t RegisterEXRImage(void)
328 %
329 */
330 ModuleExport size_t RegisterEXRImage(void)
331 {
332   MagickInfo
333     *entry;
334
335   entry=AcquireMagickInfo("EXR","EXR","High Dynamic-range (HDR)");
336 #if defined(MAGICKCORE_OPENEXR_DELEGATE)
337   entry->decoder=(DecodeImageHandler *) ReadEXRImage;
338   entry->encoder=(EncodeImageHandler *) WriteEXRImage;
339 #endif
340   entry->magick=(IsImageFormatHandler *) IsEXR;
341   entry->flags^=CoderAdjoinFlag;
342   entry->flags^=CoderBlobSupportFlag;
343   (void) RegisterMagickInfo(entry);
344   return(MagickImageCoderSignature);
345 }
346 \f
347 /*
348 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
349 %                                                                             %
350 %                                                                             %
351 %                                                                             %
352 %   U n r e g i s t e r E X R I m a g e                                       %
353 %                                                                             %
354 %                                                                             %
355 %                                                                             %
356 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
357 %
358 %  UnregisterEXRImage() removes format registrations made by the
359 %  EXR module from the list of supported formats.
360 %
361 %  The format of the UnregisterEXRImage method is:
362 %
363 %      UnregisterEXRImage(void)
364 %
365 */
366 ModuleExport void UnregisterEXRImage(void)
367 {
368   (void) UnregisterMagickInfo("EXR");
369 }
370 \f
371 #if defined(MAGICKCORE_OPENEXR_DELEGATE)
372 /*
373 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
374 %                                                                             %
375 %                                                                             %
376 %                                                                             %
377 %   W r i t e E X R I m a g e                                                 %
378 %                                                                             %
379 %                                                                             %
380 %                                                                             %
381 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
382 %
383 %  WriteEXRImage() writes an image to a file the in the high dynamic-range
384 %  (HDR) file format developed by Industrial Light & Magic.
385 %
386 %  The format of the WriteEXRImage method is:
387 %
388 %      MagickBooleanType WriteEXRImage(const ImageInfo *image_info,
389 %        Image *image,ExceptionInfo *exception)
390 %
391 %  A description of each parameter follows.
392 %
393 %    o image_info: the image info.
394 %
395 %    o image:  The image.
396 %
397 %    o exception: return any errors or warnings in this structure.
398 %
399 */
400 static MagickBooleanType WriteEXRImage(const ImageInfo *image_info,Image *image,
401   ExceptionInfo *exception)
402 {
403   const char
404     *sampling_factor,
405     *value;
406
407   ImageInfo
408     *write_info;
409
410   ImfHalf
411     half_quantum;
412
413   ImfHeader
414     *hdr_info;
415
416   ImfOutputFile
417     *file;
418
419   ImfRgba
420     *scanline;
421
422   int
423     channels,
424     compression,
425     factors[3];
426
427   MagickBooleanType
428     status;
429
430   register const Quantum
431     *p;
432
433   register ssize_t
434     x;
435
436   ssize_t
437     y;
438
439   /*
440     Open output image file.
441   */
442   assert(image_info != (const ImageInfo *) NULL);
443   assert(image_info->signature == MagickCoreSignature);
444   assert(image != (Image *) NULL);
445   assert(image->signature == MagickCoreSignature);
446   if (image->debug != MagickFalse)
447     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
448   assert(exception != (ExceptionInfo *) NULL);
449   assert(exception->signature == MagickCoreSignature);
450   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
451   if (status == MagickFalse)
452     return(status);
453   (void) SetImageColorspace(image,RGBColorspace,exception);
454   write_info=CloneImageInfo(image_info);
455   (void) AcquireUniqueFilename(write_info->filename);
456   hdr_info=ImfNewHeader();
457   ImfHeaderSetDataWindow(hdr_info,0,0,(int) image->columns-1,(int)
458     image->rows-1);
459   ImfHeaderSetDisplayWindow(hdr_info,0,0,(int) image->columns-1,(int)
460     image->rows-1);
461   compression=IMF_NO_COMPRESSION;
462   if (write_info->compression == ZipSCompression)
463     compression=IMF_ZIPS_COMPRESSION;
464   if (write_info->compression == ZipCompression)
465     compression=IMF_ZIP_COMPRESSION;
466   if (write_info->compression == PizCompression)
467     compression=IMF_PIZ_COMPRESSION;
468   if (write_info->compression == Pxr24Compression)
469     compression=IMF_PXR24_COMPRESSION;
470 #if defined(B44Compression)
471   if (write_info->compression == B44Compression)
472     compression=IMF_B44_COMPRESSION;
473 #endif
474 #if defined(B44ACompression)
475   if (write_info->compression == B44ACompression)
476     compression=IMF_B44A_COMPRESSION;
477 #endif
478   channels=0;
479   value=GetImageOption(image_info,"exr:color-type");
480   if (value != (const char *) NULL)
481     {
482       if (LocaleCompare(value,"RGB") == 0)
483         channels=IMF_WRITE_RGB;
484       else if (LocaleCompare(value,"RGBA") == 0)
485         channels=IMF_WRITE_RGBA;
486       else if (LocaleCompare(value,"YC") == 0)
487         channels=IMF_WRITE_YC;
488       else if (LocaleCompare(value,"YCA") == 0)
489         channels=IMF_WRITE_YCA;
490       else if (LocaleCompare(value,"Y") == 0)
491         channels=IMF_WRITE_Y;
492       else if (LocaleCompare(value,"YA") == 0)
493         channels=IMF_WRITE_YA;
494       else if (LocaleCompare(value,"R") == 0)
495         channels=IMF_WRITE_R;
496       else if (LocaleCompare(value,"G") == 0)
497         channels=IMF_WRITE_G;
498       else if (LocaleCompare(value,"B") == 0)
499         channels=IMF_WRITE_B;
500       else if (LocaleCompare(value,"A") == 0)
501         channels=IMF_WRITE_A;
502       else
503         (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
504           "ignoring invalid defined exr:color-type","=%s",value);
505    }
506   sampling_factor=(const char *) NULL;
507   factors[0]=0;
508   if (image_info->sampling_factor != (char *) NULL)
509     sampling_factor=image_info->sampling_factor;
510   if (sampling_factor != NULL)
511     {
512       /*
513         Sampling factors, valid values are 1x1 or 2x2.
514       */
515       if (sscanf(sampling_factor,"%d:%d:%d",factors,factors+1,factors+2) == 3)
516         {
517           if ((factors[0] == factors[1]) && (factors[1] == factors[2]))
518             factors[0]=1;
519           else
520             if ((factors[0] == (2*factors[1])) && (factors[2] == 0))
521               factors[0]=2;
522         }
523       else
524         if (sscanf(sampling_factor,"%dx%d",factors,factors+1) == 2)
525           {
526             if (factors[0] != factors[1])
527               factors[0]=0;
528           }
529       if ((factors[0] != 1) && (factors[0] != 2))
530         (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
531           "ignoring sampling-factor","=%s",sampling_factor);
532       else if (channels != 0)
533         {
534           /*
535             Cross check given color type and subsampling.
536           */
537           factors[1]=((channels == IMF_WRITE_YCA) ||
538             (channels == IMF_WRITE_YC)) ? 2 : 1;
539           if (factors[0] != factors[1])
540             (void) ThrowMagickException(exception,GetMagickModule(),
541               CoderWarning,"sampling-factor and color type mismatch","=%s",
542               sampling_factor);
543         }
544     }
545   if (channels == 0)
546     {
547       /*
548         If no color type given, select it now.
549       */
550       if (factors[0] == 2)
551         channels=image->alpha_trait != UndefinedPixelTrait ? IMF_WRITE_YCA :
552           IMF_WRITE_YC;
553       else
554         channels=image->alpha_trait != UndefinedPixelTrait ? IMF_WRITE_RGBA :
555           IMF_WRITE_RGB;
556     }
557   ImfHeaderSetCompression(hdr_info,compression);
558   ImfHeaderSetLineOrder(hdr_info,IMF_INCREASING_Y);
559   file=ImfOpenOutputFile(write_info->filename,hdr_info,channels);
560   ImfDeleteHeader(hdr_info);
561   if (file == (ImfOutputFile *) NULL)
562     {
563       (void) RelinquishUniqueFileResource(write_info->filename);
564       write_info=DestroyImageInfo(write_info);
565       ThrowFileException(exception,BlobError,"UnableToOpenBlob",
566         ImfErrorMessage());
567       return(MagickFalse);
568     }
569   scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline));
570   if (scanline == (ImfRgba *) NULL)
571     {
572       (void) ImfCloseOutputFile(file);
573       (void) RelinquishUniqueFileResource(write_info->filename);
574       write_info=DestroyImageInfo(write_info);
575       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
576     }
577   ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline));
578   for (y=0; y < (ssize_t) image->rows; y++)
579   {
580     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
581     if (p == (const Quantum *) NULL)
582       break;
583     for (x=0; x < (ssize_t) image->columns; x++)
584     {
585       ImfFloatToHalf(QuantumScale*GetPixelRed(image,p),&half_quantum);
586       scanline[x].r=half_quantum;
587       ImfFloatToHalf(QuantumScale*GetPixelGreen(image,p),&half_quantum);
588       scanline[x].g=half_quantum;
589       ImfFloatToHalf(QuantumScale*GetPixelBlue(image,p),&half_quantum);
590       scanline[x].b=half_quantum;
591       if (image->alpha_trait == UndefinedPixelTrait)
592         ImfFloatToHalf(1.0,&half_quantum);
593       else
594         ImfFloatToHalf(QuantumScale*GetPixelAlpha(image,p),&half_quantum);
595       scanline[x].a=half_quantum;
596       p+=GetPixelChannels(image);
597     }
598     ImfOutputSetFrameBuffer(file,scanline-(y*image->columns),1,image->columns);
599     ImfOutputWritePixels(file,1);
600   }
601   (void) ImfCloseOutputFile(file);
602   scanline=(ImfRgba *) RelinquishMagickMemory(scanline);
603   (void) FileToImage(image,write_info->filename,exception);
604   (void) RelinquishUniqueFileResource(write_info->filename);
605   write_info=DestroyImageInfo(write_info);
606   (void) CloseBlob(image);
607   return(MagickTrue);
608 }
609 #endif