Coverage Report

Created: 2025-07-07 10:01

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