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