1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2020 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 #include "lcms2_internal.h"
27 
28 #include "core/fxcrt/fx_memory.h"
29 #include "core/fxcrt/fx_system.h"
30 
31 // This function is here to help applications to prevent mixing lcms versions on header and shared objects.
cmsGetEncodedCMMversion(void)32 int CMSEXPORT cmsGetEncodedCMMversion(void)
33 {
34        return LCMS_VERSION;
35 }
36 
37 // I am so tired about incompatibilities on those functions that here are some replacements
38 // that hopefully would be fully portable.
39 
40 // compare two strings ignoring case
cmsstrcasecmp(const char * s1,const char * s2)41 int CMSEXPORT cmsstrcasecmp(const char* s1, const char* s2)
42 {
43     CMSREGISTER const unsigned char *us1 = (const unsigned char *)s1,
44                                  *us2 = (const unsigned char *)s2;
45 
46     while (toupper(*us1) == toupper(*us2++))
47         if (*us1++ == '\0')
48             return 0;
49 
50     return (toupper(*us1) - toupper(*--us2));
51 }
52 
53 // long int because C99 specifies ftell in such way (7.19.9.2)
cmsfilelength(FILE * f)54 long int CMSEXPORT cmsfilelength(FILE* f)
55 {
56     long int p , n;
57 
58     p = ftell(f); // register current file position
59     if (p == -1L)
60         return -1L;
61 
62     if (fseek(f, 0, SEEK_END) != 0) {
63         return -1L;
64     }
65 
66     n = ftell(f);
67     fseek(f, p, SEEK_SET); // file position restored
68 
69     return n;
70 }
71 
_cmsRegisterMemHandlerPlugin(cmsContext ContextID,cmsPluginBase * Plugin)72 cmsBool  _cmsRegisterMemHandlerPlugin(cmsContext ContextID, cmsPluginBase* Plugin)
73 {
74     return TRUE;
75 }
76 
77 // Generic allocate
_cmsMalloc(cmsContext ContextID,cmsUInt32Number size)78 void* CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size)
79 {
80     return FXMEM_DefaultAlloc(size);
81 }
82 
83 // Generic allocate & zero
_cmsMallocZero(cmsContext ContextID,cmsUInt32Number size)84 void* CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size)
85 {
86     void* p = FXMEM_DefaultAlloc(size);
87     if (p) memset(p, 0, size);
88     return p;
89 }
90 
91 // Generic calloc
_cmsCalloc(cmsContext ContextID,cmsUInt32Number num,cmsUInt32Number size)92 void* CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
93 {
94     cmsUInt32Number total = num * size;
95     if (total == 0 || total / size != num || total >= 512 * 1024 * 1024)
96         return NULL;
97 
98     return _cmsMallocZero(ContextID, num * size);
99 }
100 
101 // Generic reallocate
_cmsRealloc(cmsContext ContextID,void * Ptr,cmsUInt32Number size)102 void* CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
103 {
104     return FXMEM_DefaultRealloc(Ptr, size);
105 }
106 
107 // Generic free memory
_cmsFree(cmsContext ContextID,void * Ptr)108 void CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr)
109 {
110     if (Ptr != NULL) FXMEM_DefaultFree(Ptr);
111 }
112 
113 // Generic block duplication
_cmsDupMem(cmsContext ContextID,const void * Org,cmsUInt32Number size)114 void* CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size)
115 {
116     void* p = FXMEM_DefaultAlloc(size);
117     memmove(p, Org, size);
118     return p;
119 }
120 
121 _cmsMemPluginChunkType _cmsMemPluginChunk = {_cmsMalloc, _cmsMallocZero, _cmsFree,
122                                              _cmsRealloc, _cmsCalloc,    _cmsDupMem
123                                             };
124 
_cmsAllocMemPluginChunk(struct _cmsContext_struct * ctx,const struct _cmsContext_struct * src)125 void _cmsAllocMemPluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src)
126 {
127     _cmsAssert(ctx != NULL);
128 
129     if (src != NULL) {
130 
131         // Duplicate
132         ctx ->chunks[MemPlugin] = _cmsSubAllocDup(ctx ->MemPool, src ->chunks[MemPlugin], sizeof(_cmsMemPluginChunkType));
133     }
134     else {
135 
136         // To reset it, we use the default allocators, which cannot be overridden
137         ctx ->chunks[MemPlugin] = &ctx ->DefaultMemoryManager;
138     }
139 }
140 
_cmsInstallAllocFunctions(cmsPluginMemHandler * Plugin,_cmsMemPluginChunkType * ptr)141 void _cmsInstallAllocFunctions(cmsPluginMemHandler* Plugin, _cmsMemPluginChunkType* ptr)
142 {
143     if (Plugin == NULL) {
144 
145         memcpy(ptr, &_cmsMemPluginChunk, sizeof(_cmsMemPluginChunk));
146     }
147     else {
148 
149         ptr ->MallocPtr  = Plugin -> MallocPtr;
150         ptr ->FreePtr    = Plugin -> FreePtr;
151         ptr ->ReallocPtr = Plugin -> ReallocPtr;
152 
153         // Make sure we revert to defaults
154         ptr ->MallocZeroPtr= _cmsMallocZero;
155         ptr ->CallocPtr    = _cmsCalloc;
156         ptr ->DupPtr       = _cmsDupMem;
157 
158         if (Plugin ->MallocZeroPtr != NULL) ptr ->MallocZeroPtr = Plugin -> MallocZeroPtr;
159         if (Plugin ->CallocPtr != NULL)     ptr ->CallocPtr     = Plugin -> CallocPtr;
160         if (Plugin ->DupPtr != NULL)        ptr ->DupPtr        = Plugin -> DupPtr;
161 
162     }
163 }
164 
165 // ********************************************************************************************
166 
167 // Sub allocation takes care of many pointers of small size. The memory allocated in
168 // this way have be freed at once. Next function allocates a single chunk for linked list
169 // I prefer this method over realloc due to the big inpact on xput realloc may have if
170 // memory is being swapped to disk. This approach is safer (although that may not be true on all platforms)
171 static
_cmsCreateSubAllocChunk(cmsContext ContextID,cmsUInt32Number Initial)172 _cmsSubAllocator_chunk* _cmsCreateSubAllocChunk(cmsContext ContextID, cmsUInt32Number Initial)
173 {
174     _cmsSubAllocator_chunk* chunk;
175 
176     // 20K by default
177     if (Initial == 0)
178         Initial = 20*1024;
179 
180     // Create the container
181     chunk = (_cmsSubAllocator_chunk*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator_chunk));
182     if (chunk == NULL) return NULL;
183 
184     // Initialize values
185     chunk ->Block     = (cmsUInt8Number*) _cmsMalloc(ContextID, Initial);
186     if (chunk ->Block == NULL) {
187 
188         // Something went wrong
189         _cmsFree(ContextID, chunk);
190         return NULL;
191     }
192 
193     chunk ->BlockSize = Initial;
194     chunk ->Used      = 0;
195     chunk ->next      = NULL;
196 
197     return chunk;
198 }
199 
200 // The suballocated is nothing but a pointer to the first element in the list. We also keep
201 // the thread ID in this structure.
_cmsCreateSubAlloc(cmsContext ContextID,cmsUInt32Number Initial)202 _cmsSubAllocator* _cmsCreateSubAlloc(cmsContext ContextID, cmsUInt32Number Initial)
203 {
204     _cmsSubAllocator* sub;
205 
206     // Create the container
207     sub = (_cmsSubAllocator*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator));
208     if (sub == NULL) return NULL;
209 
210     sub ->ContextID = ContextID;
211 
212     sub ->h = _cmsCreateSubAllocChunk(ContextID, Initial);
213     if (sub ->h == NULL) {
214         _cmsFree(ContextID, sub);
215         return NULL;
216     }
217 
218     return sub;
219 }
220 
221 
222 // Get rid of whole linked list
_cmsSubAllocDestroy(_cmsSubAllocator * sub)223 void _cmsSubAllocDestroy(_cmsSubAllocator* sub)
224 {
225     _cmsSubAllocator_chunk *chunk, *n;
226 
227     for (chunk = sub ->h; chunk != NULL; chunk = n) {
228 
229         n = chunk->next;
230         if (chunk->Block != NULL) _cmsFree(sub ->ContextID, chunk->Block);
231         _cmsFree(sub ->ContextID, chunk);
232     }
233 
234     // Free the header
235     _cmsFree(sub ->ContextID, sub);
236 }
237 
238 
239 // Get a pointer to small memory block.
_cmsSubAlloc(_cmsSubAllocator * sub,cmsUInt32Number size)240 void*  _cmsSubAlloc(_cmsSubAllocator* sub, cmsUInt32Number size)
241 {
242     cmsUInt32Number Free = sub -> h ->BlockSize - sub -> h -> Used;
243     cmsUInt8Number* ptr;
244 
245     size = _cmsALIGNMEM(size);
246 
247     // Check for memory. If there is no room, allocate a new chunk of double memory size.
248     if (size > Free) {
249 
250         _cmsSubAllocator_chunk* chunk;
251         cmsUInt32Number newSize;
252 
253         newSize = sub -> h ->BlockSize * 2;
254         if (newSize < size) newSize = size;
255 
256         chunk = _cmsCreateSubAllocChunk(sub -> ContextID, newSize);
257         if (chunk == NULL) return NULL;
258 
259         // Link list
260         chunk ->next = sub ->h;
261         sub ->h    = chunk;
262 
263     }
264 
265     ptr =  sub -> h ->Block + sub -> h ->Used;
266     sub -> h -> Used += size;
267 
268     return (void*) ptr;
269 }
270 
271 // Duplicate in pool
_cmsSubAllocDup(_cmsSubAllocator * s,const void * ptr,cmsUInt32Number size)272 void* _cmsSubAllocDup(_cmsSubAllocator* s, const void *ptr, cmsUInt32Number size)
273 {
274     void *NewPtr;
275 
276     // Dup of null pointer is also NULL
277     if (ptr == NULL)
278         return NULL;
279 
280     NewPtr = _cmsSubAlloc(s, size);
281 
282     if (ptr != NULL && NewPtr != NULL) {
283         memcpy(NewPtr, ptr, size);
284     }
285 
286     return NewPtr;
287 }
288 
289 
290 
291 // Error logging ******************************************************************
292 
293 // There is no error handling at all. When a function fails, it returns proper value.
294 // For example, all create functions does return NULL on failure. Other return FALSE
295 // It may be interesting, for the developer, to know why the function is failing.
296 // for that reason, lcms2 does offer a logging function. This function does receive
297 // a ENGLISH string with some clues on what is going wrong. You can show this
298 // info to the end user, or just create some sort of log.
299 // The logging function should NOT terminate the program, as this obviously can leave
300 // resources. It is the programmer's responsibility to check each function return code
301 // to make sure it didn't fail.
302 
303 // Error messages are limited to MAX_ERROR_MESSAGE_LEN
304 
305 #define MAX_ERROR_MESSAGE_LEN   1024
306 
307 // ---------------------------------------------------------------------------------------------------------
308 
309 // This is our default log error
310 static void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text);
311 
312 // Context0 storage, which is global
313 _cmsLogErrorChunkType _cmsLogErrorChunk = { DefaultLogErrorHandlerFunction };
314 
315 // Allocates and inits error logger container for a given context. If src is NULL, only initializes the value
316 // to the default. Otherwise, it duplicates the value. The interface is standard across all context clients
_cmsAllocLogErrorChunk(struct _cmsContext_struct * ctx,const struct _cmsContext_struct * src)317 void _cmsAllocLogErrorChunk(struct _cmsContext_struct* ctx,
318                             const struct _cmsContext_struct* src)
319 {
320     static _cmsLogErrorChunkType LogErrorChunk = { DefaultLogErrorHandlerFunction };
321     void* from;
322 
323      if (src != NULL) {
324         from = src ->chunks[Logger];
325     }
326     else {
327        from = &LogErrorChunk;
328     }
329 
330     ctx ->chunks[Logger] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsLogErrorChunkType));
331 }
332 
333 // The default error logger does nothing.
334 static
DefaultLogErrorHandlerFunction(cmsContext ContextID,cmsUInt32Number ErrorCode,const char * Text)335 void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text)
336 {
337     // fprintf(stderr, "[lcms]: %s\n", Text);
338     // fflush(stderr);
339 
340      cmsUNUSED_PARAMETER(ContextID);
341      cmsUNUSED_PARAMETER(ErrorCode);
342      cmsUNUSED_PARAMETER(Text);
343 }
344 
345 // Change log error, context based
cmsSetLogErrorHandlerTHR(cmsContext ContextID,cmsLogErrorHandlerFunction Fn)346 void CMSEXPORT cmsSetLogErrorHandlerTHR(cmsContext ContextID, cmsLogErrorHandlerFunction Fn)
347 {
348     _cmsLogErrorChunkType* lhg = (_cmsLogErrorChunkType*) _cmsContextGetClientChunk(ContextID, Logger);
349 
350     if (lhg != NULL) {
351 
352         if (Fn == NULL)
353             lhg -> LogErrorHandler = DefaultLogErrorHandlerFunction;
354         else
355             lhg -> LogErrorHandler = Fn;
356     }
357 }
358 
359 // Change log error, legacy
cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn)360 void CMSEXPORT cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn)
361 {
362     cmsSetLogErrorHandlerTHR(NULL, Fn);
363 }
364 
365 // Log an error
366 // ErrorText is a text holding an english description of error.
cmsSignalError(cmsContext ContextID,cmsUInt32Number ErrorCode,const char * ErrorText,...)367 void CMSEXPORT cmsSignalError(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText, ...)
368 {
369     va_list args;
370     char Buffer[MAX_ERROR_MESSAGE_LEN];
371     _cmsLogErrorChunkType* lhg;
372 
373 
374     va_start(args, ErrorText);
375     vsnprintf(Buffer, MAX_ERROR_MESSAGE_LEN-1, ErrorText, args);
376     va_end(args);
377 
378     // Check for the context, if specified go there. If not, go for the global
379     lhg = (_cmsLogErrorChunkType*) _cmsContextGetClientChunk(ContextID, Logger);
380     if (lhg ->LogErrorHandler) {
381         lhg ->LogErrorHandler(ContextID, ErrorCode, Buffer);
382     }
383 }
384 
385 // Utility function to print signatures
_cmsTagSignature2String(char String[5],cmsTagSignature sig)386 void _cmsTagSignature2String(char String[5], cmsTagSignature sig)
387 {
388     cmsUInt32Number be;
389 
390     // Convert to big endian
391     be = _cmsAdjustEndianess32((cmsUInt32Number) sig);
392 
393     // Move chars
394     memmove(String, &be, 4);
395 
396     // Make sure of terminator
397     String[4] = 0;
398 }
399 
400 //--------------------------------------------------------------------------------------------------
401 
402 
403 static
defMtxCreate(cmsContext id)404 void* defMtxCreate(cmsContext id)
405 {
406     _cmsMutex* ptr_mutex = (_cmsMutex*) _cmsMalloc(id, sizeof(_cmsMutex));
407     _cmsInitMutexPrimitive(ptr_mutex);
408     return (void*) ptr_mutex;
409 }
410 
411 static
defMtxDestroy(cmsContext id,void * mtx)412 void defMtxDestroy(cmsContext id, void* mtx)
413 {
414     _cmsDestroyMutexPrimitive((_cmsMutex *) mtx);
415     _cmsFree(id, mtx);
416 }
417 
418 static
defMtxLock(cmsContext id,void * mtx)419 cmsBool defMtxLock(cmsContext id, void* mtx)
420 {
421     cmsUNUSED_PARAMETER(id);
422     return _cmsLockPrimitive((_cmsMutex *) mtx) == 0;
423 }
424 
425 static
defMtxUnlock(cmsContext id,void * mtx)426 void defMtxUnlock(cmsContext id, void* mtx)
427 {
428     cmsUNUSED_PARAMETER(id);
429     _cmsUnlockPrimitive((_cmsMutex *) mtx);
430 }
431 
432 
433 
434 // Pointers to memory manager functions in Context0
435 _cmsMutexPluginChunkType _cmsMutexPluginChunk = { defMtxCreate, defMtxDestroy, defMtxLock, defMtxUnlock };
436 
437 // Allocate and init mutex container.
_cmsAllocMutexPluginChunk(struct _cmsContext_struct * ctx,const struct _cmsContext_struct * src)438 void _cmsAllocMutexPluginChunk(struct _cmsContext_struct* ctx,
439                                         const struct _cmsContext_struct* src)
440 {
441     static _cmsMutexPluginChunkType MutexChunk = {defMtxCreate, defMtxDestroy, defMtxLock, defMtxUnlock };
442     void* from;
443 
444      if (src != NULL) {
445         from = src ->chunks[MutexPlugin];
446     }
447     else {
448        from = &MutexChunk;
449     }
450 
451     ctx ->chunks[MutexPlugin] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsMutexPluginChunkType));
452 }
453 
454 // Register new ways to transform
_cmsRegisterMutexPlugin(cmsContext ContextID,cmsPluginBase * Data)455 cmsBool  _cmsRegisterMutexPlugin(cmsContext ContextID, cmsPluginBase* Data)
456 {
457     cmsPluginMutex* Plugin = (cmsPluginMutex*) Data;
458     _cmsMutexPluginChunkType* ctx = ( _cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
459 
460     if (Data == NULL) {
461 
462         // No lock routines
463         ctx->CreateMutexPtr = NULL;
464         ctx->DestroyMutexPtr = NULL;
465         ctx->LockMutexPtr = NULL;
466         ctx ->UnlockMutexPtr = NULL;
467         return TRUE;
468     }
469 
470     // Factory callback is required
471     if (Plugin ->CreateMutexPtr == NULL || Plugin ->DestroyMutexPtr == NULL ||
472         Plugin ->LockMutexPtr == NULL || Plugin ->UnlockMutexPtr == NULL) return FALSE;
473 
474 
475     ctx->CreateMutexPtr  = Plugin->CreateMutexPtr;
476     ctx->DestroyMutexPtr = Plugin ->DestroyMutexPtr;
477     ctx ->LockMutexPtr   = Plugin ->LockMutexPtr;
478     ctx ->UnlockMutexPtr = Plugin ->UnlockMutexPtr;
479 
480     // All is ok
481     return TRUE;
482 }
483 
484 // Generic Mutex fns
_cmsCreateMutex(cmsContext ContextID)485 void* CMSEXPORT _cmsCreateMutex(cmsContext ContextID)
486 {
487     _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
488 
489     if (ptr ->CreateMutexPtr == NULL) return NULL;
490 
491     return ptr ->CreateMutexPtr(ContextID);
492 }
493 
_cmsDestroyMutex(cmsContext ContextID,void * mtx)494 void CMSEXPORT _cmsDestroyMutex(cmsContext ContextID, void* mtx)
495 {
496     _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
497 
498     if (ptr ->DestroyMutexPtr != NULL) {
499 
500         ptr ->DestroyMutexPtr(ContextID, mtx);
501     }
502 }
503 
_cmsLockMutex(cmsContext ContextID,void * mtx)504 cmsBool CMSEXPORT _cmsLockMutex(cmsContext ContextID, void* mtx)
505 {
506     _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
507 
508     if (ptr ->LockMutexPtr == NULL) return TRUE;
509 
510     return ptr ->LockMutexPtr(ContextID, mtx);
511 }
512 
_cmsUnlockMutex(cmsContext ContextID,void * mtx)513 void CMSEXPORT _cmsUnlockMutex(cmsContext ContextID, void* mtx)
514 {
515     _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
516 
517     if (ptr ->UnlockMutexPtr != NULL) {
518 
519         ptr ->UnlockMutexPtr(ContextID, mtx);
520     }
521 }
522