1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2017 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"), Buffere 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", 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 #ifdef _WIN32_WCE
489 time_t wceex_time(time_t *timer);
490 struct tm * wceex_gmtime(const time_t *timer);
491 
492 #define time wceex_time
493 #define gmtime wceex_gmtime
494 #endif
495 
496 // Creates an empty structure holding all required parameters
cmsCreateProfilePlaceholder(cmsContext ContextID)497 cmsHPROFILE CMSEXPORT cmsCreateProfilePlaceholder(cmsContext ContextID)
498 {
499     time_t now = time(NULL);
500     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) _cmsMallocZero(ContextID, sizeof(_cmsICCPROFILE));
501     if (Icc == NULL) return NULL;
502 
503     Icc ->ContextID = ContextID;
504 
505     // Set it to empty
506     Icc -> TagCount   = 0;
507 
508     // Set default version
509     Icc ->Version =  0x02100000;
510 
511     // Set creation date/time
512     memmove(&Icc ->Created, gmtime(&now), sizeof(Icc ->Created));
513 
514     // Create a mutex if the user provided proper plugin. NULL otherwise
515     Icc ->UsrMutex = _cmsCreateMutex(ContextID);
516 
517     // Return the handle
518     return (cmsHPROFILE) Icc;
519 }
520 
cmsGetProfileContextID(cmsHPROFILE hProfile)521 cmsContext CMSEXPORT cmsGetProfileContextID(cmsHPROFILE hProfile)
522 {
523      _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
524 
525     if (Icc == NULL) return NULL;
526     return Icc -> ContextID;
527 }
528 
529 
530 // Return the number of tags
cmsGetTagCount(cmsHPROFILE hProfile)531 cmsInt32Number CMSEXPORT cmsGetTagCount(cmsHPROFILE hProfile)
532 {
533     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
534     if (Icc == NULL) return -1;
535 
536     return  (cmsInt32Number) Icc->TagCount;
537 }
538 
539 // Return the tag signature of a given tag number
cmsGetTagSignature(cmsHPROFILE hProfile,cmsUInt32Number n)540 cmsTagSignature CMSEXPORT cmsGetTagSignature(cmsHPROFILE hProfile, cmsUInt32Number n)
541 {
542     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
543 
544     if (n > Icc->TagCount) return (cmsTagSignature) 0;  // Mark as not available
545     if (n >= MAX_TABLE_TAG) return (cmsTagSignature) 0; // As double check
546 
547     return Icc ->TagNames[n];
548 }
549 
550 
551 static
SearchOneTag(_cmsICCPROFILE * Profile,cmsTagSignature sig)552 int SearchOneTag(_cmsICCPROFILE* Profile, cmsTagSignature sig)
553 {
554     int i;
555 
556     for (i=0; i < (int) Profile -> TagCount; i++) {
557 
558         if (sig == Profile -> TagNames[i])
559             return i;
560     }
561 
562     return -1;
563 }
564 
565 // Search for a specific tag in tag dictionary. Returns position or -1 if tag not found.
566 // If followlinks is turned on, then the position of the linked tag is returned
_cmsSearchTag(_cmsICCPROFILE * Icc,cmsTagSignature sig,cmsBool lFollowLinks)567 int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks)
568 {
569     int n;
570     cmsTagSignature LinkedSig;
571 
572     do {
573 
574         // Search for given tag in ICC profile directory
575         n = SearchOneTag(Icc, sig);
576         if (n < 0)
577             return -1;        // Not found
578 
579         if (!lFollowLinks)
580             return n;         // Found, don't follow links
581 
582         // Is this a linked tag?
583         LinkedSig = Icc ->TagLinked[n];
584 
585         // Yes, follow link
586         if (LinkedSig != (cmsTagSignature) 0) {
587             // fix bug mantis id#0055942
588             // assume that TRCTag and ColorantTag can't be linked.
589             // Xiaochuan Liu 2014-04-23
590             if ((sig == cmsSigRedTRCTag || sig == cmsSigGreenTRCTag || sig == cmsSigBlueTRCTag) &&
591                 (LinkedSig == cmsSigRedColorantTag || LinkedSig == cmsSigGreenColorantTag || LinkedSig == cmsSigBlueColorantTag))
592             {
593                 return n;
594             }
595             sig = LinkedSig;
596         }
597 
598     } while (LinkedSig != (cmsTagSignature) 0);
599 
600     return n;
601 }
602 
603 // Deletes a tag entry
604 
605 static
_cmsDeleteTagByPos(_cmsICCPROFILE * Icc,int i)606 void _cmsDeleteTagByPos(_cmsICCPROFILE* Icc, int i)
607 {
608     _cmsAssert(Icc != NULL);
609     _cmsAssert(i >= 0);
610 
611 
612     if (Icc -> TagPtrs[i] != NULL) {
613 
614         // Free previous version
615         if (Icc ->TagSaveAsRaw[i]) {
616             _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
617         }
618         else {
619             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
620 
621             if (TypeHandler != NULL) {
622 
623                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
624                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameter
625                 LocalTypeHandler.ICCVersion = Icc ->Version;
626                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
627                 Icc ->TagPtrs[i] = NULL;
628             }
629         }
630 
631     }
632 }
633 
634 
635 // Creates a new tag entry
636 static
_cmsNewTag(_cmsICCPROFILE * Icc,cmsTagSignature sig,int * NewPos)637 cmsBool _cmsNewTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, int* NewPos)
638 {
639     int i;
640 
641     // Search for the tag
642     i = _cmsSearchTag(Icc, sig, FALSE);
643     if (i >= 0) {
644 
645         // Already exists? delete it
646         _cmsDeleteTagByPos(Icc, i);
647         *NewPos = i;
648     }
649     else  {
650 
651         // No, make a new one
652 
653         if (Icc -> TagCount >= MAX_TABLE_TAG) {
654             cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", MAX_TABLE_TAG);
655             return FALSE;
656         }
657 
658         *NewPos = (int) Icc ->TagCount;
659         Icc -> TagCount++;
660     }
661 
662     return TRUE;
663 }
664 
665 
666 // Check existence
cmsIsTag(cmsHPROFILE hProfile,cmsTagSignature sig)667 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
668 {
669        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
670        return _cmsSearchTag(Icc, sig, FALSE) >= 0;
671 }
672 
673 
674 
675 // Enforces that the profile version is per. spec.
676 // Operates on the big endian bytes from the profile.
677 // Called before converting to platform endianness.
678 // Byte 0 is BCD major version, so max 9.
679 // Byte 1 is 2 BCD digits, one per nibble.
680 // Reserved bytes 2 & 3 must be 0.
681 static
_validatedVersion(cmsUInt32Number DWord)682 cmsUInt32Number _validatedVersion(cmsUInt32Number DWord)
683 {
684     cmsUInt8Number* pByte = (cmsUInt8Number*) &DWord;
685     cmsUInt8Number temp1;
686     cmsUInt8Number temp2;
687 
688     if (*pByte > 0x09) *pByte = (cmsUInt8Number) 0x09;
689     temp1 = (cmsUInt8Number) (*(pByte+1) & 0xf0);
690     temp2 = (cmsUInt8Number) (*(pByte+1) & 0x0f);
691     if (temp1 > 0x90U) temp1 = 0x90U;
692     if (temp2 > 0x09U) temp2 = 0x09U;
693     *(pByte+1) = (cmsUInt8Number)(temp1 | temp2);
694     *(pByte+2) = (cmsUInt8Number)0;
695     *(pByte+3) = (cmsUInt8Number)0;
696 
697     return DWord;
698 }
699 
700 // Read profile header and validate it
_cmsReadHeader(_cmsICCPROFILE * Icc)701 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
702 {
703     cmsTagEntry Tag;
704     cmsICCHeader Header;
705     cmsUInt32Number i, j;
706     cmsUInt32Number HeaderSize;
707     cmsIOHANDLER* io = Icc ->IOhandler;
708     cmsUInt32Number TagCount;
709 
710 
711     // Read the header
712     if (io -> Read(io, &Header, sizeof(cmsICCHeader), 1) != 1) {
713         return FALSE;
714     }
715 
716     // Validate file as an ICC profile
717     if (_cmsAdjustEndianess32(Header.magic) != cmsMagicNumber) {
718         cmsSignalError(Icc ->ContextID, cmsERROR_BAD_SIGNATURE, "not an ICC profile, invalid signature");
719         return FALSE;
720     }
721 
722     // Adjust endianness of the used parameters
723     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
724     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
725     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
726 
727     Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
728     Icc -> flags           = _cmsAdjustEndianess32(Header.flags);
729     Icc -> manufacturer    = _cmsAdjustEndianess32(Header.manufacturer);
730     Icc -> model           = _cmsAdjustEndianess32(Header.model);
731     Icc -> creator         = _cmsAdjustEndianess32(Header.creator);
732 
733     _cmsAdjustEndianess64(&Icc -> attributes, &Header.attributes);
734     Icc -> Version         = _cmsAdjustEndianess32(_validatedVersion(Header.version));
735 
736     // Get size as reported in header
737     HeaderSize = _cmsAdjustEndianess32(Header.size);
738 
739     // Make sure HeaderSize is lower than profile size
740     if (HeaderSize >= Icc ->IOhandler ->ReportedSize)
741             HeaderSize = Icc ->IOhandler ->ReportedSize;
742 
743 
744     // Get creation date/time
745     _cmsDecodeDateTimeNumber(&Header.date, &Icc ->Created);
746 
747     // The profile ID are 32 raw bytes
748     memmove(Icc ->ProfileID.ID32, Header.profileID.ID32, 16);
749 
750 
751     // Read tag directory
752     if (!_cmsReadUInt32Number(io, &TagCount)) return FALSE;
753     if (TagCount > MAX_TABLE_TAG) {
754 
755         cmsSignalError(Icc ->ContextID, cmsERROR_RANGE, "Too many tags (%d)", TagCount);
756         return FALSE;
757     }
758 
759 
760     // Read tag directory
761     Icc -> TagCount = 0;
762     for (i=0; i < TagCount; i++) {
763 
764         if (!_cmsReadUInt32Number(io, (cmsUInt32Number *) &Tag.sig)) return FALSE;
765         if (!_cmsReadUInt32Number(io, &Tag.offset)) return FALSE;
766         if (!_cmsReadUInt32Number(io, &Tag.size)) return FALSE;
767 
768         // Perform some sanity check. Offset + size should fall inside file.
769         if (Tag.offset + Tag.size > HeaderSize ||
770             Tag.offset + Tag.size < Tag.offset)
771                   continue;
772 
773         Icc -> TagNames[Icc ->TagCount]   = Tag.sig;
774         Icc -> TagOffsets[Icc ->TagCount] = Tag.offset;
775         Icc -> TagSizes[Icc ->TagCount]   = Tag.size;
776 
777        // Search for links
778         for (j=0; j < Icc ->TagCount; j++) {
779 
780             if ((Icc ->TagOffsets[j] == Tag.offset) &&
781                 (Icc ->TagSizes[j]   == Tag.size) &&
782                 (Icc ->TagNames[j]   == Tag.sig)) {
783 
784                 Icc ->TagLinked[Icc ->TagCount] = Icc ->TagNames[j];
785             }
786 
787         }
788 
789         Icc ->TagCount++;
790     }
791 
792     return TRUE;
793 }
794 
795 // Saves profile header
_cmsWriteHeader(_cmsICCPROFILE * Icc,cmsUInt32Number UsedSpace)796 cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace)
797 {
798     cmsICCHeader Header;
799     cmsUInt32Number i;
800     cmsTagEntry Tag;
801     cmsUInt32Number Count;
802 
803     Header.size        = _cmsAdjustEndianess32(UsedSpace);
804     Header.cmmId       = _cmsAdjustEndianess32(lcmsSignature);
805     Header.version     = _cmsAdjustEndianess32(Icc ->Version);
806 
807     Header.deviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Icc -> DeviceClass);
808     Header.colorSpace  = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> ColorSpace);
809     Header.pcs         = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Icc -> PCS);
810 
811     //   NOTE: in v4 Timestamp must be in UTC rather than in local time
812     _cmsEncodeDateTimeNumber(&Header.date, &Icc ->Created);
813 
814     Header.magic       = _cmsAdjustEndianess32(cmsMagicNumber);
815 
816 #ifdef CMS_IS_WINDOWS_
817     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMicrosoft);
818 #else
819     Header.platform    = (cmsPlatformSignature) _cmsAdjustEndianess32(cmsSigMacintosh);
820 #endif
821 
822     Header.flags        = _cmsAdjustEndianess32(Icc -> flags);
823     Header.manufacturer = _cmsAdjustEndianess32(Icc -> manufacturer);
824     Header.model        = _cmsAdjustEndianess32(Icc -> model);
825 
826     _cmsAdjustEndianess64(&Header.attributes, &Icc -> attributes);
827 
828     // Rendering intent in the header (for embedded profiles)
829     Header.renderingIntent = _cmsAdjustEndianess32(Icc -> RenderingIntent);
830 
831     // Illuminant is always D50
832     Header.illuminant.X = (cmsS15Fixed16Number) _cmsAdjustEndianess32((cmsUInt32Number) _cmsDoubleTo15Fixed16(cmsD50_XYZ()->X));
833     Header.illuminant.Y = (cmsS15Fixed16Number) _cmsAdjustEndianess32((cmsUInt32Number) _cmsDoubleTo15Fixed16(cmsD50_XYZ()->Y));
834     Header.illuminant.Z = (cmsS15Fixed16Number) _cmsAdjustEndianess32((cmsUInt32Number) _cmsDoubleTo15Fixed16(cmsD50_XYZ()->Z));
835 
836     // Created by LittleCMS (that's me!)
837     Header.creator      = _cmsAdjustEndianess32(lcmsSignature);
838 
839     memset(&Header.reserved, 0, sizeof(Header.reserved));
840 
841     // Set profile ID. Endianness is always big endian
842     memmove(&Header.profileID, &Icc ->ProfileID, 16);
843 
844     // Dump the header
845     if (!Icc -> IOhandler->Write(Icc->IOhandler, sizeof(cmsICCHeader), &Header)) return FALSE;
846 
847     // Saves Tag directory
848 
849     // Get true count
850     Count = 0;
851     for (i=0;  i < Icc -> TagCount; i++) {
852         if (Icc ->TagNames[i] != (cmsTagSignature) 0)
853             Count++;
854     }
855 
856     // Store number of tags
857     if (!_cmsWriteUInt32Number(Icc ->IOhandler, Count)) return FALSE;
858 
859     for (i=0; i < Icc -> TagCount; i++) {
860 
861         if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;   // It is just a placeholder
862 
863         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsUInt32Number) Icc -> TagNames[i]);
864         Tag.offset = _cmsAdjustEndianess32((cmsUInt32Number) Icc -> TagOffsets[i]);
865         Tag.size   = _cmsAdjustEndianess32((cmsUInt32Number) Icc -> TagSizes[i]);
866 
867         if (!Icc ->IOhandler -> Write(Icc-> IOhandler, sizeof(cmsTagEntry), &Tag)) return FALSE;
868     }
869 
870     return TRUE;
871 }
872 
873 // ----------------------------------------------------------------------- Set/Get several struct members
874 
875 
cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)876 cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProfile)
877 {
878     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
879     return Icc -> RenderingIntent;
880 }
881 
cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile,cmsUInt32Number RenderingIntent)882 void CMSEXPORT cmsSetHeaderRenderingIntent(cmsHPROFILE hProfile, cmsUInt32Number RenderingIntent)
883 {
884     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
885     Icc -> RenderingIntent = RenderingIntent;
886 }
887 
cmsGetHeaderFlags(cmsHPROFILE hProfile)888 cmsUInt32Number CMSEXPORT cmsGetHeaderFlags(cmsHPROFILE hProfile)
889 {
890     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
891     return (cmsUInt32Number) Icc -> flags;
892 }
893 
cmsSetHeaderFlags(cmsHPROFILE hProfile,cmsUInt32Number Flags)894 void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
895 {
896     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
897     Icc -> flags = (cmsUInt32Number) Flags;
898 }
899 
cmsGetHeaderManufacturer(cmsHPROFILE hProfile)900 cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
901 {
902     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
903     return Icc ->manufacturer;
904 }
905 
cmsSetHeaderManufacturer(cmsHPROFILE hProfile,cmsUInt32Number manufacturer)906 void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
907 {
908     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
909     Icc -> manufacturer = manufacturer;
910 }
911 
cmsGetHeaderCreator(cmsHPROFILE hProfile)912 cmsUInt32Number CMSEXPORT cmsGetHeaderCreator(cmsHPROFILE hProfile)
913 {
914     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
915     return Icc ->creator;
916 }
917 
cmsGetHeaderModel(cmsHPROFILE hProfile)918 cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
919 {
920     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
921     return Icc ->model;
922 }
923 
cmsSetHeaderModel(cmsHPROFILE hProfile,cmsUInt32Number model)924 void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
925 {
926     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
927     Icc -> model = model;
928 }
929 
cmsGetHeaderAttributes(cmsHPROFILE hProfile,cmsUInt64Number * Flags)930 void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
931 {
932     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
933     memmove(Flags, &Icc -> attributes, sizeof(cmsUInt64Number));
934 }
935 
cmsSetHeaderAttributes(cmsHPROFILE hProfile,cmsUInt64Number Flags)936 void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags)
937 {
938     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
939     memmove(&Icc -> attributes, &Flags, sizeof(cmsUInt64Number));
940 }
941 
cmsGetHeaderProfileID(cmsHPROFILE hProfile,cmsUInt8Number * ProfileID)942 void CMSEXPORT cmsGetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
943 {
944     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
945     memmove(ProfileID, Icc ->ProfileID.ID8, 16);
946 }
947 
cmsSetHeaderProfileID(cmsHPROFILE hProfile,cmsUInt8Number * ProfileID)948 void CMSEXPORT cmsSetHeaderProfileID(cmsHPROFILE hProfile, cmsUInt8Number* ProfileID)
949 {
950     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
951     memmove(&Icc -> ProfileID, ProfileID, 16);
952 }
953 
cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile,struct tm * Dest)954 cmsBool  CMSEXPORT cmsGetHeaderCreationDateTime(cmsHPROFILE hProfile, struct tm *Dest)
955 {
956     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
957     memmove(Dest, &Icc ->Created, sizeof(struct tm));
958     return TRUE;
959 }
960 
cmsGetPCS(cmsHPROFILE hProfile)961 cmsColorSpaceSignature CMSEXPORT cmsGetPCS(cmsHPROFILE hProfile)
962 {
963     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
964     return Icc -> PCS;
965 }
966 
cmsSetPCS(cmsHPROFILE hProfile,cmsColorSpaceSignature pcs)967 void CMSEXPORT cmsSetPCS(cmsHPROFILE hProfile, cmsColorSpaceSignature pcs)
968 {
969     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
970     Icc -> PCS = pcs;
971 }
972 
cmsGetColorSpace(cmsHPROFILE hProfile)973 cmsColorSpaceSignature CMSEXPORT cmsGetColorSpace(cmsHPROFILE hProfile)
974 {
975     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
976     return Icc -> ColorSpace;
977 }
978 
cmsSetColorSpace(cmsHPROFILE hProfile,cmsColorSpaceSignature sig)979 void CMSEXPORT cmsSetColorSpace(cmsHPROFILE hProfile, cmsColorSpaceSignature sig)
980 {
981     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
982     Icc -> ColorSpace = sig;
983 }
984 
cmsGetDeviceClass(cmsHPROFILE hProfile)985 cmsProfileClassSignature CMSEXPORT cmsGetDeviceClass(cmsHPROFILE hProfile)
986 {
987     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
988     return Icc -> DeviceClass;
989 }
990 
cmsSetDeviceClass(cmsHPROFILE hProfile,cmsProfileClassSignature sig)991 void CMSEXPORT cmsSetDeviceClass(cmsHPROFILE hProfile, cmsProfileClassSignature sig)
992 {
993     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
994     Icc -> DeviceClass = sig;
995 }
996 
cmsGetEncodedICCversion(cmsHPROFILE hProfile)997 cmsUInt32Number CMSEXPORT cmsGetEncodedICCversion(cmsHPROFILE hProfile)
998 {
999     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1000     return Icc -> Version;
1001 }
1002 
cmsSetEncodedICCversion(cmsHPROFILE hProfile,cmsUInt32Number Version)1003 void CMSEXPORT cmsSetEncodedICCversion(cmsHPROFILE hProfile, cmsUInt32Number Version)
1004 {
1005     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1006     Icc -> Version = Version;
1007 }
1008 
1009 // Get an hexadecimal number with same digits as v
1010 static
BaseToBase(cmsUInt32Number in,int BaseIn,int BaseOut)1011 cmsUInt32Number BaseToBase(cmsUInt32Number in, int BaseIn, int BaseOut)
1012 {
1013     char Buff[100];
1014     int i, len;
1015     cmsUInt32Number out;
1016 
1017     for (len=0; in > 0 && len < 100; len++) {
1018 
1019         Buff[len] = (char) (in % BaseIn);
1020         in /= BaseIn;
1021     }
1022 
1023     for (i=len-1, out=0; i >= 0; --i) {
1024         out = out * BaseOut + Buff[i];
1025     }
1026 
1027     return out;
1028 }
1029 
cmsSetProfileVersion(cmsHPROFILE hProfile,cmsFloat64Number Version)1030 void  CMSEXPORT cmsSetProfileVersion(cmsHPROFILE hProfile, cmsFloat64Number Version)
1031 {
1032     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1033 
1034     // 4.2 -> 0x4200000
1035 
1036     Icc -> Version = BaseToBase((cmsUInt32Number) floor(Version * 100.0 + 0.5), 10, 16) << 16;
1037 }
1038 
cmsGetProfileVersion(cmsHPROFILE hProfile)1039 cmsFloat64Number CMSEXPORT cmsGetProfileVersion(cmsHPROFILE hProfile)
1040 {
1041     _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) hProfile;
1042     cmsUInt32Number n = Icc -> Version >> 16;
1043 
1044     return BaseToBase(n, 16, 10) / 100.0;
1045 }
1046 // --------------------------------------------------------------------------------------------------------------
1047 
1048 
1049 // Create profile from IOhandler
cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID,cmsIOHANDLER * io)1050 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandlerTHR(cmsContext ContextID, cmsIOHANDLER* io)
1051 {
1052     _cmsICCPROFILE* NewIcc;
1053     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1054 
1055     if (hEmpty == NULL) return NULL;
1056 
1057     NewIcc = (_cmsICCPROFILE*) hEmpty;
1058 
1059     NewIcc ->IOhandler = io;
1060     if (!_cmsReadHeader(NewIcc)) goto Error;
1061     return hEmpty;
1062 
1063 Error:
1064     cmsCloseProfile(hEmpty);
1065     return NULL;
1066 }
1067 
1068 // Create profile from IOhandler
cmsOpenProfileFromIOhandler2THR(cmsContext ContextID,cmsIOHANDLER * io,cmsBool write)1069 cmsHPROFILE CMSEXPORT cmsOpenProfileFromIOhandler2THR(cmsContext ContextID, cmsIOHANDLER* io, cmsBool write)
1070 {
1071     _cmsICCPROFILE* NewIcc;
1072     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1073 
1074     if (hEmpty == NULL) return NULL;
1075 
1076     NewIcc = (_cmsICCPROFILE*) hEmpty;
1077 
1078     NewIcc ->IOhandler = io;
1079     if (write) {
1080 
1081         NewIcc -> IsWrite = TRUE;
1082         return hEmpty;
1083     }
1084 
1085     if (!_cmsReadHeader(NewIcc)) goto Error;
1086     return hEmpty;
1087 
1088 Error:
1089     cmsCloseProfile(hEmpty);
1090     return NULL;
1091 }
1092 
1093 
1094 // Create profile from disk file
cmsOpenProfileFromFileTHR(cmsContext ContextID,const char * lpFileName,const char * sAccess)1095 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFileTHR(cmsContext ContextID, const char *lpFileName, const char *sAccess)
1096 {
1097     _cmsICCPROFILE* NewIcc;
1098     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1099 
1100     if (hEmpty == NULL) return NULL;
1101 
1102     NewIcc = (_cmsICCPROFILE*) hEmpty;
1103 
1104     NewIcc ->IOhandler = cmsOpenIOhandlerFromFile(ContextID, lpFileName, sAccess);
1105     if (NewIcc ->IOhandler == NULL) goto Error;
1106 
1107     if (*sAccess == 'W' || *sAccess == 'w') {
1108 
1109         NewIcc -> IsWrite = TRUE;
1110 
1111         return hEmpty;
1112     }
1113 
1114     if (!_cmsReadHeader(NewIcc)) goto Error;
1115     return hEmpty;
1116 
1117 Error:
1118     cmsCloseProfile(hEmpty);
1119     return NULL;
1120 }
1121 
1122 
cmsOpenProfileFromFile(const char * ICCProfile,const char * sAccess)1123 cmsHPROFILE CMSEXPORT cmsOpenProfileFromFile(const char *ICCProfile, const char *sAccess)
1124 {
1125     return cmsOpenProfileFromFileTHR(NULL, ICCProfile, sAccess);
1126 }
1127 
1128 
cmsOpenProfileFromStreamTHR(cmsContext ContextID,FILE * ICCProfile,const char * sAccess)1129 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStreamTHR(cmsContext ContextID, FILE* ICCProfile, const char *sAccess)
1130 {
1131     _cmsICCPROFILE* NewIcc;
1132     cmsHPROFILE hEmpty = cmsCreateProfilePlaceholder(ContextID);
1133 
1134     if (hEmpty == NULL) return NULL;
1135 
1136     NewIcc = (_cmsICCPROFILE*) hEmpty;
1137 
1138     NewIcc ->IOhandler = cmsOpenIOhandlerFromStream(ContextID, ICCProfile);
1139     if (NewIcc ->IOhandler == NULL) goto Error;
1140 
1141     if (*sAccess == 'w') {
1142 
1143         NewIcc -> IsWrite = TRUE;
1144         return hEmpty;
1145     }
1146 
1147     if (!_cmsReadHeader(NewIcc)) goto Error;
1148     return hEmpty;
1149 
1150 Error:
1151     cmsCloseProfile(hEmpty);
1152     return NULL;
1153 
1154 }
1155 
cmsOpenProfileFromStream(FILE * ICCProfile,const char * sAccess)1156 cmsHPROFILE  CMSEXPORT cmsOpenProfileFromStream(FILE* ICCProfile, const char *sAccess)
1157 {
1158     return cmsOpenProfileFromStreamTHR(NULL, ICCProfile, sAccess);
1159 }
1160 
1161 
1162 // Open from memory block
cmsOpenProfileFromMemTHR(cmsContext ContextID,const void * MemPtr,cmsUInt32Number dwSize)1163 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMemTHR(cmsContext ContextID, const void* MemPtr, cmsUInt32Number dwSize)
1164 {
1165     _cmsICCPROFILE* NewIcc;
1166     cmsHPROFILE hEmpty;
1167 
1168     hEmpty = cmsCreateProfilePlaceholder(ContextID);
1169     if (hEmpty == NULL) return NULL;
1170 
1171     NewIcc = (_cmsICCPROFILE*) hEmpty;
1172 
1173     // Ok, in this case const void* is casted to void* just because open IO handler
1174     // shares read and writing modes. Don't abuse this feature!
1175     NewIcc ->IOhandler = cmsOpenIOhandlerFromMem(ContextID, (void*) MemPtr, dwSize, "r");
1176     if (NewIcc ->IOhandler == NULL) goto Error;
1177 
1178     if (!_cmsReadHeader(NewIcc)) goto Error;
1179 
1180     return hEmpty;
1181 
1182 Error:
1183     cmsCloseProfile(hEmpty);
1184     return NULL;
1185 }
1186 
cmsOpenProfileFromMem(const void * MemPtr,cmsUInt32Number dwSize)1187 cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number dwSize)
1188 {
1189     return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
1190 }
1191 
1192 
1193 
1194 // Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
1195 static
SaveTags(_cmsICCPROFILE * Icc,_cmsICCPROFILE * FileOrig)1196 cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
1197 {
1198     cmsUInt8Number* Data;
1199     cmsUInt32Number i;
1200     cmsUInt32Number Begin;
1201     cmsIOHANDLER* io = Icc ->IOhandler;
1202     cmsTagDescriptor* TagDescriptor;
1203     cmsTagTypeSignature TypeBase;
1204     cmsTagTypeSignature Type;
1205     cmsTagTypeHandler* TypeHandler;
1206     cmsFloat64Number   Version = cmsGetProfileVersion((cmsHPROFILE) Icc);
1207     cmsTagTypeHandler LocalTypeHandler;
1208 
1209     for (i=0; i < Icc -> TagCount; i++) {
1210 
1211         if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;
1212 
1213         // Linked tags are not written
1214         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
1215 
1216         Icc -> TagOffsets[i] = Begin = io ->UsedSpace;
1217 
1218         Data = (cmsUInt8Number*)  Icc -> TagPtrs[i];
1219 
1220         if (!Data) {
1221 
1222             // Reach here if we are copying a tag from a disk-based ICC profile which has not been modified by user.
1223             // In this case a blind copy of the block data is performed
1224             if (FileOrig != NULL && Icc -> TagOffsets[i]) {
1225 
1226                 cmsUInt32Number TagSize   = FileOrig -> TagSizes[i];
1227                 cmsUInt32Number TagOffset = FileOrig -> TagOffsets[i];
1228                 void* Mem;
1229 
1230                 if (!FileOrig ->IOhandler->Seek(FileOrig ->IOhandler, TagOffset)) return FALSE;
1231 
1232                 Mem = _cmsMalloc(Icc ->ContextID, TagSize);
1233                 if (Mem == NULL) return FALSE;
1234 
1235                 if (FileOrig ->IOhandler->Read(FileOrig->IOhandler, Mem, TagSize, 1) != 1) return FALSE;
1236                 if (!io ->Write(io, TagSize, Mem)) return FALSE;
1237                 _cmsFree(Icc ->ContextID, Mem);
1238 
1239                 Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1240 
1241 
1242                 // Align to 32 bit boundary.
1243                 if (! _cmsWriteAlignment(io))
1244                     return FALSE;
1245             }
1246 
1247             continue;
1248         }
1249 
1250 
1251         // Should this tag be saved as RAW? If so, tagsizes should be specified in advance (no further cooking is done)
1252         if (Icc ->TagSaveAsRaw[i]) {
1253 
1254             if (io -> Write(io, Icc ->TagSizes[i], Data) != 1) return FALSE;
1255         }
1256         else {
1257 
1258             // Search for support on this tag
1259             TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, Icc -> TagNames[i]);
1260             if (TagDescriptor == NULL) continue;                        // Unsupported, ignore it
1261 
1262             if (TagDescriptor ->DecideType != NULL) {
1263 
1264                 Type = TagDescriptor ->DecideType(Version, Data);
1265             }
1266             else {
1267 
1268                 Type = TagDescriptor ->SupportedTypes[0];
1269             }
1270 
1271             TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1272 
1273             if (TypeHandler == NULL) {
1274                 cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
1275                 continue;
1276             }
1277 
1278             TypeBase = TypeHandler ->Signature;
1279             if (!_cmsWriteTypeBase(io, TypeBase))
1280                 return FALSE;
1281 
1282             LocalTypeHandler = *TypeHandler;
1283             LocalTypeHandler.ContextID  = Icc ->ContextID;
1284             LocalTypeHandler.ICCVersion = Icc ->Version;
1285             if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, io, Data, TagDescriptor ->ElemCount)) {
1286 
1287                 char String[5];
1288 
1289                 _cmsTagSignature2String(String, (cmsTagSignature) TypeBase);
1290                 cmsSignalError(Icc ->ContextID, cmsERROR_WRITE, "Couldn't write type '%s'", String);
1291                 return FALSE;
1292             }
1293         }
1294 
1295 
1296         Icc -> TagSizes[i] = (io ->UsedSpace - Begin);
1297 
1298         // Align to 32 bit boundary.
1299         if (! _cmsWriteAlignment(io))
1300             return FALSE;
1301     }
1302 
1303 
1304     return TRUE;
1305 }
1306 
1307 
1308 // Fill the offset and size fields for all linked tags
1309 static
SetLinks(_cmsICCPROFILE * Icc)1310 cmsBool SetLinks( _cmsICCPROFILE* Icc)
1311 {
1312     cmsUInt32Number i;
1313 
1314     for (i=0; i < Icc -> TagCount; i++) {
1315 
1316         cmsTagSignature lnk = Icc ->TagLinked[i];
1317         if (lnk != (cmsTagSignature) 0) {
1318 
1319             int j = _cmsSearchTag(Icc, lnk, FALSE);
1320             if (j >= 0) {
1321 
1322                 Icc ->TagOffsets[i] = Icc ->TagOffsets[j];
1323                 Icc ->TagSizes[i]   = Icc ->TagSizes[j];
1324             }
1325 
1326         }
1327     }
1328 
1329     return TRUE;
1330 }
1331 
1332 // Low-level save to IOHANDLER. It returns the number of bytes used to
1333 // store the profile, or zero on error. io may be NULL and in this case
1334 // no data is written--only sizes are calculated
cmsSaveProfileToIOhandler(cmsHPROFILE hProfile,cmsIOHANDLER * io)1335 cmsUInt32Number CMSEXPORT cmsSaveProfileToIOhandler(cmsHPROFILE hProfile, cmsIOHANDLER* io)
1336 {
1337     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1338     _cmsICCPROFILE Keep;
1339     cmsIOHANDLER* PrevIO = NULL;
1340     cmsUInt32Number UsedSpace;
1341     cmsContext ContextID;
1342 
1343     _cmsAssert(hProfile != NULL);
1344 
1345     if (!_cmsLockMutex(Icc->ContextID, Icc->UsrMutex)) return 0;
1346     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
1347 
1348     ContextID = cmsGetProfileContextID(hProfile);
1349     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
1350     if (PrevIO == NULL) {
1351         _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1352         return 0;
1353     }
1354 
1355     // Pass #1 does compute offsets
1356 
1357     if (!_cmsWriteHeader(Icc, 0)) goto Error;
1358     if (!SaveTags(Icc, &Keep)) goto Error;
1359 
1360     UsedSpace = PrevIO ->UsedSpace;
1361 
1362     // Pass #2 does save to iohandler
1363 
1364     if (io != NULL) {
1365 
1366         Icc ->IOhandler = io;
1367         if (!SetLinks(Icc)) goto Error;
1368         if (!_cmsWriteHeader(Icc, UsedSpace)) goto Error;
1369         if (!SaveTags(Icc, &Keep)) goto Error;
1370     }
1371 
1372     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1373     if (!cmsCloseIOhandler(PrevIO))
1374         UsedSpace = 0; // As a error marker
1375 
1376     _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1377 
1378     return UsedSpace;
1379 
1380 
1381 Error:
1382     cmsCloseIOhandler(PrevIO);
1383     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
1384     _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
1385 
1386     return 0;
1387 }
1388 
1389 #ifdef _WIN32_WCE
1390 int wceex_unlink(const char *filename);
1391 #ifndef remove
1392 #   define remove wceex_unlink
1393 #endif
1394 #endif
1395 
1396 // Low-level save to disk.
cmsSaveProfileToFile(cmsHPROFILE hProfile,const char * FileName)1397 cmsBool  CMSEXPORT cmsSaveProfileToFile(cmsHPROFILE hProfile, const char* FileName)
1398 {
1399     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1400     cmsIOHANDLER* io = cmsOpenIOhandlerFromFile(ContextID, FileName, "w");
1401     cmsBool rc;
1402 
1403     if (io == NULL) return FALSE;
1404 
1405     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1406     rc &= cmsCloseIOhandler(io);
1407 
1408     if (rc == FALSE) {          // remove() is C99 per 7.19.4.1
1409             remove(FileName);   // We have to IGNORE return value in this case
1410     }
1411     return rc;
1412 }
1413 
1414 // Same as anterior, but for streams
cmsSaveProfileToStream(cmsHPROFILE hProfile,FILE * Stream)1415 cmsBool CMSEXPORT cmsSaveProfileToStream(cmsHPROFILE hProfile, FILE* Stream)
1416 {
1417     cmsBool rc;
1418     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1419     cmsIOHANDLER* io = cmsOpenIOhandlerFromStream(ContextID, Stream);
1420 
1421     if (io == NULL) return FALSE;
1422 
1423     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1424     rc &= cmsCloseIOhandler(io);
1425 
1426     return rc;
1427 }
1428 
1429 
1430 // 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)1431 cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUInt32Number* BytesNeeded)
1432 {
1433     cmsBool rc;
1434     cmsIOHANDLER* io;
1435     cmsContext ContextID = cmsGetProfileContextID(hProfile);
1436 
1437     _cmsAssert(BytesNeeded != NULL);
1438 
1439     // Should we just calculate the needed space?
1440     if (MemPtr == NULL) {
1441 
1442            *BytesNeeded =  cmsSaveProfileToIOhandler(hProfile, NULL);
1443             return (*BytesNeeded == 0) ? FALSE : TRUE;
1444     }
1445 
1446     // That is a real write operation
1447     io =  cmsOpenIOhandlerFromMem(ContextID, MemPtr, *BytesNeeded, "w");
1448     if (io == NULL) return FALSE;
1449 
1450     rc = (cmsSaveProfileToIOhandler(hProfile, io) != 0);
1451     rc &= cmsCloseIOhandler(io);
1452 
1453     return rc;
1454 }
1455 
1456 
1457 
1458 // Closes a profile freeing any involved resources
cmsCloseProfile(cmsHPROFILE hProfile)1459 cmsBool  CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
1460 {
1461     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1462     cmsBool  rc = TRUE;
1463     cmsUInt32Number i;
1464 
1465     if (!Icc) return FALSE;
1466 
1467     // Was open in write mode?
1468     if (Icc ->IsWrite) {
1469 
1470         Icc ->IsWrite = FALSE;      // Assure no further writing
1471         rc &= cmsSaveProfileToFile(hProfile, Icc ->IOhandler->PhysicalFile);
1472     }
1473 
1474     for (i=0; i < Icc -> TagCount; i++) {
1475 
1476         if (Icc -> TagPtrs[i]) {
1477 
1478             cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
1479 
1480             if (TypeHandler != NULL) {
1481                 cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
1482 
1483                 LocalTypeHandler.ContextID = Icc ->ContextID;              // As an additional parameters
1484                 LocalTypeHandler.ICCVersion = Icc ->Version;
1485                 LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
1486             }
1487             else
1488                 _cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
1489         }
1490     }
1491 
1492     if (Icc ->IOhandler != NULL) {
1493         rc &= cmsCloseIOhandler(Icc->IOhandler);
1494     }
1495 
1496     _cmsDestroyMutex(Icc->ContextID, Icc->UsrMutex);
1497 
1498     _cmsFree(Icc ->ContextID, Icc);   // Free placeholder memory
1499 
1500     return rc;
1501 }
1502 
1503 
1504 // -------------------------------------------------------------------------------------------------------------------
1505 
1506 
1507 // Returns TRUE if a given tag is supported by a plug-in
1508 static
IsTypeSupported(cmsTagDescriptor * TagDescriptor,cmsTagTypeSignature Type)1509 cmsBool IsTypeSupported(cmsTagDescriptor* TagDescriptor, cmsTagTypeSignature Type)
1510 {
1511     cmsUInt32Number i, nMaxTypes;
1512 
1513     nMaxTypes = TagDescriptor->nSupportedTypes;
1514     if (nMaxTypes >= MAX_TYPES_IN_LCMS_PLUGIN)
1515         nMaxTypes = MAX_TYPES_IN_LCMS_PLUGIN;
1516 
1517     for (i=0; i < nMaxTypes; i++) {
1518         if (Type == TagDescriptor ->SupportedTypes[i]) return TRUE;
1519     }
1520 
1521     return FALSE;
1522 }
1523 
1524 
1525 // That's the main read function
cmsReadTag(cmsHPROFILE hProfile,cmsTagSignature sig)1526 void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
1527 {
1528     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1529     cmsIOHANDLER* io = Icc ->IOhandler;
1530     cmsTagTypeHandler* TypeHandler;
1531     cmsTagTypeHandler LocalTypeHandler;
1532     cmsTagDescriptor*  TagDescriptor;
1533     cmsTagTypeSignature BaseType;
1534     cmsUInt32Number Offset, TagSize;
1535     cmsUInt32Number ElemCount;
1536     int n;
1537 
1538     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return NULL;
1539 
1540     n = _cmsSearchTag(Icc, sig, TRUE);
1541     if (n < 0) goto Error;               // Not found, return NULL
1542 
1543 
1544     // If the element is already in memory, return the pointer
1545     if (Icc -> TagPtrs[n]) {
1546 
1547         if (Icc->TagTypeHandlers[n] == NULL) goto Error;
1548 
1549         // Sanity check
1550         BaseType = Icc->TagTypeHandlers[n]->Signature;
1551         if (BaseType == 0) goto Error;
1552 
1553         TagDescriptor = _cmsGetTagDescriptor(Icc->ContextID, sig);
1554         if (TagDescriptor == NULL) goto Error;
1555 
1556         if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
1557 
1558         if (Icc ->TagSaveAsRaw[n]) goto Error;  // We don't support read raw tags as cooked
1559 
1560         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1561         return Icc -> TagPtrs[n];
1562     }
1563 
1564     // We need to read it. Get the offset and size to the file
1565     Offset    = Icc -> TagOffsets[n];
1566     TagSize   = Icc -> TagSizes[n];
1567 
1568     if (TagSize < 8) goto Error;
1569 
1570     // Seek to its location
1571     if (!io -> Seek(io, Offset))
1572         goto Error;
1573 
1574     // Search for support on this tag
1575     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1576     if (TagDescriptor == NULL) {
1577 
1578         char String[5];
1579 
1580         _cmsTagSignature2String(String, sig);
1581 
1582         // An unknown element was found.
1583         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown tag type '%s' found.", String);
1584         goto Error;     // Unsupported.
1585     }
1586 
1587     // if supported, get type and check if in list
1588     BaseType = _cmsReadTypeBase(io);
1589     if (BaseType == 0) goto Error;
1590 
1591     if (!IsTypeSupported(TagDescriptor, BaseType)) goto Error;
1592 
1593     TagSize  -= 8;       // Alredy read by the type base logic
1594 
1595     // Get type handler
1596     TypeHandler = _cmsGetTagTypeHandler(Icc ->ContextID, BaseType);
1597     if (TypeHandler == NULL) goto Error;
1598     LocalTypeHandler = *TypeHandler;
1599 
1600 
1601     // Read the tag
1602     Icc -> TagTypeHandlers[n] = TypeHandler;
1603 
1604     LocalTypeHandler.ContextID = Icc ->ContextID;
1605     LocalTypeHandler.ICCVersion = Icc ->Version;
1606     Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
1607 
1608     // The tag type is supported, but something wrong happened and we cannot read the tag.
1609     // let know the user about this (although it is just a warning)
1610     if (Icc -> TagPtrs[n] == NULL) {
1611 
1612         char String[5];
1613 
1614         _cmsTagSignature2String(String, sig);
1615         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Corrupted tag '%s'", String);
1616         goto Error;
1617     }
1618 
1619     // This is a weird error that may be a symptom of something more serious, the number of
1620     // stored item is actually less than the number of required elements.
1621     if (ElemCount < TagDescriptor ->ElemCount) {
1622 
1623         char String[5];
1624 
1625         _cmsTagSignature2String(String, sig);
1626         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d",
1627             String, TagDescriptor ->ElemCount, ElemCount);
1628         goto Error;
1629     }
1630 
1631 
1632     // Return the data
1633     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1634     return Icc -> TagPtrs[n];
1635 
1636 
1637     // Return error and unlock tha data
1638 Error:
1639     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1640     return NULL;
1641 }
1642 
1643 
1644 // Get true type of data
_cmsGetTagTrueType(cmsHPROFILE hProfile,cmsTagSignature sig)1645 cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig)
1646 {
1647     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1648     cmsTagTypeHandler* TypeHandler;
1649     int n;
1650 
1651     // Search for given tag in ICC profile directory
1652     n = _cmsSearchTag(Icc, sig, TRUE);
1653     if (n < 0) return (cmsTagTypeSignature) 0;                // Not found, return NULL
1654 
1655     // Get the handler. The true type is there
1656     TypeHandler =  Icc -> TagTypeHandlers[n];
1657     return TypeHandler ->Signature;
1658 }
1659 
1660 
1661 // Write a single tag. This just keeps track of the tak into a list of "to be written". If the tag is already
1662 // in that list, the previous version is deleted.
cmsWriteTag(cmsHPROFILE hProfile,cmsTagSignature sig,const void * data)1663 cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data)
1664 {
1665     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1666     cmsTagTypeHandler* TypeHandler = NULL;
1667     cmsTagTypeHandler LocalTypeHandler;
1668     cmsTagDescriptor* TagDescriptor = NULL;
1669     cmsTagTypeSignature Type;
1670     int i;
1671     cmsFloat64Number Version;
1672     char TypeString[5], SigString[5];
1673 
1674     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1675 
1676     // To delete tags.
1677     if (data == NULL) {
1678 
1679          // Delete the tag
1680          i = _cmsSearchTag(Icc, sig, FALSE);
1681          if (i >= 0) {
1682 
1683              // Use zero as a mark of deleted
1684              _cmsDeleteTagByPos(Icc, i);
1685              Icc ->TagNames[i] = (cmsTagSignature) 0;
1686              _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1687              return TRUE;
1688          }
1689          // Didn't find the tag
1690         goto Error;
1691     }
1692 
1693     if (!_cmsNewTag(Icc, sig, &i)) goto Error;
1694 
1695     // This is not raw
1696     Icc ->TagSaveAsRaw[i] = FALSE;
1697 
1698     // This is not a link
1699     Icc ->TagLinked[i] = (cmsTagSignature) 0;
1700 
1701     // Get information about the TAG.
1702     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1703     if (TagDescriptor == NULL){
1704          cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag '%x'", sig);
1705         goto Error;
1706     }
1707 
1708 
1709     // Now we need to know which type to use. It depends on the version.
1710     Version = cmsGetProfileVersion(hProfile);
1711 
1712     if (TagDescriptor ->DecideType != NULL) {
1713 
1714         // Let the tag descriptor to decide the type base on depending on
1715         // the data. This is useful for example on parametric curves, where
1716         // curves specified by a table cannot be saved as parametric and needs
1717         // to be casted to single v2-curves, even on v4 profiles.
1718 
1719         Type = TagDescriptor ->DecideType(Version, data);
1720     }
1721     else {
1722 
1723         Type = TagDescriptor ->SupportedTypes[0];
1724     }
1725 
1726     // Does the tag support this type?
1727     if (!IsTypeSupported(TagDescriptor, Type)) {
1728 
1729         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1730         _cmsTagSignature2String(SigString,  sig);
1731 
1732         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1733         goto Error;
1734     }
1735 
1736     // Does we have a handler for this type?
1737     TypeHandler =  _cmsGetTagTypeHandler(Icc->ContextID, Type);
1738     if (TypeHandler == NULL) {
1739 
1740         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1741         _cmsTagSignature2String(SigString,  sig);
1742 
1743         cmsSignalError(Icc ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported type '%s' for tag '%s'", TypeString, SigString);
1744         goto Error;           // Should never happen
1745     }
1746 
1747 
1748     // Fill fields on icc structure
1749     Icc ->TagTypeHandlers[i]  = TypeHandler;
1750     Icc ->TagNames[i]         = sig;
1751     Icc ->TagSizes[i]         = 0;
1752     Icc ->TagOffsets[i]       = 0;
1753 
1754     LocalTypeHandler = *TypeHandler;
1755     LocalTypeHandler.ContextID  = Icc ->ContextID;
1756     LocalTypeHandler.ICCVersion = Icc ->Version;
1757     Icc ->TagPtrs[i]            = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
1758 
1759     if (Icc ->TagPtrs[i] == NULL)  {
1760 
1761         _cmsTagSignature2String(TypeString, (cmsTagSignature) Type);
1762         _cmsTagSignature2String(SigString,  sig);
1763         cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "Malformed struct in type '%s' for tag '%s'", TypeString, SigString);
1764 
1765         goto Error;
1766     }
1767 
1768     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1769     return TRUE;
1770 
1771 Error:
1772     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1773     return FALSE;
1774 
1775 }
1776 
1777 // Read and write raw data. The only way those function would work and keep consistence with normal read and write
1778 // is to do an additional step of serialization. That means, readRaw would issue a normal read and then convert the obtained
1779 // data to raw bytes by using the "write" serialization logic. And vice-versa. I know this may end in situations where
1780 // raw data written does not exactly correspond with the raw data proposed to cmsWriteRaw data, but this approach allows
1781 // to write a tag as raw data and the read it as handled.
1782 
cmsReadRawTag(cmsHPROFILE hProfile,cmsTagSignature sig,void * data,cmsUInt32Number BufferSize)1783 cmsUInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, void* data, cmsUInt32Number BufferSize)
1784 {
1785     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1786     void *Object;
1787     int i;
1788     cmsIOHANDLER* MemIO;
1789     cmsTagTypeHandler* TypeHandler = NULL;
1790     cmsTagTypeHandler LocalTypeHandler;
1791     cmsTagDescriptor* TagDescriptor = NULL;
1792     cmsUInt32Number rc;
1793     cmsUInt32Number Offset, TagSize;
1794 
1795     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1796 
1797     // Search for given tag in ICC profile directory
1798     i = _cmsSearchTag(Icc, sig, TRUE);
1799     if (i < 0) goto Error;                 // Not found,
1800 
1801     // It is already read?
1802     if (Icc -> TagPtrs[i] == NULL) {
1803 
1804         // No yet, get original position
1805         Offset   = Icc ->TagOffsets[i];
1806         TagSize  = Icc ->TagSizes[i];
1807 
1808         // read the data directly, don't keep copy
1809         if (data != NULL) {
1810 
1811             if (BufferSize < TagSize)
1812                 TagSize = BufferSize;
1813 
1814             if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) goto Error;
1815             if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) goto Error;
1816 
1817             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1818             return TagSize;
1819         }
1820 
1821         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1822         return Icc ->TagSizes[i];
1823     }
1824 
1825     // The data has been already read, or written. But wait!, maybe the user choosed to save as
1826     // raw data. In this case, return the raw data directly
1827     if (Icc ->TagSaveAsRaw[i]) {
1828 
1829         if (data != NULL)  {
1830 
1831             TagSize  = Icc ->TagSizes[i];
1832             if (BufferSize < TagSize)
1833                 TagSize = BufferSize;
1834 
1835             memmove(data, Icc ->TagPtrs[i], TagSize);
1836 
1837             _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1838             return TagSize;
1839         }
1840 
1841         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1842         return Icc ->TagSizes[i];
1843     }
1844 
1845     // Already readed, or previously set by cmsWriteTag(). We need to serialize that
1846     // data to raw in order to maintain consistency.
1847 
1848     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1849     Object = cmsReadTag(hProfile, sig);
1850     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1851 
1852     if (Object == NULL) goto Error;
1853 
1854     // Now we need to serialize to a memory block: just use a memory iohandler
1855 
1856     if (data == NULL) {
1857         MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
1858     } else{
1859         MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
1860     }
1861     if (MemIO == NULL) goto Error;
1862 
1863     // Obtain type handling for the tag
1864     TypeHandler = Icc ->TagTypeHandlers[i];
1865     TagDescriptor = _cmsGetTagDescriptor(Icc-> ContextID, sig);
1866     if (TagDescriptor == NULL) {
1867         cmsCloseIOhandler(MemIO);
1868         goto Error;
1869     }
1870 
1871     if (TypeHandler == NULL) goto Error;
1872 
1873     // Serialize
1874     LocalTypeHandler = *TypeHandler;
1875     LocalTypeHandler.ContextID  = Icc ->ContextID;
1876     LocalTypeHandler.ICCVersion = Icc ->Version;
1877 
1878     if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
1879         cmsCloseIOhandler(MemIO);
1880         goto Error;
1881     }
1882 
1883     if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
1884         cmsCloseIOhandler(MemIO);
1885         goto Error;
1886     }
1887 
1888     // Get Size and close
1889     rc = MemIO ->Tell(MemIO);
1890     cmsCloseIOhandler(MemIO);      // Ignore return code this time
1891 
1892     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1893     return rc;
1894 
1895 Error:
1896     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1897     return 0;
1898 }
1899 
1900 // Similar to the anterior. This function allows to write directly to the ICC profile any data, without
1901 // checking anything. As a rule, mixing Raw with cooked doesn't work, so writing a tag as raw and then reading
1902 // it as cooked without serializing does result into an error. If that is what you want, you will need to dump
1903 // the profile to memry or disk and then reopen it.
cmsWriteRawTag(cmsHPROFILE hProfile,cmsTagSignature sig,const void * data,cmsUInt32Number Size)1904 cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, const void* data, cmsUInt32Number Size)
1905 {
1906     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1907     int i;
1908 
1909     if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return 0;
1910 
1911     if (!_cmsNewTag(Icc, sig, &i)) {
1912         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1913          return FALSE;
1914     }
1915 
1916     // Mark the tag as being written as RAW
1917     Icc ->TagSaveAsRaw[i] = TRUE;
1918     Icc ->TagNames[i]     = sig;
1919     Icc ->TagLinked[i]    = (cmsTagSignature) 0;
1920 
1921     // Keep a copy of the block
1922     Icc ->TagPtrs[i]  = _cmsDupMem(Icc ->ContextID, data, Size);
1923     Icc ->TagSizes[i] = Size;
1924 
1925     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1926 
1927     if (Icc->TagPtrs[i] == NULL) {
1928            Icc->TagNames[i] = (cmsTagSignature) 0;
1929            return FALSE;
1930     }
1931     return TRUE;
1932 }
1933 
1934 // Using this function you can collapse several tag entries to the same block in the profile
cmsLinkTag(cmsHPROFILE hProfile,cmsTagSignature sig,cmsTagSignature dest)1935 cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
1936 {
1937     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1938     int i;
1939 
1940      if (!_cmsLockMutex(Icc->ContextID, Icc ->UsrMutex)) return FALSE;
1941 
1942     if (!_cmsNewTag(Icc, sig, &i)) {
1943         _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1944         return FALSE;
1945     }
1946 
1947     // Keep necessary information
1948     Icc ->TagSaveAsRaw[i] = FALSE;
1949     Icc ->TagNames[i]     = sig;
1950     Icc ->TagLinked[i]    = dest;
1951 
1952     Icc ->TagPtrs[i]    = NULL;
1953     Icc ->TagSizes[i]   = 0;
1954     Icc ->TagOffsets[i] = 0;
1955 
1956     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
1957     return TRUE;
1958 }
1959 
1960 
1961 // Returns the tag linked to sig, in the case two tags are sharing same resource
cmsTagLinkedTo(cmsHPROFILE hProfile,cmsTagSignature sig)1962 cmsTagSignature  CMSEXPORT cmsTagLinkedTo(cmsHPROFILE hProfile, cmsTagSignature sig)
1963 {
1964     _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
1965     int i;
1966 
1967     // Search for given tag in ICC profile directory
1968     i = _cmsSearchTag(Icc, sig, FALSE);
1969     if (i < 0) return (cmsTagSignature) 0;                 // Not found, return 0
1970 
1971     return Icc -> TagLinked[i];
1972 }
1973