1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2020 Marti Maria Saguer
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24 //---------------------------------------------------------------------------------
25 //
26 
27 #include "lcms2_internal.h"
28 
29 // Generic I/O, tag dictionary management, profile struct
30 
31 // IOhandlers are abstractions used by littleCMS to read from whatever file, stream,
32 // memory block or any storage. Each IOhandler provides implementations for read,
33 // write, seek and tell functions. LittleCMS code deals with IO across those objects.
34 // In this way, is easier to add support for new storage media.
35 
36 // NULL stream, for taking care of used space -------------------------------------
37 
38 // NULL IOhandler basically does nothing but keep track on how many bytes have been
39 // written. This is handy when creating profiles, where the file size is needed in the
40 // header. Then, whole profile is serialized across NULL IOhandler and a second pass
41 // writes the bytes to the pertinent IOhandler.
42 
43 typedef struct {
44     cmsUInt32Number Pointer;         // Points to current location
45 } FILENULL;
46 
47 static
NULLRead(cmsIOHANDLER * iohandler,void * Buffer,cmsUInt32Number size,cmsUInt32Number count)48 cmsUInt32Number NULLRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
49 {
50     FILENULL* ResData = (FILENULL*) iohandler ->stream;
51 
52     cmsUInt32Number len = size * count;
53     ResData -> Pointer += len;
54     return count;
55 
56     cmsUNUSED_PARAMETER(Buffer);
57 }
58 
59 static
NULLSeek(cmsIOHANDLER * iohandler,cmsUInt32Number offset)60 cmsBool  NULLSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
61 {
62     FILENULL* ResData = (FILENULL*) iohandler ->stream;
63 
64     ResData ->Pointer = offset;
65     return TRUE;
66 }
67 
68 static
NULLTell(cmsIOHANDLER * iohandler)69 cmsUInt32Number NULLTell(cmsIOHANDLER* iohandler)
70 {
71     FILENULL* ResData = (FILENULL*) iohandler ->stream;
72     return ResData -> Pointer;
73 }
74 
75 static
NULLWrite(cmsIOHANDLER * iohandler,cmsUInt32Number size,const void * Ptr)76 cmsBool  NULLWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void *Ptr)
77 {
78     FILENULL* ResData = (FILENULL*) iohandler ->stream;
79 
80     ResData ->Pointer += size;
81     if (ResData ->Pointer > iohandler->UsedSpace)
82         iohandler->UsedSpace = ResData ->Pointer;
83 
84     return TRUE;
85 
86     cmsUNUSED_PARAMETER(Ptr);
87 }
88 
89 static
NULLClose(cmsIOHANDLER * iohandler)90 cmsBool  NULLClose(cmsIOHANDLER* iohandler)
91 {
92     FILENULL* ResData = (FILENULL*) iohandler ->stream;
93 
94     _cmsFree(iohandler ->ContextID, ResData);
95     _cmsFree(iohandler ->ContextID, iohandler);
96     return TRUE;
97 }
98 
99 // The NULL IOhandler creator
cmsOpenIOhandlerFromNULL(cmsContext ContextID)100 cmsIOHANDLER*  CMSEXPORT cmsOpenIOhandlerFromNULL(cmsContext ContextID)
101 {
102     struct _cms_io_handler* iohandler = NULL;
103     FILENULL* fm = NULL;
104 
105     iohandler = (struct _cms_io_handler*) _cmsMallocZero(ContextID, sizeof(struct _cms_io_handler));
106     if (iohandler == NULL) return NULL;
107 
108     fm = (FILENULL*) _cmsMallocZero(ContextID, sizeof(FILENULL));
109     if (fm == NULL) goto Error;
110 
111     fm ->Pointer = 0;
112 
113     iohandler ->ContextID = ContextID;
114     iohandler ->stream  = (void*) fm;
115     iohandler ->UsedSpace = 0;
116     iohandler ->ReportedSize = 0;
117     iohandler ->PhysicalFile[0] = 0;
118 
119     iohandler ->Read    = NULLRead;
120     iohandler ->Seek    = NULLSeek;
121     iohandler ->Close   = NULLClose;
122     iohandler ->Tell    = NULLTell;
123     iohandler ->Write   = NULLWrite;
124 
125     return iohandler;
126 
127 Error:
128     if (iohandler) _cmsFree(ContextID, iohandler);
129     return NULL;
130 
131 }
132 
133 
134 // Memory-based stream --------------------------------------------------------------
135 
136 // Those functions implements an iohandler which takes a block of memory as storage medium.
137 
138 typedef struct {
139     cmsUInt8Number* Block;    // Points to allocated memory
140     cmsUInt32Number Size;     // Size of allocated memory
141     cmsUInt32Number Pointer;  // Points to current location
142     int FreeBlockOnClose;     // As title
143 
144 } FILEMEM;
145 
146 static
MemoryRead(struct _cms_io_handler * iohandler,void * Buffer,cmsUInt32Number size,cmsUInt32Number count)147 cmsUInt32Number MemoryRead(struct _cms_io_handler* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
148 {
149     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
150     cmsUInt8Number* Ptr;
151     cmsUInt32Number len = size * count;
152 
153     if (ResData -> Pointer + len > ResData -> Size){
154 
155         len = (ResData -> Size - ResData -> Pointer);
156         cmsSignalError(iohandler ->ContextID, cmsERROR_READ, "Read from memory error. Got %d bytes, block should be of %d bytes", len, count * size);
157         return 0;
158     }
159 
160     Ptr  = ResData -> Block;
161     Ptr += ResData -> Pointer;
162     memmove(Buffer, Ptr, len);
163     ResData -> Pointer += len;
164 
165     return count;
166 }
167 
168 // SEEK_CUR is assumed
169 static
MemorySeek(struct _cms_io_handler * iohandler,cmsUInt32Number offset)170 cmsBool  MemorySeek(struct _cms_io_handler* iohandler, cmsUInt32Number offset)
171 {
172     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
173 
174     if (offset > ResData ->Size) {
175         cmsSignalError(iohandler ->ContextID, cmsERROR_SEEK,  "Too few data; probably corrupted profile");
176         return FALSE;
177     }
178 
179     ResData ->Pointer = offset;
180     return TRUE;
181 }
182 
183 // Tell for memory
184 static
MemoryTell(struct _cms_io_handler * iohandler)185 cmsUInt32Number MemoryTell(struct _cms_io_handler* iohandler)
186 {
187     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
188 
189     if (ResData == NULL) return 0;
190     return ResData -> Pointer;
191 }
192 
193 
194 // Writes data to memory, also keeps used space for further reference.
195 static
MemoryWrite(struct _cms_io_handler * iohandler,cmsUInt32Number size,const void * Ptr)196 cmsBool MemoryWrite(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void *Ptr)
197 {
198     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
199 
200     if (ResData == NULL) return FALSE; // Housekeeping
201 
202     // Check for available space. Clip.
203     if (ResData->Pointer + size > ResData->Size) {
204         size = ResData ->Size - ResData->Pointer;
205     }
206 
207     if (size == 0) return TRUE;     // Write zero bytes is ok, but does nothing
208 
209     memmove(ResData ->Block + ResData ->Pointer, Ptr, size);
210     ResData ->Pointer += size;
211 
212     if (ResData ->Pointer > iohandler->UsedSpace)
213         iohandler->UsedSpace = ResData ->Pointer;
214 
215     return TRUE;
216 }
217 
218 
219 static
MemoryClose(struct _cms_io_handler * iohandler)220 cmsBool  MemoryClose(struct _cms_io_handler* iohandler)
221 {
222     FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
223 
224     if (ResData ->FreeBlockOnClose) {
225 
226         if (ResData ->Block) _cmsFree(iohandler ->ContextID, ResData ->Block);
227     }
228 
229     _cmsFree(iohandler ->ContextID, ResData);
230     _cmsFree(iohandler ->ContextID, iohandler);
231 
232     return TRUE;
233 }
234 
235 // Create a iohandler for memory block. AccessMode=='r' assumes the iohandler is going to read, and makes
236 // a copy of the memory block for letting user to free the memory after invoking open profile. In write
237 // mode ("w"), Buffer points to the begin of memory block to be written.
cmsOpenIOhandlerFromMem(cmsContext ContextID,void * Buffer,cmsUInt32Number size,const char * AccessMode)238 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromMem(cmsContext ContextID, void *Buffer, cmsUInt32Number size, const char* AccessMode)
239 {
240     cmsIOHANDLER* iohandler = NULL;
241     FILEMEM* fm = NULL;
242 
243     _cmsAssert(AccessMode != NULL);
244 
245     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
246     if (iohandler == NULL) return NULL;
247 
248     switch (*AccessMode) {
249 
250     case 'r':
251         fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
252         if (fm == NULL) goto Error;
253 
254         if (Buffer == NULL) {
255             cmsSignalError(ContextID, cmsERROR_READ, "Couldn't read profile from NULL pointer");
256             goto Error;
257         }
258 
259         fm ->Block = (cmsUInt8Number*) _cmsMalloc(ContextID, size);
260         if (fm ->Block == NULL) {
261 
262             _cmsFree(ContextID, fm);
263             _cmsFree(ContextID, iohandler);
264             cmsSignalError(ContextID, cmsERROR_READ, "Couldn't allocate %ld bytes for profile", (long) size);
265             return NULL;
266         }
267 
268 
269         memmove(fm->Block, Buffer, size);
270         fm ->FreeBlockOnClose = TRUE;
271         fm ->Size    = size;
272         fm ->Pointer = 0;
273         iohandler -> ReportedSize = size;
274         break;
275 
276     case 'w':
277         fm = (FILEMEM*) _cmsMallocZero(ContextID, sizeof(FILEMEM));
278         if (fm == NULL) goto Error;
279 
280         fm ->Block = (cmsUInt8Number*) Buffer;
281         fm ->FreeBlockOnClose = FALSE;
282         fm ->Size    = size;
283         fm ->Pointer = 0;
284         iohandler -> ReportedSize = 0;
285         break;
286 
287     default:
288         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown access mode '%c'", *AccessMode);
289         return NULL;
290     }
291 
292     iohandler ->ContextID = ContextID;
293     iohandler ->stream  = (void*) fm;
294     iohandler ->UsedSpace = 0;
295     iohandler ->PhysicalFile[0] = 0;
296 
297     iohandler ->Read    = MemoryRead;
298     iohandler ->Seek    = MemorySeek;
299     iohandler ->Close   = MemoryClose;
300     iohandler ->Tell    = MemoryTell;
301     iohandler ->Write   = MemoryWrite;
302 
303     return iohandler;
304 
305 Error:
306     if (fm) _cmsFree(ContextID, fm);
307     if (iohandler) _cmsFree(ContextID, iohandler);
308     return NULL;
309 }
310 
311 // File-based stream -------------------------------------------------------
312 
313 // Read count elements of size bytes each. Return number of elements read
314 static
FileRead(cmsIOHANDLER * iohandler,void * Buffer,cmsUInt32Number size,cmsUInt32Number count)315 cmsUInt32Number FileRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count)
316 {
317     cmsUInt32Number nReaded = (cmsUInt32Number) fread(Buffer, size, count, (FILE*) iohandler->stream);
318 
319     if (nReaded != count) {
320             cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Read error. Got %d bytes, block should be of %d bytes", nReaded * size, count * size);
321             return 0;
322     }
323 
324     return nReaded;
325 }
326 
327 // Position file pointer in the file
328 static
FileSeek(cmsIOHANDLER * iohandler,cmsUInt32Number offset)329 cmsBool  FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
330 {
331     if (fseek((FILE*) iohandler ->stream, (long) offset, SEEK_SET) != 0) {
332 
333        cmsSignalError(iohandler ->ContextID, cmsERROR_FILE, "Seek error; probably corrupted file");
334        return FALSE;
335     }
336 
337     return TRUE;
338 }
339 
340 // Returns file pointer position or 0 on error, which is also a valid position.
341 static
FileTell(cmsIOHANDLER * iohandler)342 cmsUInt32Number FileTell(cmsIOHANDLER* iohandler)
343 {
344     long t = ftell((FILE*)iohandler ->stream);
345     if (t == -1L) {
346         cmsSignalError(iohandler->ContextID, cmsERROR_FILE, "Tell error; probably corrupted file");
347         return 0;
348     }
349 
350     return (cmsUInt32Number)t;
351 }
352 
353 // Writes data to stream, also keeps used space for further reference. Returns TRUE on success, FALSE on error
354 static
FileWrite(cmsIOHANDLER * iohandler,cmsUInt32Number size,const void * Buffer)355 cmsBool  FileWrite(cmsIOHANDLER* iohandler, cmsUInt32Number size, const void* Buffer)
356 {
357     if (size == 0) return TRUE;  // We allow to write 0 bytes, but nothing is written
358 
359     iohandler->UsedSpace += size;
360     return (fwrite(Buffer, size, 1, (FILE*)iohandler->stream) == 1);
361 }
362 
363 // Closes the file
364 static
FileClose(cmsIOHANDLER * iohandler)365 cmsBool  FileClose(cmsIOHANDLER* iohandler)
366 {
367     if (fclose((FILE*) iohandler ->stream) != 0) return FALSE;
368     _cmsFree(iohandler ->ContextID, iohandler);
369     return TRUE;
370 }
371 
372 // Create a iohandler for disk based files.
cmsOpenIOhandlerFromFile(cmsContext ContextID,const char * FileName,const char * AccessMode)373 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const char* FileName, const char* AccessMode)
374 {
375     cmsIOHANDLER* iohandler = NULL;
376     FILE* fm = NULL;
377     cmsInt32Number fileLen;
378 
379     _cmsAssert(FileName != NULL);
380     _cmsAssert(AccessMode != NULL);
381 
382     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
383     if (iohandler == NULL) return NULL;
384 
385     switch (*AccessMode) {
386 
387     case 'r':
388         fm = fopen(FileName, "rb");
389         if (fm == NULL) {
390             _cmsFree(ContextID, iohandler);
391              cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
392             return NULL;
393         }
394         fileLen = cmsfilelength(fm);
395         if (fileLen < 0)
396         {
397             fclose(fm);
398             _cmsFree(ContextID, iohandler);
399             cmsSignalError(ContextID, cmsERROR_FILE, "Cannot get size of file '%s'", FileName);
400             return NULL;
401         }
402 
403         iohandler -> ReportedSize = (cmsUInt32Number) fileLen;
404         break;
405 
406     case 'w':
407         fm = fopen(FileName, "wb");
408         if (fm == NULL) {
409             _cmsFree(ContextID, iohandler);
410              cmsSignalError(ContextID, cmsERROR_FILE, "Couldn't create '%s'", FileName);
411             return NULL;
412         }
413         iohandler -> ReportedSize = 0;
414         break;
415 
416     default:
417         _cmsFree(ContextID, iohandler);
418          cmsSignalError(ContextID, cmsERROR_FILE, "Unknown access mode '%c'", *AccessMode);
419         return NULL;
420     }
421 
422     iohandler ->ContextID = ContextID;
423     iohandler ->stream = (void*) fm;
424     iohandler ->UsedSpace = 0;
425 
426     // Keep track of the original file
427     strncpy(iohandler -> PhysicalFile, FileName, sizeof(iohandler -> PhysicalFile)-1);
428     iohandler -> PhysicalFile[sizeof(iohandler -> PhysicalFile)-1] = 0;
429 
430     iohandler ->Read    = FileRead;
431     iohandler ->Seek    = FileSeek;
432     iohandler ->Close   = FileClose;
433     iohandler ->Tell    = FileTell;
434     iohandler ->Write   = FileWrite;
435 
436     return iohandler;
437 }
438 
439 // Create a iohandler for stream based files
cmsOpenIOhandlerFromStream(cmsContext ContextID,FILE * Stream)440 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream)
441 {
442     cmsIOHANDLER* iohandler = NULL;
443     cmsInt32Number fileSize;
444 
445     fileSize = cmsfilelength(Stream);
446     if (fileSize < 0)
447     {
448         cmsSignalError(ContextID, cmsERROR_FILE, "Cannot get size of stream");
449         return NULL;
450     }
451 
452     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
453     if (iohandler == NULL) return NULL;
454 
455     iohandler -> ContextID = ContextID;
456     iohandler -> stream = (void*) Stream;
457     iohandler -> UsedSpace = 0;
458     iohandler -> ReportedSize = (cmsUInt32Number) fileSize;
459     iohandler -> PhysicalFile[0] = 0;
460 
461     iohandler ->Read    = FileRead;
462     iohandler ->Seek    = FileSeek;
463     iohandler ->Close   = FileClose;
464     iohandler ->Tell    = FileTell;
465     iohandler ->Write   = FileWrite;
466 
467     return iohandler;
468 }
469 
470 
471 
472 // Close an open IO handler
cmsCloseIOhandler(cmsIOHANDLER * io)473 cmsBool CMSEXPORT cmsCloseIOhandler(cmsIOHANDLER* io)
474 {
475     return io -> Close(io);
476 }
477 
478 // -------------------------------------------------------------------------------------------------------
479 
cmsGetProfileIOhandler(cmsHPROFILE hProfile)480 cmsIOHANDLER* CMSEXPORT cmsGetProfileIOhandler(cmsHPROFILE hProfile)
481 {
482 	_cmsICCPROFILE* Icc = (_cmsICCPROFILE*)hProfile;
483 
484 	if (Icc == NULL) return NULL;
485 	return Icc->IOhandler;
486 }
487 
488 // Creates an empty structure holding all required parameters
cmsCreateProfilePlaceholder(cmsContext ContextID)489 cmsHPROFILE CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID)
490 {
491     time_t now = time(NULL);
492     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) _cmsMallocZero(ContextID, sizeof(_cmsICCPROFILE));
493     if (Icc == NULL) return NULL;
494 
495     Icc ->ContextID = ContextID;
496 
497     // Set it to empty
498     Icc -> TagCount   = 0;
499 
500     // Set default version
501     Icc ->Version =  0x02100000;
502 
503     // Set creation date/time
504     memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
505 
506     // Create a mutex if the user provided proper plugin. NULL otherwise
507     Icc ->UsrMutex = _cmsCreateMutex(ContextID);
508 
509     // Return the handle
510     return (cmsHPROFILE) Icc;
511 }
512 
cmsGetProfileContextID(cmsHPROFILE hProfile)513 cmsContext CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile)
514 {
515      _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
516 
517     if (Icc == NULL) return NULL;
518     return Icc -> ContextID;
519 }
520 
521 
522 // Return the number of tags
cmsGetTagCount(cmsHPROFILE hProfile)523 cmsInt32Number CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
524 {
525     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
526     if (Icc == NULL) return -1;
527 
528     return  (cmsInt32Number) Icc->TagCount;
529 }
530 
531 // Return the tag signature of a given tag number
cmsGetTagSignature(cmsHPROFILE hProfile,cmsUInt32Number n)532 cmsTagSignature CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n)
533 {
534     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
535 
536     if (n > Icc->TagCount) return (cmsTagSignature) 0;  // Mark as not available
537     if (n >= MAX_TABLE_TAG) return (cmsTagSignature) 0; // As double check
538 
539     return Icc ->TagNames[n];
540 }
541 
542 
543 static
SearchOneTag(_cmsICCPROFILE * Profile,cmsTagSignature sig)544 int SearchOneTag(_cmsICCPROFILE* Profile, cmsTagSignature sig)
545 {
546     int i;
547 
548     for (i=0; i < (int) Profile -> TagCount; i++) {
549 
550         if (sig == Profile -> TagNames[i])
551             return i;
552     }
553 
554     return -1;
555 }
556 
557 // Search for a specific tag in tag dictionary. Returns position or -1 if tag not found.
558 // If followlinks is turned on, then the position of the linked tag is returned
_cmsSearchTag(_cmsICCPROFILE * Icc,cmsTagSignature sig,cmsBool lFollowLinks)559 int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks)
560 {
561     int n;
562     cmsTagSignature LinkedSig;
563 
564     do {
565 
566         // Search for given tag in ICC profile directory
567         n = SearchOneTag(Icc, sig);
568         if (n < 0)
569             return -1;        // Not found
570 
571         if (!lFollowLinks)
572             return n;         // Found, don't follow links
573 
574         // Is this a linked tag?
575         LinkedSig = Icc ->TagLinked[n];
576 
577         // Yes, follow link
578         if (LinkedSig != (cmsTagSignature) 0) {
579             sig = LinkedSig;
580         }
581 
582     } while (LinkedSig != (cmsTagSignature) 0);
583 
584     return n;
585 }
586 
587 // Deletes a tag entry
588 
589 static
_cmsDeleteTagByPos(_cmsICCPROFILE * Icc,int i)590 void _cmsDeleteTagByPos(_cmsICCPROFILE* Icc, int i)
591 {
592     _cmsAssert(Icc != NULL);
593     _cmsAssert(i >= 0);
594 
595 
596     if (Icc -> TagPtrs[i] != NULL) {
597 
598         // Free previous version
599         if (Icc ->TagSaveAsRaw[i]) {
600             _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
601         }
602         else {
603             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
604 
605             if (TypeHandler != NULL) {
606 
607                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
608                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameter
609                 LocalTypeHandler.ICCVersion = Icc ->Version;
610                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
611                 Icc ->TagPtrs[i] = NULL;
612             }
613         }
614 
615     }
616 }
617 
618 
619 // Creates a new tag entry
620 static
_cmsNewTag(_cmsICCPROFILE * Icc,cmsTagSignature sig,int * NewPos)621 cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
622 {
623     int i;
624 
625     // Search for the tag
626     i = _cmsSearchTag(Icc, sig, FALSE);
627     if (i >= 0) {
628 
629         // Already exists? delete it
630         _cmsDeleteTagByPos(Icc, i);
631         *NewPos = i;
632     }
633     else  {
634 
635         // No, make a new one
636         if (Icc -> TagCount >= MAX_TABLE_TAG) {
637             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
638             return FALSE;
639         }
640 
641         *NewPos = (int) Icc ->TagCount;
642         Icc -> TagCount++;
643     }
644 
645     return TRUE;
646 }
647 
648 
649 // Check existence
cmsIsTag(cmsHPROFILE hProfile,cmsTagSignature sig)650 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
651 {
652        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
653        return _cmsSearchTag(Icc, sig, FALSE) >= 0;
654 }
655 
656 // Enforces that the profile version is per. spec.
657 // Operates on the big endian bytes from the profile.
658 // Called before converting to platform endianness.
659 // Byte 0 is BCD major version, so max 9.
660 // Byte 1 is 2 BCD digits, one per nibble.
661 // Reserved bytes 2 & 3 must be 0.
662 static
_validatedVersion(cmsUInt32Number DWord)663 cmsUInt32Number _validatedVersion(cmsUInt32Number DWord)
664 {
665     cmsUInt8Number* pByte = (cmsUInt8Number*) &DWord;
666     cmsUInt8Number temp1;
667     cmsUInt8Number temp2;
668 
669     if (*pByte > 0x09) *pByte = (cmsUInt8Number) 0x09;
670     temp1 = (cmsUInt8Number) (*(pByte+1) & 0xf0);
671     temp2 = (cmsUInt8Number) (*(pByte+1) & 0x0f);
672     if (temp1 > 0x90U) temp1 = 0x90U;
673     if (temp2 > 0x09U) temp2 = 0x09U;
674     *(pByte+1) = (cmsUInt8Number)(temp1 | temp2);
675     *(pByte+2) = (cmsUInt8Number)0;
676     *(pByte+3) = (cmsUInt8Number)0;
677 
678     return DWord;
679 }
680 
681 // Read profile header and validate it
_cmsReadHeader(_cmsICCPROFILE * Icc)682 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
683 {
684     cmsTagEntry Tag;
685     cmsICCHeader Header;
686     cmsUInt32Number i, j;
687     cmsUInt32Number HeaderSize;
688     cmsIOHANDLER* io = Icc ->IOhandler;
689     cmsUInt32Number TagCount;
690 
691 
692     // Read the header
693     if (io -> Read(io, &Header, sizeof(cmsICCHeader), 1) != 1) {
694         return FALSE;
695     }
696 
697     // Validate file as an ICC profile
698     if (_cmsAdjustEndianess32(Header.magic) != cmsMagicNumber) {
699         cmsSignalError(Icc ->ContextID, cmsERROR_BAD_SIGNATURE, "not an ICC profile, invalid signature");
700         return FALSE;
701     }
702 
703     // Adjust endianness of the used parameters
704     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
705     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
706     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
707 
708     Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
709     Icc -> flags           = _cmsAdjustEndianess32(Header.flags);
710     Icc -> manufacturer    = _cmsAdjustEndianess32(Header.manufacturer);
711     Icc -> model           = _cmsAdjustEndianess32(Header.model);
712     Icc -> creator         = _cmsAdjustEndianess32(Header.creator);
713 
714     _cmsAdjustEndianess64(&Icc -> attributes, &Header.attributes);
715     Icc -> Version         = _cmsAdjustEndianess32(_validatedVersion(Header.version));
716 
717     // Get size as reported in header
718     HeaderSize = _cmsAdjustEndianess32(Header.size);
719 
720     // Make sure HeaderSize is lower than profile size
721     if (HeaderSize >= Icc ->IOhandler ->ReportedSize)
722             HeaderSize = Icc ->IOhandler ->ReportedSize;
723 
724 
725     // Get creation date/time
726     _cmsDecodeDateTimeNumber(&Header.date, &Icc ->Created);
727 
728     // The profile ID are 32 raw bytes
729     memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
730 
731 
732     // Read tag directory
733     if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;
734     if (TagCount > MAX_TABLE_TAG) {
735 
736         cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", TagCount);
737         return FALSE;
738     }
739 
740 
741     // Read tag directory
742     Icc -> TagCount = 0;
743     for (i=0; i < TagCount; i++) {
744 
745         if (!_cmsReadUInt32Number(io, (cmsUInt32Number *) &Tag.sig)) return FALSE;
746         if (!_cmsReadUInt32Number(io, &Tag.offset)) return FALSE;
747         if (!_cmsReadUInt32Number(io, &Tag.size)) return FALSE;
748 
749         // Perform some sanity check. Offset + size should fall inside file.
750         if (Tag.offset + Tag.size > HeaderSize ||
751             Tag.offset + Tag.size < Tag.offset)
752                   continue;
753 
754         Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
755         Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
756         Icc -> TagSizes[Icc ->TagCount]   = Tag.size;
757 
758        // Search for links
759         for (j=0; j < Icc ->TagCount; j++) {
760 
761             if ((Icc ->TagOffsets[j] == Tag.offset) &&
762                 (Icc ->TagSizes[j]   == Tag.size)) {
763 
764                 Icc ->TagLinked[Icc ->TagCount] = Icc ->TagNames[j];
765             }
766 
767         }
768 
769         Icc ->TagCount++;
770     }
771 
772     return TRUE;
773 }
774 
775 // Saves profile header
_cmsWriteHeader(_cmsICCPROFILE * Icc,cmsUInt32Number UsedSpace)776 cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
777 {
778     cmsICCHeader Header;
779     cmsUInt32Number i;
780     cmsTagEntry Tag;
781     cmsUInt32Number Count;
782 
783     Header.size        = _cmsAdjustEndianess32(UsedSpace);
784     Header.cmmId       = _cmsAdjustEndianess32(lcmsSignature);
785     Header.version     = _cmsAdjustEndianess32(Icc ->Version);
786 
787     Header.deviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Icc -> DeviceClass);
788     Header.colorSpace  = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> ColorSpace);
789     Header.pcs         = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> PCS);
790 
791     //   NOTE: in v4 Timestamp must be in UTC rather than in local time
792     _cmsEncodeDateTimeNumber(&Header.date, &Icc ->Created);
793 
794     Header.magic       = _cmsAdjustEndianess32(cmsMagicNumber);
795 
796 #ifdef CMS_IS_WINDOWS_
797     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMicrosoft);
798 #else
799     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMacintosh);
800 #endif
801 
802     Header.flags        = _cmsAdjustEndianess32(Icc -> flags);
803     Header.manufacturer = _cmsAdjustEndianess32(Icc -> manufacturer);
804     Header.model        = _cmsAdjustEndianess32(Icc -> model);
805 
806     _cmsAdjustEndianess64(&Header.attributes, &Icc -> attributes);
807 
808     // Rendering intent in the header (for embedded profiles)
809     Header.renderingIntent = _cmsAdjustEndianess32(Icc -> RenderingIntent);
810 
811     // Illuminant is always D50
812     Header.illuminant.X = (cmsS15Fixed16Number) _cmsAdjustEndianess32((cmsUInt32Number) _cmsDoubleTo15Fixed16(cmsD50_XYZ()->X));
813     Header.illuminant.Y = (cmsS15Fixed16Number) _cmsAdjustEndianess32((cmsUInt32Number) _cmsDoubleTo15Fixed16(cmsD50_XYZ()->Y));
814     Header.illuminant.Z = (cmsS15Fixed16Number) _cmsAdjustEndianess32((cmsUInt32Number) _cmsDoubleTo15Fixed16(cmsD50_XYZ()->Z));
815 
816     // Created by LittleCMS (that's me!)
817     Header.creator      = _cmsAdjustEndianess32(lcmsSignature);
818 
819     memset(&Header.reserved, 0, sizeof(Header.reserved));
820 
821     // Set profile ID. Endianness is always big endian
822     memmove(&Header.profileID, &Icc ->ProfileID, 16);
823 
824     // Dump the header
825     if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
826 
827     // Saves Tag directory
828 
829     // Get true count
830     Count = 0;
831     for (i=0;  i < Icc -> TagCount; i++) {
832         if (Icc ->TagNames[i] != (cmsTagSignature) 0)
833             Count++;
834     }
835 
836     // Store number of tags
837     if (!_cmsWriteUInt32Number(Icc ->IOhandler, Count)) return FALSE;
838 
839     for (i=0; i < Icc -> TagCount; i++) {
840 
841         if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;   // It is just a placeholder
842 
843         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsUInt32Number) Icc -> TagNames[i]);
844         Tag.offset = _cmsAdjustEndianess32((cmsUInt32Number) Icc -> TagOffsets[i]);
845         Tag.size   = _cmsAdjustEndianess32((cmsUInt32Number) Icc -> TagSizes[i]);
846 
847         if (!Icc ->IOhandler -> Write(Icc-> IOhandler, sizeof(cmsTagEntry), &Tag)) return FALSE;
848     }
849 
850     return TRUE;
851 }
852 
853 // ----------------------------------------------------------------------- Set/Get several struct members
854 
855 
cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)856 cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)
857 {
858     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
859     return Icc -> RenderingIntent;
860 }
861 
cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile,cmsUInt32Number RenderingIntent)862 void CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent)
863 {
864     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
865     Icc -> RenderingIntent = RenderingIntent;
866 }
867 
cmsGetHeaderFlags(cmsHPROFILE hProfile)868 cmsUInt32Number CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile)
869 {
870     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
871     return (cmsUInt32Number) Icc -> flags;
872 }
873 
cmsSetHeaderFlags(cmsHPROFILE hProfile,cmsUInt32Number Flags)874 void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
875 {
876     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
877     Icc -> flags = (cmsUInt32Number) Flags;
878 }
879 
cmsGetHeaderManufacturer(cmsHPROFILE hProfile)880 cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
881 {
882     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
883     return Icc ->manufacturer;
884 }
885 
cmsSetHeaderManufacturer(cmsHPROFILE hProfile,cmsUInt32Number manufacturer)886 void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
887 {
888     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
889     Icc -> manufacturer = manufacturer;
890 }
891 
cmsGetHeaderCreator(cmsHPROFILE hProfile)892 cmsUInt32Number CMSEXPORT cmsGetHeaderCreator(cmsHPROFILE hProfile)
893 {
894     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
895     return Icc ->creator;
896 }
897 
cmsGetHeaderModel(cmsHPROFILE hProfile)898 cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
899 {
900     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
901     return Icc ->model;
902 }
903 
cmsSetHeaderModel(cmsHPROFILE hProfile,cmsUInt32Number model)904 void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
905 {
906     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
907     Icc -> model = model;
908 }
909 
cmsGetHeaderAttributes(cmsHPROFILE hProfile,cmsUInt64Number * Flags)910 void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
911 {
912     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
913     memmove(Flags, &Icc -> attributes, sizeof(cmsUInt64Number));
914 }
915 
cmsSetHeaderAttributes(cmsHPROFILE hProfile,cmsUInt64Number Flags)916 void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags)
917 {
918     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
919     memmove(&Icc -> attributes, &Flags, sizeof(cmsUInt64Number));
920 }
921 
cmsGetHeaderProfileID(cmsHPROFILE hProfile,cmsUInt8Number * ProfileID)922 void CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
923 {
924     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
925     memmove(ProfileID, Icc ->ProfileID.ID8, 16);
926 }
927 
cmsSetHeaderProfileID(cmsHPROFILE hProfile,cmsUInt8Number * ProfileID)928 void CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
929 {
930     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
931     memmove(&Icc -> ProfileID, ProfileID, 16);
932 }
933 
cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile,struct tm * Dest)934 cmsBool  CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest)
935 {
936     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
937     memmove(Dest, &Icc ->Created, sizeof(struct tm));
938     return TRUE;
939 }
940 
cmsGetPCS(cmsHPROFILE hProfile)941 cmsColorSpaceSignature CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
942 {
943     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
944     return Icc -> PCS;
945 }
946 
cmsSetPCS(cmsHPROFILE hProfile,cmsColorSpaceSignature pcs)947 void CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs)
948 {
949     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
950     Icc -> PCS = pcs;
951 }
952 
cmsGetColorSpace(cmsHPROFILE hProfile)953 cmsColorSpaceSignature CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
954 {
955     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
956     return Icc -> ColorSpace;
957 }
958 
cmsSetColorSpace(cmsHPROFILE hProfile,cmsColorSpaceSignature sig)959 void CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig)
960 {
961     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
962     Icc -> ColorSpace = sig;
963 }
964 
cmsGetDeviceClass(cmsHPROFILE hProfile)965 cmsProfileClassSignature CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
966 {
967     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
968     return Icc -> DeviceClass;
969 }
970 
cmsSetDeviceClass(cmsHPROFILE hProfile,cmsProfileClassSignature sig)971 void CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig)
972 {
973     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
974     Icc -> DeviceClass = sig;
975 }
976 
cmsGetEncodedICCversion(cmsHPROFILE hProfile)977 cmsUInt32Number CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile)
978 {
979     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
980     return Icc -> Version;
981 }
982 
cmsSetEncodedICCversion(cmsHPROFILE hProfile,cmsUInt32Number Version)983 void CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version)
984 {
985     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
986     Icc -> Version = Version;
987 }
988 
989 // Get an hexadecimal number with same digits as v
990 static
BaseToBase(cmsUInt32Number in,int BaseIn,int BaseOut)991 cmsUInt32Number BaseToBase(cmsUInt32Number in, int BaseIn, int BaseOut)
992 {
993     char Buff[100];
994     int i, len;
995     cmsUInt32Number out;
996 
997     for (len=0; in > 0 && len < 100; len++) {
998 
999         Buff[len] = (char) (in % BaseIn);
1000         in /= BaseIn;
1001     }
1002 
1003     for (i=len-1, out=0; i >= 0; --i) {
1004         out = out * BaseOut + Buff[i];
1005     }
1006 
1007     return out;
1008 }
1009 
cmsSetProfileVersion(cmsHPROFILE hProfile,cmsFloat64Number Version)1010 void  CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version)
1011 {
1012     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1013 
1014     // 4.2 -> 0x4200000
1015 
1016     Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0 + 0.5), 10, 16) << 16;
1017 }
1018 
cmsGetProfileVersion(cmsHPROFILE hProfile)1019 cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
1020 {
1021     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1022     cmsUInt32Number n = Icc -> Version >> 16;
1023 
1024     return BaseToBase(n, 16, 10) / 100.0;
1025 }
1026 // --------------------------------------------------------------------------------------------------------------
1027 
1028 
1029 // Create profile from IOhandler
cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID,cmsIOHANDLER * io)1030 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io)
1031 {
1032     _cmsICCPROFILE* NewIcc;
1033     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1034 
1035     if (hEmpty == NULL) return NULL;
1036 
1037     NewIcc = (_cmsICCPROFILE*) hEmpty;
1038 
1039     NewIcc ->IOhandler = io;
1040     if (!_cmsReadHeader(NewIcc)) goto Error;
1041     return hEmpty;
1042 
1043 Error:
1044     cmsCloseProfile(hEmpty);
1045     return NULL;
1046 }
1047 
1048 // Create profile from IOhandler
cmsOpenProfileFromIOhandler2THR(cmsContext ContextID,cmsIOHANDLER * io,cmsBool write)1049 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandler2THR(cmsContext ContextID, cmsIOHANDLER* io, cmsBool write)
1050 {
1051     _cmsICCPROFILE* NewIcc;
1052     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1053 
1054     if (hEmpty == NULL) return NULL;
1055 
1056     NewIcc = (_cmsICCPROFILE*) hEmpty;
1057 
1058     NewIcc ->IOhandler = io;
1059     if (write) {
1060 
1061         NewIcc -> IsWrite = TRUE;
1062         return hEmpty;
1063     }
1064 
1065     if (!_cmsReadHeader(NewIcc)) goto Error;
1066     return hEmpty;
1067 
1068 Error:
1069     cmsCloseProfile(hEmpty);
1070     return NULL;
1071 }
1072 
1073 
1074 // Create profile from disk file
cmsOpenProfileFromFileTHR(cmsContext ContextID,const char * lpFileName,const char * sAccess)1075 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, const char *sAccess)
1076 {
1077     _cmsICCPROFILE* NewIcc;
1078     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1079 
1080     if (hEmpty == NULL) return NULL;
1081 
1082     NewIcc = (_cmsICCPROFILE*) hEmpty;
1083 
1084     NewIcc ->IOhandler = cmsOpenIOhandlerFromFile(ContextID, lpFileName, sAccess);
1085     if (NewIcc ->IOhandler == NULL) goto Error;
1086 
1087     if (*sAccess == 'W' || *sAccess == 'w') {
1088 
1089         NewIcc -> IsWrite = TRUE;
1090 
1091         return hEmpty;
1092     }
1093 
1094     if (!_cmsReadHeader(NewIcc)) goto Error;
1095     return hEmpty;
1096 
1097 Error:
1098     cmsCloseProfile(hEmpty);
1099     return NULL;
1100 }
1101 
1102 
cmsOpenProfileFromFile(const char * ICCProfile,const char * sAccess)1103 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess)
1104 {
1105     return cmsOpenProfileFromFileTHR(NULL, ICCProfile, sAccess);
1106 }
1107 
1108 
cmsOpenProfileFromStreamTHR(cmsContext ContextID,FILE * ICCProfile,const char * sAccess)1109 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char *sAccess)
1110 {
1111     _cmsICCPROFILE* NewIcc;
1112     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1113 
1114     if (hEmpty == NULL) return NULL;
1115 
1116     NewIcc = (_cmsICCPROFILE*) hEmpty;
1117 
1118     NewIcc ->IOhandler = cmsOpenIOhandlerFromStream(ContextID, ICCProfile);
1119     if (NewIcc ->IOhandler == NULL) goto Error;
1120 
1121     if (*sAccess == 'w') {
1122 
1123         NewIcc -> IsWrite = TRUE;
1124         return hEmpty;
1125     }
1126 
1127     if (!_cmsReadHeader(NewIcc)) goto Error;
1128     return hEmpty;
1129 
1130 Error:
1131     cmsCloseProfile(hEmpty);
1132     return NULL;
1133 
1134 }
1135 
cmsOpenProfileFromStream(FILE * ICCProfile,const char * sAccess)1136 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char *sAccess)
1137 {
1138     return cmsOpenProfileFromStreamTHR(NULL, ICCProfile, sAccess);
1139 }
1140 
1141 
1142 // Open from memory block
cmsOpenProfileFromMemTHR(cmsContext ContextID,const void * MemPtr,cmsUInt32Number dwSize)1143 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void* MemPtr, cmsUInt32Number dwSize)
1144 {
1145     _cmsICCPROFILE* NewIcc;
1146     cmsHPROFILE hEmpty;
1147 
1148     hEmpty = cmsCreateProfilePlaceholder(ContextID);
1149     if (hEmpty == NULL) return NULL;
1150 
1151     NewIcc = (_cmsICCPROFILE*) hEmpty;
1152 
1153     // Ok, in this case const void* is casted to void* just because open IO handler
1154     // shares read and writing modes. Don't abuse this feature!
1155     NewIcc ->IOhandler = cmsOpenIOhandlerFromMem(ContextID, (void*) MemPtr, dwSize, "r");
1156     if (NewIcc ->IOhandler == NULL) goto Error;
1157 
1158     if (!_cmsReadHeader(NewIcc)) goto Error;
1159 
1160     return hEmpty;
1161 
1162 Error:
1163     cmsCloseProfile(hEmpty);
1164     return NULL;
1165 }
1166 
cmsOpenProfileFromMem(const void * MemPtr,cmsUInt32Number dwSize)1167 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number dwSize)
1168 {
1169     return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
1170 }
1171 
1172 
1173 
1174 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
1175 static
SaveTags(_cmsICCPROFILE * Icc,_cmsICCPROFILE * FileOrig)1176 cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
1177 {
1178     cmsUInt8Number* Data;
1179     cmsUInt32Number i;
1180     cmsUInt32Number Begin;
1181     cmsIOHANDLER* io = Icc ->IOhandler;
1182     cmsTagDescriptor* TagDescriptor;
1183     cmsTagTypeSignature TypeBase;
1184     cmsTagTypeSignature Type;
1185     cmsTagTypeHandler* TypeHandler;
1186     cmsFloat64Number   Version = cmsGetProfileVersion((cmsHPROFILE) Icc);
1187     cmsTagTypeHandler LocalTypeHandler;
1188 
1189     for (i=0; i < Icc -> TagCount; i++) {
1190 
1191         if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;
1192 
1193         // Linked tags are not written
1194         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
1195 
1196         Icc -> TagOffsets[i] = Begin = io ->UsedSpace;
1197 
1198         Data = (cmsUInt8Number*)  Icc -> TagPtrs[i];
1199 
1200         if (!Data) {
1201 
1202             // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
1203             // In this case a blind copy of the block data is performed
1204             if (FileOrig != NULL && Icc -> TagOffsets[i]) {
1205 
1206                 if (FileOrig->IOhandler != NULL)
1207                 {
1208                     cmsUInt32Number TagSize = FileOrig->TagSizes[i];
1209                     cmsUInt32Number TagOffset = FileOrig->TagOffsets[i];
1210                     void* Mem;
1211 
1212                     if (!FileOrig->IOhandler->Seek(FileOrig->IOhandler, TagOffset)) return FALSE;
1213 
1214                     Mem = _cmsMalloc(Icc->ContextID, TagSize);
1215                     if (Mem == NULL) return FALSE;
1216 
1217                     if (FileOrig->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
1218                     if (!io->Write(io, TagSize, Mem)) return FALSE;
1219                     _cmsFree(Icc->ContextID, Mem);
1220 
1221                     Icc->TagSizes[i] = (io->UsedSpace - Begin);
1222 
1223 
1224                     // Align to 32 bit boundary.
1225                     if (!_cmsWriteAlignment(io))
1226                         return FALSE;
1227                 }
1228             }
1229 
1230             continue;
1231         }
1232 
1233 
1234         // Should this tag be saved as RAW? If so, tagsizes should be specified in advance (no further cooking is done)
1235         if (Icc ->TagSaveAsRaw[i]) {
1236 
1237             if (io -> Write(io, Icc ->TagSizes[i], Data) != 1) return FALSE;
1238         }
1239         else {
1240 
1241             // Search for support on this tag
1242             TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, Icc -> TagNames[i]);
1243             if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
1244 
1245             if (TagDescriptor ->DecideType != NULL) {
1246 
1247                 Type = TagDescriptor ->DecideType(Version, Data);
1248             }
1249             else {
1250 
1251                 Type = TagDescriptor ->SupportedTypes[0];
1252             }
1253 
1254             TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1255 
1256             if (TypeHandler == NULL) {
1257                 cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
1258                 continue;
1259             }
1260 
1261             TypeBase = TypeHandler ->Signature;
1262             if (!_cmsWriteTypeBase(io, TypeBase))
1263                 return FALSE;
1264 
1265             LocalTypeHandler = *TypeHandler;
1266             LocalTypeHandler.ContextID  = Icc ->ContextID;
1267             LocalTypeHandler.ICCVersion = Icc ->Version;
1268             if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, io, Data, TagDescriptor ->ElemCount)) {
1269 
1270                 char String[5];
1271 
1272                 _cmsTagSignature2String(String, (cmsTagSignature) TypeBase);
1273                 cmsSignalError(Icc ->ContextID, cmsERROR_WRITE, "Couldn't write type '%s'", String);
1274                 return FALSE;
1275             }
1276         }
1277 
1278 
1279         Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1280 
1281         // Align to 32 bit boundary.
1282         if (! _cmsWriteAlignment(io))
1283             return FALSE;
1284     }
1285 
1286 
1287     return TRUE;
1288 }
1289 
1290 
1291 // Fill the offset and size fields for all linked tags
1292 static
SetLinks(_cmsICCPROFILE * Icc)1293 cmsBool SetLinks( _cmsICCPROFILE* Icc)
1294 {
1295     cmsUInt32Number i;
1296 
1297     for (i=0; i < Icc -> TagCount; i++) {
1298 
1299         cmsTagSignature lnk = Icc ->TagLinked[i];
1300         if (lnk != (cmsTagSignature) 0) {
1301 
1302             int j = _cmsSearchTag(Icc, lnk, FALSE);
1303             if (j >= 0) {
1304 
1305                 Icc ->TagOffsets[i] = Icc ->TagOffsets[j];
1306                 Icc ->TagSizes[i]   = Icc ->TagSizes[j];
1307             }
1308 
1309         }
1310     }
1311 
1312     return TRUE;
1313 }
1314 
1315 // Low-level save to IOHANDLER. It returns the number of bytes used to
1316 // store the profile, or zero on error. io may be NULL and in this case
1317 // no data is written--only sizes are calculated
cmsSaveProfileToIOhandler(cmsHPROFILE hProfile,cmsIOHANDLER * io)1318 cmsUInt32Number CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io)
1319 {
1320     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1321     _cmsICCPROFILE Keep;
1322     cmsIOHANDLER* PrevIO = NULL;
1323     cmsUInt32Number UsedSpace;
1324     cmsContext ContextID;
1325 
1326     _cmsAssert(hProfile != NULL);
1327 
1328     if (!_cmsLockMutex(Icc->ContextID, Icc->UsrMutex)) return 0;
1329     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
1330 
1331     ContextID = cmsGetProfileContextID(hProfile);
1332     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
1333     if (PrevIO == NULL) {
1334         _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1335         return 0;
1336     }
1337 
1338     // Pass #1 does compute offsets
1339 
1340     if (!_cmsWriteHeader(Icc, 0)) goto Error;
1341     if (!SaveTags(Icc, &Keep)) goto Error;
1342 
1343     UsedSpace = PrevIO ->UsedSpace;
1344 
1345     // Pass #2 does save to iohandler
1346 
1347     if (io != NULL) {
1348 
1349         Icc ->IOhandler = io;
1350         if (!SetLinks(Icc)) goto Error;
1351         if (!_cmsWriteHeader(Icc, UsedSpace)) goto Error;
1352         if (!SaveTags(Icc, &Keep)) goto Error;
1353     }
1354 
1355     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1356     if (!cmsCloseIOhandler(PrevIO))
1357         UsedSpace = 0; // As a error marker
1358 
1359     _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1360 
1361     return UsedSpace;
1362 
1363 
1364 Error:
1365     cmsCloseIOhandler(PrevIO);
1366     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1367     _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1368 
1369     return 0;
1370 }
1371 
1372 
1373 // Low-level save to disk.
cmsSaveProfileToFile(cmsHPROFILE hProfile,const char * FileName)1374 cmsBool  CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName)
1375 {
1376     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1377     cmsIOHANDLER* io = cmsOpenIOhandlerFromFile(ContextID, FileName, "w");
1378     cmsBool rc;
1379 
1380     if (io == NULL) return FALSE;
1381 
1382     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1383     rc &= cmsCloseIOhandler(io);
1384 
1385     if (rc == FALSE) {          // remove() is C99 per 7.19.4.1
1386             remove(FileName);   // We have to IGNORE return value in this case
1387     }
1388     return rc;
1389 }
1390 
1391 // Same as anterior, but for streams
cmsSaveProfileToStream(cmsHPROFILE hProfile,FILE * Stream)1392 cmsBool CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream)
1393 {
1394     cmsBool rc;
1395     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1396     cmsIOHANDLER* io = cmsOpenIOhandlerFromStream(ContextID, Stream);
1397 
1398     if (io == NULL) return FALSE;
1399 
1400     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1401     rc &= cmsCloseIOhandler(io);
1402 
1403     return rc;
1404 }
1405 
1406 
1407 // Same as anterior, but for memory blocks. In this case, a NULL as MemPtr means calculate needed space only
cmsSaveProfileToMem(cmsHPROFILE hProfile,void * MemPtr,cmsUInt32Number * BytesNeeded)1408 cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded)
1409 {
1410     cmsBool rc;
1411     cmsIOHANDLER* io;
1412     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1413 
1414     _cmsAssert(BytesNeeded != NULL);
1415 
1416     // Should we just calculate the needed space?
1417     if (MemPtr == NULL) {
1418 
1419            *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
1420             return (*BytesNeeded == 0) ? FALSE : TRUE;
1421     }
1422 
1423     // That is a real write operation
1424     io =  cmsOpenIOhandlerFromMem(ContextID, MemPtr, *BytesNeeded, "w");
1425     if (io == NULL) return FALSE;
1426 
1427     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1428     rc &= cmsCloseIOhandler(io);
1429 
1430     return rc;
1431 }
1432 
1433 
1434 
1435 // Closes a profile freeing any involved resources
cmsCloseProfile(cmsHPROFILE hProfile)1436 cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
1437 {
1438     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1439     cmsBool  rc = TRUE;
1440     cmsUInt32Number i;
1441 
1442     if (!Icc) return FALSE;
1443 
1444     // Was open in write mode?
1445     if (Icc ->IsWrite) {
1446 
1447         Icc ->IsWrite = FALSE;      // Assure no further writing
1448         rc &= cmsSaveProfileToFile(hProfile, Icc ->IOhandler->PhysicalFile);
1449     }
1450 
1451     for (i=0; i < Icc -> TagCount; i++) {
1452 
1453         if (Icc -> TagPtrs[i]) {
1454 
1455             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
1456 
1457             if (TypeHandler != NULL) {
1458                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
1459 
1460                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameters
1461                 LocalTypeHandler.ICCVersion = Icc ->Version;
1462                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
1463             }
1464             else
1465                 _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
1466         }
1467     }
1468 
1469     if (Icc ->IOhandler != NULL) {
1470         rc &= cmsCloseIOhandler(Icc->IOhandler);
1471     }
1472 
1473     _cmsDestroyMutex(Icc->ContextID, Icc->UsrMutex);
1474 
1475     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
1476 
1477     return rc;
1478 }
1479 
1480 
1481 // -------------------------------------------------------------------------------------------------------------------
1482 
1483 
1484 // Returns TRUE if a given tag is supported by a plug-in
1485 static
IsTypeSupported(cmsTagDescriptor * TagDescriptor,cmsTagTypeSignature Type)1486 cmsBool IsTypeSupported(cmsTagDescriptor* TagDescriptor, cmsTagTypeSignature Type)
1487 {
1488     cmsUInt32Number i, nMaxTypes;
1489 
1490     nMaxTypes = TagDescriptor->nSupportedTypes;
1491     if (nMaxTypes >= MAX_TYPES_IN_LCMS_PLUGIN)
1492         nMaxTypes = MAX_TYPES_IN_LCMS_PLUGIN;
1493 
1494     for (i=0; i < nMaxTypes; i++) {
1495         if (Type == TagDescriptor ->SupportedTypes[i]) return TRUE;
1496     }
1497 
1498     return FALSE;
1499 }
1500 
1501 
1502 // That's the main read function
cmsReadTag(cmsHPROFILE hProfile,cmsTagSignature sig)1503 void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
1504 {
1505     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1506     cmsIOHANDLER* io = Icc ->IOhandler;
1507     cmsTagTypeHandler* TypeHandler;
1508     cmsTagTypeHandler LocalTypeHandler;
1509     cmsTagDescriptor*  TagDescriptor;
1510     cmsTagTypeSignature BaseType;
1511     cmsUInt32Number Offset, TagSize;
1512     cmsUInt32Number ElemCount;
1513     int n;
1514 
1515     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return NULL;
1516 
1517     n = _cmsSearchTag(Icc, sig, TRUE);
1518     if (n < 0) goto Error;               // Not found, return NULL
1519 
1520 
1521     // If the element is already in memory, return the pointer
1522     if (Icc -> TagPtrs[n]) {
1523 
1524         if (Icc->TagTypeHandlers[n] == NULL) goto Error;
1525 
1526         // Sanity check
1527         BaseType = Icc->TagTypeHandlers[n]->Signature;
1528         if (BaseType == 0) goto Error;
1529 
1530         TagDescriptor = _cmsGetTagDescriptor(Icc->ContextID, sig);
1531         if (TagDescriptor == NULL) goto Error;
1532 
1533         if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
1534 
1535         if (Icc ->TagSaveAsRaw[n]) goto Error;  // We don't support read raw tags as cooked
1536 
1537         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1538         return Icc -> TagPtrs[n];
1539     }
1540 
1541     // We need to read it. Get the offset and size to the file
1542     Offset    = Icc -> TagOffsets[n];
1543     TagSize   = Icc -> TagSizes[n];
1544 
1545     if (TagSize < 8) goto Error;
1546 
1547     // Seek to its location
1548     if (!io -> Seek(io, Offset))
1549         goto Error;
1550 
1551     // Search for support on this tag
1552     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1553     if (TagDescriptor == NULL) {
1554 
1555         char String[5];
1556 
1557         _cmsTagSignature2String(String, sig);
1558 
1559         // An unknown element was found.
1560         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown tag type '%s' found.", String);
1561         goto Error;     // Unsupported.
1562     }
1563 
1564     // if supported, get type and check if in list
1565     BaseType = _cmsReadTypeBase(io);
1566     if (BaseType == 0) goto Error;
1567 
1568     if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
1569 
1570     TagSize  -= 8;       // Already read by the type base logic
1571 
1572     // Get type handler
1573     TypeHandler = _cmsGetTagTypeHandler(Icc ->ContextID, BaseType);
1574     if (TypeHandler == NULL) goto Error;
1575     LocalTypeHandler = *TypeHandler;
1576 
1577 
1578     // Read the tag
1579     Icc -> TagTypeHandlers[n] = TypeHandler;
1580 
1581     LocalTypeHandler.ContextID = Icc ->ContextID;
1582     LocalTypeHandler.ICCVersion = Icc ->Version;
1583     Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
1584 
1585     // The tag type is supported, but something wrong happened and we cannot read the tag.
1586     // let know the user about this (although it is just a warning)
1587     if (Icc -> TagPtrs[n] == NULL) {
1588 
1589         char String[5];
1590 
1591         _cmsTagSignature2String(String, sig);
1592         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
1593         goto Error;
1594     }
1595 
1596     // This is a weird error that may be a symptom of something more serious, the number of
1597     // stored item is actually less than the number of required elements.
1598     if (ElemCount < TagDescriptor ->ElemCount) {
1599 
1600         char String[5];
1601 
1602         _cmsTagSignature2String(String, sig);
1603         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d",
1604             String, TagDescriptor ->ElemCount, ElemCount);
1605         goto Error;
1606     }
1607 
1608 
1609     // Return the data
1610     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1611     return Icc -> TagPtrs[n];
1612 
1613 
1614     // Return error and unlock tha data
1615 Error:
1616     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1617     return NULL;
1618 }
1619 
1620 
1621 // Get true type of data
_cmsGetTagTrueType(cmsHPROFILE hProfile,cmsTagSignature sig)1622 cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig)
1623 {
1624     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1625     cmsTagTypeHandler* TypeHandler;
1626     int n;
1627 
1628     // Search for given tag in ICC profile directory
1629     n = _cmsSearchTag(Icc, sig, TRUE);
1630     if (n < 0) return (cmsTagTypeSignature) 0;                // Not found, return NULL
1631 
1632     // Get the handler. The true type is there
1633     TypeHandler =  Icc -> TagTypeHandlers[n];
1634     return TypeHandler ->Signature;
1635 }
1636 
1637 
1638 // Write a single tag. This just keeps track of the tak into a list of "to be written". If the tag is already
1639 // in that list, the previous version is deleted.
cmsWriteTag(cmsHPROFILE hProfile,cmsTagSignature sig,const void * data)1640 cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data)
1641 {
1642     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1643     cmsTagTypeHandler* TypeHandler = NULL;
1644     cmsTagTypeHandler LocalTypeHandler;
1645     cmsTagDescriptor* TagDescriptor = NULL;
1646     cmsTagTypeSignature Type;
1647     int i;
1648     cmsFloat64Number Version;
1649     char TypeString[5], SigString[5];
1650 
1651     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1652 
1653     // To delete tags.
1654     if (data == NULL) {
1655 
1656          // Delete the tag
1657          i = _cmsSearchTag(Icc, sig, FALSE);
1658          if (i >= 0) {
1659 
1660              // Use zero as a mark of deleted
1661              _cmsDeleteTagByPos(Icc, i);
1662              Icc ->TagNames[i] = (cmsTagSignature) 0;
1663              _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1664              return TRUE;
1665          }
1666          // Didn't find the tag
1667         goto Error;
1668     }
1669 
1670     if (!_cmsNewTag(Icc, sig, &i)) goto Error;
1671 
1672     // This is not raw
1673     Icc ->TagSaveAsRaw[i] = FALSE;
1674 
1675     // This is not a link
1676     Icc ->TagLinked[i] = (cmsTagSignature) 0;
1677 
1678     // Get information about the TAG.
1679     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1680     if (TagDescriptor == NULL){
1681          cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
1682         goto Error;
1683     }
1684 
1685 
1686     // Now we need to know which type to use. It depends on the version.
1687     Version = cmsGetProfileVersion(hProfile);
1688 
1689     if (TagDescriptor ->DecideType != NULL) {
1690 
1691         // Let the tag descriptor to decide the type base on depending on
1692         // the data. This is useful for example on parametric curves, where
1693         // curves specified by a table cannot be saved as parametric and needs
1694         // to be casted to single v2-curves, even on v4 profiles.
1695 
1696         Type = TagDescriptor ->DecideType(Version, data);
1697     }
1698     else {
1699 
1700         Type = TagDescriptor ->SupportedTypes[0];
1701     }
1702 
1703     // Does the tag support this type?
1704     if (!IsTypeSupported(TagDescriptor, Type)) {
1705 
1706         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1707         _cmsTagSignature2String(SigString,  sig);
1708 
1709         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1710         goto Error;
1711     }
1712 
1713     // Does we have a handler for this type?
1714     TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1715     if (TypeHandler == NULL) {
1716 
1717         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1718         _cmsTagSignature2String(SigString,  sig);
1719 
1720         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1721         goto Error;           // Should never happen
1722     }
1723 
1724 
1725     // Fill fields on icc structure
1726     Icc ->TagTypeHandlers[i]  = TypeHandler;
1727     Icc ->TagNames[i]         = sig;
1728     Icc ->TagSizes[i]         = 0;
1729     Icc ->TagOffsets[i]       = 0;
1730 
1731     LocalTypeHandler = *TypeHandler;
1732     LocalTypeHandler.ContextID  = Icc ->ContextID;
1733     LocalTypeHandler.ICCVersion = Icc ->Version;
1734     Icc ->TagPtrs[i]            = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
1735 
1736     if (Icc ->TagPtrs[i] == NULL)  {
1737 
1738         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1739         _cmsTagSignature2String(SigString,  sig);
1740         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%s' for tag '%s'", TypeString, SigString);
1741 
1742         goto Error;
1743     }
1744 
1745     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1746     return TRUE;
1747 
1748 Error:
1749     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1750     return FALSE;
1751 
1752 }
1753 
1754 // Read and write raw data. The only way those function would work and keep consistence with normal read and write
1755 // is to do an additional step of serialization. That means, readRaw would issue a normal read and then convert the obtained
1756 // data to raw bytes by using the "write" serialization logic. And vice-versa. I know this may end in situations where
1757 // raw data written does not exactly correspond with the raw data proposed to cmsWriteRaw data, but this approach allows
1758 // to write a tag as raw data and the read it as handled.
1759 
cmsReadRawTag(cmsHPROFILE hProfile,cmsTagSignature sig,void * data,cmsUInt32Number BufferSize)1760 cmsUInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* data, cmsUInt32Number BufferSize)
1761 {
1762     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1763     void *Object;
1764     int i;
1765     cmsIOHANDLER* MemIO;
1766     cmsTagTypeHandler* TypeHandler = NULL;
1767     cmsTagTypeHandler LocalTypeHandler;
1768     cmsTagDescriptor* TagDescriptor = NULL;
1769     cmsUInt32Number rc;
1770     cmsUInt32Number Offset, TagSize;
1771 
1772     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1773 
1774     // Search for given tag in ICC profile directory
1775     i = _cmsSearchTag(Icc, sig, TRUE);
1776     if (i < 0) goto Error;                 // Not found,
1777 
1778     // It is already read?
1779     if (Icc -> TagPtrs[i] == NULL) {
1780 
1781         // No yet, get original position
1782         Offset   = Icc ->TagOffsets[i];
1783         TagSize  = Icc ->TagSizes[i];
1784 
1785         // read the data directly, don't keep copy
1786         if (data != NULL) {
1787 
1788             if (BufferSize < TagSize)
1789                 TagSize = BufferSize;
1790 
1791             if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) goto Error;
1792             if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) goto Error;
1793 
1794             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1795             return TagSize;
1796         }
1797 
1798         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1799         return Icc ->TagSizes[i];
1800     }
1801 
1802     // The data has been already read, or written. But wait!, maybe the user chose to save as
1803     // raw data. In this case, return the raw data directly
1804     if (Icc ->TagSaveAsRaw[i]) {
1805 
1806         if (data != NULL)  {
1807 
1808             TagSize  = Icc ->TagSizes[i];
1809             if (BufferSize < TagSize)
1810                 TagSize = BufferSize;
1811 
1812             memmove(data, Icc ->TagPtrs[i], TagSize);
1813 
1814             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1815             return TagSize;
1816         }
1817 
1818         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1819         return Icc ->TagSizes[i];
1820     }
1821 
1822     // Already read, or previously set by cmsWriteTag(). We need to serialize that
1823     // data to raw in order to maintain consistency.
1824 
1825     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1826     Object = cmsReadTag(hProfile, sig);
1827     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1828 
1829     if (Object == NULL) goto Error;
1830 
1831     // Now we need to serialize to a memory block: just use a memory iohandler
1832 
1833     if (data == NULL) {
1834         MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
1835     } else{
1836         MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
1837     }
1838     if (MemIO == NULL) goto Error;
1839 
1840     // Obtain type handling for the tag
1841     TypeHandler = Icc ->TagTypeHandlers[i];
1842     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1843     if (TagDescriptor == NULL) {
1844         cmsCloseIOhandler(MemIO);
1845         goto Error;
1846     }
1847 
1848     if (TypeHandler == NULL) goto Error;
1849 
1850     // Serialize
1851     LocalTypeHandler = *TypeHandler;
1852     LocalTypeHandler.ContextID  = Icc ->ContextID;
1853     LocalTypeHandler.ICCVersion = Icc ->Version;
1854 
1855     if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
1856         cmsCloseIOhandler(MemIO);
1857         goto Error;
1858     }
1859 
1860     if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
1861         cmsCloseIOhandler(MemIO);
1862         goto Error;
1863     }
1864 
1865     // Get Size and close
1866     rc = MemIO ->Tell(MemIO);
1867     cmsCloseIOhandler(MemIO);      // Ignore return code this time
1868 
1869     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1870     return rc;
1871 
1872 Error:
1873     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1874     return 0;
1875 }
1876 
1877 // Similar to the anterior. This function allows to write directly to the ICC profile any data, without
1878 // checking anything. As a rule, mixing Raw with cooked doesn't work, so writing a tag as raw and then reading
1879 // it as cooked without serializing does result into an error. If that is what you want, you will need to dump
1880 // the profile to memry or disk and then reopen it.
cmsWriteRawTag(cmsHPROFILE hProfile,cmsTagSignature sig,const void * data,cmsUInt32Number Size)1881 cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size)
1882 {
1883     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1884     int i;
1885 
1886     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1887 
1888     if (!_cmsNewTag(Icc, sig, &i)) {
1889         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1890          return FALSE;
1891     }
1892 
1893     // Mark the tag as being written as RAW
1894     Icc ->TagSaveAsRaw[i] = TRUE;
1895     Icc ->TagNames[i]     = sig;
1896     Icc ->TagLinked[i]    = (cmsTagSignature) 0;
1897 
1898     // Keep a copy of the block
1899     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
1900     Icc ->TagSizes[i] = Size;
1901 
1902     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1903 
1904     if (Icc->TagPtrs[i] == NULL) {
1905            Icc->TagNames[i] = (cmsTagSignature) 0;
1906            return FALSE;
1907     }
1908     return TRUE;
1909 }
1910 
1911 // Using this function you can collapse several tag entries to the same block in the profile
cmsLinkTag(cmsHPROFILE hProfile,cmsTagSignature sig,cmsTagSignature dest)1912 cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
1913 {
1914     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1915     int i;
1916 
1917      if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1918 
1919     if (!_cmsNewTag(Icc, sig, &i)) {
1920         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1921         return FALSE;
1922     }
1923 
1924     // Keep necessary information
1925     Icc ->TagSaveAsRaw[i] = FALSE;
1926     Icc ->TagNames[i]     = sig;
1927     Icc ->TagLinked[i]    = dest;
1928 
1929     Icc ->TagPtrs[i]    = NULL;
1930     Icc ->TagSizes[i]   = 0;
1931     Icc ->TagOffsets[i] = 0;
1932 
1933     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1934     return TRUE;
1935 }
1936 
1937 
1938 // Returns the tag linked to sig, in the case two tags are sharing same resource
cmsTagLinkedTo(cmsHPROFILE hProfile,cmsTagSignature sig)1939 cmsTagSignature  CMSEXPORT cmsTagLinkedTo(cmsHPROFILE hProfile, cmsTagSignature sig)
1940 {
1941     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1942     int i;
1943 
1944     // Search for given tag in ICC profile directory
1945     i = _cmsSearchTag(Icc, sig, FALSE);
1946     if (i < 0) return (cmsTagSignature) 0;                 // Not found, return 0
1947 
1948     return Icc -> TagLinked[i];
1949 }
1950