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