1 //---------------------------------------------------------------------------------
3 // Little Color Management System
4 // Copyright (c) 1998-2012 Marti Maria Saguer
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:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
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.
24 //---------------------------------------------------------------------------------
26 #include "lcms2_internal.h"
28 // I am so tired about incompatibilities on those functions that here are some replacements
29 // that hopefully would be fully portable.
31 // compare two strings ignoring case
32 int CMSEXPORT cmsstrcasecmp(const char* s1, const char* s2)
34 register const unsigned char *us1 = (const unsigned char *)s1,
35 *us2 = (const unsigned char *)s2;
37 while (toupper(*us1) == toupper(*us2++))
41 return (toupper(*us1) - toupper(*--us2));
44 // long int because C99 specifies ftell in such way (7.19.9.2)
45 long int CMSEXPORT cmsfilelength(FILE* f)
49 p = ftell(f); // register current file position
51 if (fseek(f, 0, SEEK_END) != 0) {
56 fseek(f, p, SEEK_SET); // file position restored
62 // Memory handling ------------------------------------------------------------------
64 // This is the interface to low-level memory management routines. By default a simple
65 // wrapping to malloc/free/realloc is provided, although there is a limit on the max
66 // amount of memoy that can be reclaimed. This is mostly as a safety feature to prevent
67 // bogus or evil code to allocate huge blocks that otherwise lcms would never need.
69 #define MAX_MEMORY_FOR_ALLOC ((cmsUInt32Number)(1024U*1024U*512U))
71 // User may override this behaviour by using a memory plug-in, which basically replaces
72 // the default memory management functions. In this case, no check is performed and it
73 // is up to the plug-in writter to keep in the safe side. There are only three functions
74 // required to be implemented: malloc, realloc and free, although the user may want to
75 // replace the optional mallocZero, calloc and dup as well.
77 cmsBool _cmsRegisterMemHandlerPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
79 // *********************************************************************************
81 // This is the default memory allocation function. It does a very coarse
82 // check of amout of memory, just to prevent exploits
84 void* _cmsMallocDefaultFn(cmsContext ContextID, cmsUInt32Number size)
86 if (size > MAX_MEMORY_FOR_ALLOC) return NULL; // Never allow over maximum
88 return (void*) malloc(size);
90 cmsUNUSED_PARAMETER(ContextID);
93 // Generic allocate & zero
95 void* _cmsMallocZeroDefaultFn(cmsContext ContextID, cmsUInt32Number size)
97 void *pt = _cmsMalloc(ContextID, size);
98 if (pt == NULL) return NULL;
105 // The default free function. The only check proformed is against NULL pointers
107 void _cmsFreeDefaultFn(cmsContext ContextID, void *Ptr)
109 // free(NULL) is defined a no-op by C99, therefore it is safe to
110 // avoid the check, but it is here just in case...
114 cmsUNUSED_PARAMETER(ContextID);
117 // The default realloc function. Again it checks for exploits. If Ptr is NULL,
118 // realloc behaves the same way as malloc and allocates a new block of size bytes.
120 void* _cmsReallocDefaultFn(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
123 if (size > MAX_MEMORY_FOR_ALLOC) return NULL; // Never realloc over 512Mb
125 return realloc(Ptr, size);
127 cmsUNUSED_PARAMETER(ContextID);
131 // The default calloc function. Allocates an array of num elements, each one of size bytes
132 // all memory is initialized to zero.
134 void* _cmsCallocDefaultFn(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
136 cmsUInt32Number Total = num * size;
138 // Preserve calloc behaviour
139 if (Total == 0) return NULL;
141 // Safe check for overflow.
142 if (num >= UINT_MAX / size) return NULL;
144 // Check for overflow
145 if (Total < num || Total < size) {
149 if (Total > MAX_MEMORY_FOR_ALLOC) return NULL; // Never alloc over 512Mb
151 return _cmsMallocZero(ContextID, Total);
154 // Generic block duplication
156 void* _cmsDupDefaultFn(cmsContext ContextID, const void* Org, cmsUInt32Number size)
160 if (size > MAX_MEMORY_FOR_ALLOC) return NULL; // Never dup over 512Mb
162 mem = _cmsMalloc(ContextID, size);
164 if (mem != NULL && Org != NULL)
165 memmove(mem, Org, size);
171 // Pointers to memory manager functions in Context0
172 _cmsMemPluginChunkType _cmsMemPluginChunk = { _cmsMallocDefaultFn, _cmsMallocZeroDefaultFn, _cmsFreeDefaultFn,
173 _cmsReallocDefaultFn, _cmsCallocDefaultFn, _cmsDupDefaultFn
177 // Reset and duplicate memory manager
178 void _cmsAllocMemPluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src)
180 _cmsAssert(ctx != NULL);
185 ctx ->chunks[MemPlugin] = _cmsSubAllocDup(ctx ->MemPool, src ->chunks[MemPlugin], sizeof(_cmsMemPluginChunkType));
189 // To reset it, we use the default allocators, which cannot be overriden
190 ctx ->chunks[MemPlugin] = &ctx ->DefaultMemoryManager;
194 // Auxiliar to fill memory management functions from plugin (or context 0 defaults)
195 void _cmsInstallAllocFunctions(cmsPluginMemHandler* Plugin, _cmsMemPluginChunkType* ptr)
197 if (Plugin == NULL) {
199 memcpy(ptr, &_cmsMemPluginChunk, sizeof(_cmsMemPluginChunk));
203 ptr ->MallocPtr = Plugin -> MallocPtr;
204 ptr ->FreePtr = Plugin -> FreePtr;
205 ptr ->ReallocPtr = Plugin -> ReallocPtr;
207 // Make sure we revert to defaults
208 ptr ->MallocZeroPtr= _cmsMallocZeroDefaultFn;
209 ptr ->CallocPtr = _cmsCallocDefaultFn;
210 ptr ->DupPtr = _cmsDupDefaultFn;
212 if (Plugin ->MallocZeroPtr != NULL) ptr ->MallocZeroPtr = Plugin -> MallocZeroPtr;
213 if (Plugin ->CallocPtr != NULL) ptr ->CallocPtr = Plugin -> CallocPtr;
214 if (Plugin ->DupPtr != NULL) ptr ->DupPtr = Plugin -> DupPtr;
220 // Plug-in replacement entry
221 cmsBool _cmsRegisterMemHandlerPlugin(cmsContext ContextID, cmsPluginBase *Data)
223 cmsPluginMemHandler* Plugin = (cmsPluginMemHandler*) Data;
224 _cmsMemPluginChunkType* ptr;
226 // NULL forces to reset to defaults. In this special case, the defaults are stored in the context structure.
227 // Remaining plug-ins does NOT have any copy in the context structure, but this is somehow special as the
228 // context internal data should be malloce'd by using those functions.
231 struct _cmsContext_struct* ctx = ( struct _cmsContext_struct*) ContextID;
233 // Return to the default allocators
234 if (ContextID != NULL) {
235 ctx->chunks[MemPlugin] = (void*) &ctx->DefaultMemoryManager;
240 // Check for required callbacks
241 if (Plugin -> MallocPtr == NULL ||
242 Plugin -> FreePtr == NULL ||
243 Plugin -> ReallocPtr == NULL) return FALSE;
245 // Set replacement functions
246 ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
250 _cmsInstallAllocFunctions(Plugin, ptr);
255 void* CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size)
257 _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
258 return ptr ->MallocPtr(ContextID, size);
261 // Generic allocate & zero
262 void* CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size)
264 _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
265 return ptr->MallocZeroPtr(ContextID, size);
269 void* CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
271 _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
272 return ptr->CallocPtr(ContextID, num, size);
275 // Generic reallocate
276 void* CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
278 _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
279 return ptr->ReallocPtr(ContextID, Ptr, size);
282 // Generic free memory
283 void CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr)
286 _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
287 ptr ->FreePtr(ContextID, Ptr);
291 // Generic block duplication
292 void* CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size)
294 _cmsMemPluginChunkType* ptr = (_cmsMemPluginChunkType*) _cmsContextGetClientChunk(ContextID, MemPlugin);
295 return ptr ->DupPtr(ContextID, Org, size);
298 // ********************************************************************************************
300 // Sub allocation takes care of many pointers of small size. The memory allocated in
301 // this way have be freed at once. Next function allocates a single chunk for linked list
302 // I prefer this method over realloc due to the big inpact on xput realloc may have if
303 // memory is being swapped to disk. This approach is safer (although that may not be true on all platforms)
305 _cmsSubAllocator_chunk* _cmsCreateSubAllocChunk(cmsContext ContextID, cmsUInt32Number Initial)
307 _cmsSubAllocator_chunk* chunk;
313 // Create the container
314 chunk = (_cmsSubAllocator_chunk*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator_chunk));
315 if (chunk == NULL) return NULL;
318 chunk ->Block = (cmsUInt8Number*) _cmsMalloc(ContextID, Initial);
319 if (chunk ->Block == NULL) {
321 // Something went wrong
322 _cmsFree(ContextID, chunk);
326 chunk ->BlockSize = Initial;
333 // The suballocated is nothing but a pointer to the first element in the list. We also keep
334 // the thread ID in this structure.
335 _cmsSubAllocator* _cmsCreateSubAlloc(cmsContext ContextID, cmsUInt32Number Initial)
337 _cmsSubAllocator* sub;
339 // Create the container
340 sub = (_cmsSubAllocator*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator));
341 if (sub == NULL) return NULL;
343 sub ->ContextID = ContextID;
345 sub ->h = _cmsCreateSubAllocChunk(ContextID, Initial);
346 if (sub ->h == NULL) {
347 _cmsFree(ContextID, sub);
355 // Get rid of whole linked list
356 void _cmsSubAllocDestroy(_cmsSubAllocator* sub)
358 _cmsSubAllocator_chunk *chunk, *n;
360 for (chunk = sub ->h; chunk != NULL; chunk = n) {
363 if (chunk->Block != NULL) _cmsFree(sub ->ContextID, chunk->Block);
364 _cmsFree(sub ->ContextID, chunk);
368 _cmsFree(sub ->ContextID, sub);
372 // Get a pointer to small memory block.
373 void* _cmsSubAlloc(_cmsSubAllocator* sub, cmsUInt32Number size)
375 cmsUInt32Number Free = sub -> h ->BlockSize - sub -> h -> Used;
378 size = _cmsALIGNMEM(size);
380 // Check for memory. If there is no room, allocate a new chunk of double memory size.
383 _cmsSubAllocator_chunk* chunk;
384 cmsUInt32Number newSize;
386 newSize = sub -> h ->BlockSize * 2;
387 if (newSize < size) newSize = size;
389 chunk = _cmsCreateSubAllocChunk(sub -> ContextID, newSize);
390 if (chunk == NULL) return NULL;
393 chunk ->next = sub ->h;
398 ptr = sub -> h ->Block + sub -> h ->Used;
399 sub -> h -> Used += size;
405 void* _cmsSubAllocDup(_cmsSubAllocator* s, const void *ptr, cmsUInt32Number size)
409 // Dup of null pointer is also NULL
413 NewPtr = _cmsSubAlloc(s, size);
415 if (ptr != NULL && NewPtr != NULL) {
416 memcpy(NewPtr, ptr, size);
424 // Error logging ******************************************************************
426 // There is no error handling at all. When a funtion fails, it returns proper value.
427 // For example, all create functions does return NULL on failure. Other return FALSE
428 // It may be interesting, for the developer, to know why the function is failing.
429 // for that reason, lcms2 does offer a logging function. This function does recive
430 // a ENGLISH string with some clues on what is going wrong. You can show this
431 // info to the end user, or just create some sort of log.
432 // The logging function should NOT terminate the program, as this obviously can leave
433 // resources. It is the programmer's responsability to check each function return code
434 // to make sure it didn't fail.
436 // Error messages are limited to MAX_ERROR_MESSAGE_LEN
438 #define MAX_ERROR_MESSAGE_LEN 1024
440 // ---------------------------------------------------------------------------------------------------------
442 // This is our default log error
443 static void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text);
445 // Context0 storage, which is global
446 _cmsLogErrorChunkType _cmsLogErrorChunk = { DefaultLogErrorHandlerFunction };
448 // Allocates and inits error logger container for a given context. If src is NULL, only initializes the value
449 // to the default. Otherwise, it duplicates the value. The interface is standard across all context clients
450 void _cmsAllocLogErrorChunk(struct _cmsContext_struct* ctx,
451 const struct _cmsContext_struct* src)
453 static _cmsLogErrorChunkType LogErrorChunk = { DefaultLogErrorHandlerFunction };
457 from = src ->chunks[Logger];
460 from = &LogErrorChunk;
463 ctx ->chunks[Logger] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsLogErrorChunkType));
466 // The default error logger does nothing.
468 void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text)
470 // fprintf(stderr, "[lcms]: %s\n", Text);
473 cmsUNUSED_PARAMETER(ContextID);
474 cmsUNUSED_PARAMETER(ErrorCode);
475 cmsUNUSED_PARAMETER(Text);
478 // Change log error, context based
479 void CMSEXPORT cmsSetLogErrorHandlerTHR(cmsContext ContextID, cmsLogErrorHandlerFunction Fn)
481 _cmsLogErrorChunkType* lhg = (_cmsLogErrorChunkType*) _cmsContextGetClientChunk(ContextID, Logger);
486 lhg -> LogErrorHandler = DefaultLogErrorHandlerFunction;
488 lhg -> LogErrorHandler = Fn;
492 // Change log error, legacy
493 void CMSEXPORT cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn)
495 cmsSetLogErrorHandlerTHR(NULL, Fn);
499 // ErrorText is a text holding an english description of error.
500 void CMSEXPORT cmsSignalError(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText, ...)
503 char Buffer[MAX_ERROR_MESSAGE_LEN];
504 _cmsLogErrorChunkType* lhg;
507 va_start(args, ErrorText);
508 vsnprintf(Buffer, MAX_ERROR_MESSAGE_LEN-1, ErrorText, args);
511 // Check for the context, if specified go there. If not, go for the global
512 lhg = (_cmsLogErrorChunkType*) _cmsContextGetClientChunk(ContextID, Logger);
513 if (lhg ->LogErrorHandler) {
514 lhg ->LogErrorHandler(ContextID, ErrorCode, Buffer);
518 // Utility function to print signatures
519 void _cmsTagSignature2String(char String[5], cmsTagSignature sig)
523 // Convert to big endian
524 be = _cmsAdjustEndianess32((cmsUInt32Number) sig);
527 memmove(String, &be, 4);
529 // Make sure of terminator
533 //--------------------------------------------------------------------------------------------------
537 void* defMtxCreate(cmsContext id)
539 _cmsMutex* ptr_mutex = (_cmsMutex*) _cmsMalloc(id, sizeof(_cmsMutex));
540 _cmsInitMutexPrimitive(ptr_mutex);
541 return (void*) ptr_mutex;
545 void defMtxDestroy(cmsContext id, void* mtx)
547 _cmsDestroyMutexPrimitive((_cmsMutex *) mtx);
552 cmsBool defMtxLock(cmsContext id, void* mtx)
554 cmsUNUSED_PARAMETER(id);
555 return _cmsLockPrimitive((_cmsMutex *) mtx) == 0;
559 void defMtxUnlock(cmsContext id, void* mtx)
561 cmsUNUSED_PARAMETER(id);
562 _cmsUnlockPrimitive((_cmsMutex *) mtx);
567 // Pointers to memory manager functions in Context0
568 _cmsMutexPluginChunkType _cmsMutexPluginChunk = { defMtxCreate, defMtxDestroy, defMtxLock, defMtxUnlock };
570 // Allocate and init mutex container.
571 void _cmsAllocMutexPluginChunk(struct _cmsContext_struct* ctx,
572 const struct _cmsContext_struct* src)
574 static _cmsMutexPluginChunkType MutexChunk = {defMtxCreate, defMtxDestroy, defMtxLock, defMtxUnlock };
578 from = src ->chunks[MutexPlugin];
584 ctx ->chunks[MutexPlugin] = _cmsSubAllocDup(ctx ->MemPool, from, sizeof(_cmsMutexPluginChunkType));
587 // Register new ways to transform
588 cmsBool _cmsRegisterMutexPlugin(cmsContext ContextID, cmsPluginBase* Data)
590 cmsPluginMutex* Plugin = (cmsPluginMutex*) Data;
591 _cmsMutexPluginChunkType* ctx = ( _cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
596 ctx->CreateMutexPtr = NULL;
597 ctx->DestroyMutexPtr = NULL;
598 ctx->LockMutexPtr = NULL;
599 ctx ->UnlockMutexPtr = NULL;
603 // Factory callback is required
604 if (Plugin ->CreateMutexPtr == NULL || Plugin ->DestroyMutexPtr == NULL ||
605 Plugin ->LockMutexPtr == NULL || Plugin ->UnlockMutexPtr == NULL) return FALSE;
608 ctx->CreateMutexPtr = Plugin->CreateMutexPtr;
609 ctx->DestroyMutexPtr = Plugin ->DestroyMutexPtr;
610 ctx ->LockMutexPtr = Plugin ->LockMutexPtr;
611 ctx ->UnlockMutexPtr = Plugin ->UnlockMutexPtr;
618 void* CMSEXPORT _cmsCreateMutex(cmsContext ContextID)
620 _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
622 if (ptr ->CreateMutexPtr == NULL) return NULL;
624 return ptr ->CreateMutexPtr(ContextID);
627 void CMSEXPORT _cmsDestroyMutex(cmsContext ContextID, void* mtx)
629 _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
631 if (ptr ->DestroyMutexPtr != NULL) {
633 ptr ->DestroyMutexPtr(ContextID, mtx);
637 cmsBool CMSEXPORT _cmsLockMutex(cmsContext ContextID, void* mtx)
639 _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
641 if (ptr ->LockMutexPtr == NULL) return TRUE;
643 return ptr ->LockMutexPtr(ContextID, mtx);
646 void CMSEXPORT _cmsUnlockMutex(cmsContext ContextID, void* mtx)
648 _cmsMutexPluginChunkType* ptr = (_cmsMutexPluginChunkType*) _cmsContextGetClientChunk(ContextID, MutexPlugin);
650 if (ptr ->UnlockMutexPtr != NULL) {
652 ptr ->UnlockMutexPtr(ContextID, mtx);