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