Coverage Report

Created: 2026-11-12 07:35

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