1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 // This file is available under and governed by the GNU General Public
  26 // License version 2 only, as published by the Free Software Foundation.
  27 // However, the following notice accompanied the original version of this
  28 // file:
  29 //
  30 //---------------------------------------------------------------------------------
  31 //
  32 //  Little Color Management System
  33 //  Copyright (c) 1998-2012 Marti Maria Saguer
  34 //
  35 // Permission is hereby granted, free of charge, to any person obtaining
  36 // a copy of this software and associated documentation files (the "Software"),
  37 // to deal in the Software without restriction, including without limitation
  38 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  39 // and/or sell copies of the Software, and to permit persons to whom the Software
  40 // is furnished to do so, subject to the following conditions:
  41 //
  42 // The above copyright notice and this permission notice shall be included in
  43 // all copies or substantial portions of the Software.
  44 //
  45 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  46 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  47 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  48 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  49 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  50 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  51 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  52 //
  53 //---------------------------------------------------------------------------------
  54 
  55 #include "lcms2_internal.h"
  56 
  57 // I am so tired about incompatibilities on those functions that here are some replacements
  58 // that hopefully would be fully portable.
  59 
  60 // compare two strings ignoring case
  61 int CMSEXPORT cmsstrcasecmp(const char* s1, const char* s2)
  62 {
  63          register const unsigned char *us1 = (const unsigned char *)s1,
  64                                       *us2 = (const unsigned char *)s2;
  65 
  66         while (toupper(*us1) == toupper(*us2++))
  67                 if (*us1++ == '\0')
  68                         return (0);
  69         return (toupper(*us1) - toupper(*--us2));
  70 }
  71 
  72 // long int because C99 specifies ftell in such way (7.19.9.2)
  73 long int CMSEXPORT cmsfilelength(FILE* f)
  74 {
  75     long int p , n;
  76 
  77     p = ftell(f); // register current file position
  78 
  79     if (fseek(f, 0, SEEK_END) != 0) {
  80         return -1;
  81     }
  82 
  83     n = ftell(f);
  84     fseek(f, p, SEEK_SET); // file position restored
  85 
  86     return n;
  87 }
  88 
  89 
  90 // Memory handling ------------------------------------------------------------------
  91 //
  92 // This is the interface to low-level memory management routines. By default a simple
  93 // wrapping to malloc/free/realloc is provided, although there is a limit on the max
  94 // amount of memoy that can be reclaimed. This is mostly as a safety feature to
  95 // prevent bogus or malintentionated code to allocate huge blocks that otherwise lcms
  96 // would never need.
  97 
  98 #define MAX_MEMORY_FOR_ALLOC  ((cmsUInt32Number)(1024U*1024U*512U))
  99 
 100 // User may override this behaviour by using a memory plug-in, which basically replaces
 101 // the default memory management functions. In this case, no check is performed and it
 102 // is up to the plug-in writter to keep in the safe side. There are only three functions
 103 // required to be implemented: malloc, realloc and free, although the user may want to
 104 // replace the optional mallocZero, calloc and dup as well.
 105 
 106 cmsBool   _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
 107 
 108 // *********************************************************************************
 109 
 110 // This is the default memory allocation function. It does a very coarse
 111 // check of amout of memory, just to prevent exploits
 112 static
 113 void* _cmsMallocDefaultFn(cmsContext ContextID, cmsUInt32Number size)
 114 {
 115     if (size > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never allow over maximum
 116 
 117     return (void*) malloc(size);
 118 
 119     cmsUNUSED_PARAMETER(ContextID);
 120 }
 121 
 122 // Generic allocate & zero
 123 static
 124 void* _cmsMallocZeroDefaultFn(cmsContext ContextID, cmsUInt32Number size)
 125 {
 126     void *pt = _cmsMalloc(ContextID, size);
 127     if (pt == NULL) return NULL;
 128 
 129     memset(pt, 0, size);
 130     return pt;
 131 }
 132 
 133 
 134 // The default free function. The only check proformed is against NULL pointers
 135 static
 136 void _cmsFreeDefaultFn(cmsContext ContextID, void *Ptr)
 137 {
 138     // free(NULL) is defined a no-op by C99, therefore it is safe to
 139     // avoid the check, but it is here just in case...
 140 
 141     if (Ptr) free(Ptr);
 142 
 143     cmsUNUSED_PARAMETER(ContextID);
 144 }
 145 
 146 // The default realloc function. Again it check for exploits. If Ptr is NULL,
 147 // realloc behaves the same way as malloc and allocates a new block of size bytes.
 148 static
 149 void* _cmsReallocDefaultFn(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
 150 {
 151 
 152     if (size > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never realloc over 512Mb
 153 
 154     return realloc(Ptr, size);
 155 
 156     cmsUNUSED_PARAMETER(ContextID);
 157 }
 158 
 159 
 160 // The default calloc function. Allocates an array of num elements, each one of size bytes
 161 // all memory is initialized to zero.
 162 static
 163 void* _cmsCallocDefaultFn(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
 164 {
 165     cmsUInt32Number Total = num * size;
 166 
 167     // Preserve calloc behaviour
 168     if (Total == 0) return NULL;
 169 
 170     // Safe check for overflow.
 171     if (num >= UINT_MAX / size) return NULL;
 172 
 173     // Check for overflow
 174     if (Total < num || Total < size) {
 175         return NULL;
 176     }
 177 
 178     if (Total > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never alloc over 512Mb
 179 
 180     return _cmsMallocZero(ContextID, Total);
 181 }
 182 
 183 // Generic block duplication
 184 static
 185 void* _cmsDupDefaultFn(cmsContext ContextID, const void* Org, cmsUInt32Number size)
 186 {
 187     void* mem;
 188 
 189     if (size > MAX_MEMORY_FOR_ALLOC) return NULL;  // Never dup over 512Mb
 190 
 191     mem = _cmsMalloc(ContextID, size);
 192 
 193     if (mem != NULL && Org != NULL)
 194         memmove(mem, Org, size);
 195 
 196     return mem;
 197 }
 198 
 199 // Pointers to malloc and _cmsFree functions in current environment
 200 static void * (* MallocPtr)(cmsContext ContextID, cmsUInt32Number size)                     = _cmsMallocDefaultFn;
 201 static void * (* MallocZeroPtr)(cmsContext ContextID, cmsUInt32Number size)                 = _cmsMallocZeroDefaultFn;
 202 static void   (* FreePtr)(cmsContext ContextID, void *Ptr)                                  = _cmsFreeDefaultFn;
 203 static void * (* ReallocPtr)(cmsContext ContextID, void *Ptr, cmsUInt32Number NewSize)      = _cmsReallocDefaultFn;
 204 static void * (* CallocPtr)(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)= _cmsCallocDefaultFn;
 205 static void * (* DupPtr)(cmsContext ContextID, const void* Org, cmsUInt32Number size)       = _cmsDupDefaultFn;
 206 
 207 // Plug-in replacement entry
 208 cmsBool  _cmsRegisterMemHandlerPlugin(cmsPluginBase *Data)
 209 {
 210     cmsPluginMemHandler* Plugin = (cmsPluginMemHandler*) Data;
 211 
 212     // NULL forces to reset to defaults
 213     if (Data == NULL) {
 214 
 215         MallocPtr    = _cmsMallocDefaultFn;
 216         MallocZeroPtr= _cmsMallocZeroDefaultFn;
 217         FreePtr      = _cmsFreeDefaultFn;
 218         ReallocPtr   = _cmsReallocDefaultFn;
 219         CallocPtr    = _cmsCallocDefaultFn;
 220         DupPtr       = _cmsDupDefaultFn;
 221         return TRUE;
 222     }
 223 
 224     // Check for required callbacks
 225     if (Plugin -> MallocPtr == NULL ||
 226         Plugin -> FreePtr == NULL ||
 227         Plugin -> ReallocPtr == NULL) return FALSE;
 228 
 229     // Set replacement functions
 230     MallocPtr  = Plugin -> MallocPtr;
 231     FreePtr    = Plugin -> FreePtr;
 232     ReallocPtr = Plugin -> ReallocPtr;
 233 
 234     if (Plugin ->MallocZeroPtr != NULL) MallocZeroPtr = Plugin ->MallocZeroPtr;
 235     if (Plugin ->CallocPtr != NULL)     CallocPtr     = Plugin -> CallocPtr;
 236     if (Plugin ->DupPtr != NULL)        DupPtr        = Plugin -> DupPtr;
 237 
 238     return TRUE;
 239 }
 240 
 241 // Generic allocate
 242 void* CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size)
 243 {
 244     return MallocPtr(ContextID, size);
 245 }
 246 
 247 // Generic allocate & zero
 248 void* CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size)
 249 {
 250     return MallocZeroPtr(ContextID, size);
 251 }
 252 
 253 // Generic calloc
 254 void* CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size)
 255 {
 256     return CallocPtr(ContextID, num, size);
 257 }
 258 
 259 // Generic reallocate
 260 void* CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number size)
 261 {
 262     return ReallocPtr(ContextID, Ptr, size);
 263 }
 264 
 265 // Generic free memory
 266 void CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr)
 267 {
 268     if (Ptr != NULL) FreePtr(ContextID, Ptr);
 269 }
 270 
 271 // Generic block duplication
 272 void* CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size)
 273 {
 274     return DupPtr(ContextID, Org, size);
 275 }
 276 
 277 // ********************************************************************************************
 278 
 279 // Sub allocation takes care of many pointers of small size. The memory allocated in
 280 // this way have be freed at once. Next function allocates a single chunk for linked list
 281 // I prefer this method over realloc due to the big inpact on xput realloc may have if
 282 // memory is being swapped to disk. This approach is safer (although that may not be true on all platforms)
 283 static
 284 _cmsSubAllocator_chunk* _cmsCreateSubAllocChunk(cmsContext ContextID, cmsUInt32Number Initial)
 285 {
 286     _cmsSubAllocator_chunk* chunk;
 287 
 288     // 20K by default
 289     if (Initial == 0)
 290         Initial = 20*1024;
 291 
 292     // Create the container
 293     chunk = (_cmsSubAllocator_chunk*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator_chunk));
 294     if (chunk == NULL) return NULL;
 295 
 296     // Initialize values
 297     chunk ->Block     = (cmsUInt8Number*) _cmsMalloc(ContextID, Initial);
 298     if (chunk ->Block == NULL) {
 299 
 300         // Something went wrong
 301         _cmsFree(ContextID, chunk);
 302         return NULL;
 303     }
 304 
 305 
 306 
 307     chunk ->BlockSize = Initial;
 308     chunk ->Used      = 0;
 309     chunk ->next      = NULL;
 310 
 311     return chunk;
 312 }
 313 
 314 // The suballocated is nothing but a pointer to the first element in the list. We also keep
 315 // the thread ID in this structure.
 316 _cmsSubAllocator* _cmsCreateSubAlloc(cmsContext ContextID, cmsUInt32Number Initial)
 317 {
 318     _cmsSubAllocator* sub;
 319 
 320     // Create the container
 321     sub = (_cmsSubAllocator*) _cmsMallocZero(ContextID, sizeof(_cmsSubAllocator));
 322     if (sub == NULL) return NULL;
 323 
 324     sub ->ContextID = ContextID;
 325 
 326     sub ->h = _cmsCreateSubAllocChunk(ContextID, Initial);
 327     if (sub ->h == NULL) {
 328         _cmsFree(ContextID, sub);
 329         return NULL;
 330     }
 331 
 332     return sub;
 333 }
 334 
 335 
 336 // Get rid of whole linked list
 337 void _cmsSubAllocDestroy(_cmsSubAllocator* sub)
 338 {
 339     _cmsSubAllocator_chunk *chunk, *n;
 340 
 341     for (chunk = sub ->h; chunk != NULL; chunk = n) {
 342 
 343         n = chunk->next;
 344         if (chunk->Block != NULL) _cmsFree(sub ->ContextID, chunk->Block);
 345         _cmsFree(sub ->ContextID, chunk);
 346     }
 347 
 348     // Free the header
 349     _cmsFree(sub ->ContextID, sub);
 350 }
 351 
 352 
 353 // Get a pointer to small memory block.
 354 void*  _cmsSubAlloc(_cmsSubAllocator* sub, cmsUInt32Number size)
 355 {
 356     cmsUInt32Number Free = sub -> h ->BlockSize - sub -> h -> Used;
 357     cmsUInt8Number* ptr;
 358 
 359     size = _cmsALIGNMEM(size);
 360 
 361     // Check for memory. If there is no room, allocate a new chunk of double memory size.
 362     if (size > Free) {
 363 
 364         _cmsSubAllocator_chunk* chunk;
 365         cmsUInt32Number newSize;
 366 
 367         newSize = sub -> h ->BlockSize * 2;
 368         if (newSize < size) newSize = size;
 369 
 370         chunk = _cmsCreateSubAllocChunk(sub -> ContextID, newSize);
 371         if (chunk == NULL) return NULL;
 372 
 373         // Link list
 374         chunk ->next = sub ->h;
 375         sub ->h    = chunk;
 376 
 377     }
 378 
 379     ptr =  sub -> h ->Block + sub -> h ->Used;
 380     sub -> h -> Used += size;
 381 
 382     return (void*) ptr;
 383 }
 384 
 385 // Error logging ******************************************************************
 386 
 387 // There is no error handling at all. When a funtion fails, it returns proper value.
 388 // For example, all create functions does return NULL on failure. Other return FALSE
 389 // It may be interesting, for the developer, to know why the function is failing.
 390 // for that reason, lcms2 does offer a logging function. This function does recive
 391 // a ENGLISH string with some clues on what is going wrong. You can show this
 392 // info to the end user, or just create some sort of log.
 393 // The logging function should NOT terminate the program, as this obviously can leave
 394 // resources. It is the programmer's responsability to check each function return code
 395 // to make sure it didn't fail.
 396 
 397 // Error messages are limited to MAX_ERROR_MESSAGE_LEN
 398 
 399 #define MAX_ERROR_MESSAGE_LEN   1024
 400 
 401 // ---------------------------------------------------------------------------------------------------------
 402 
 403 // This is our default log error
 404 static void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text);
 405 
 406 // The current handler in actual environment
 407 static cmsLogErrorHandlerFunction LogErrorHandler   = DefaultLogErrorHandlerFunction;
 408 
 409 // The default error logger does nothing.
 410 static
 411 void DefaultLogErrorHandlerFunction(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text)
 412 {
 413     // fprintf(stderr, "[lcms]: %s\n", Text);
 414     // fflush(stderr);
 415 
 416      cmsUNUSED_PARAMETER(ContextID);
 417      cmsUNUSED_PARAMETER(ErrorCode);
 418      cmsUNUSED_PARAMETER(Text);
 419 }
 420 
 421 // Change log error
 422 void CMSEXPORT cmsSetLogErrorHandler(cmsLogErrorHandlerFunction Fn)
 423 {
 424     if (Fn == NULL)
 425         LogErrorHandler = DefaultLogErrorHandlerFunction;
 426     else
 427         LogErrorHandler = Fn;
 428 }
 429 
 430 // Log an error
 431 // ErrorText is a text holding an english description of error.
 432 void CMSEXPORT cmsSignalError(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText, ...)
 433 {
 434     va_list args;
 435     char Buffer[MAX_ERROR_MESSAGE_LEN];
 436 
 437     va_start(args, ErrorText);
 438     vsnprintf(Buffer, MAX_ERROR_MESSAGE_LEN-1, ErrorText, args);
 439     va_end(args);
 440 
 441     // Call handler
 442     LogErrorHandler(ContextID, ErrorCode, Buffer);
 443 }
 444 
 445 // Utility function to print signatures
 446 void _cmsTagSignature2String(char String[5], cmsTagSignature sig)
 447 {
 448     cmsUInt32Number be;
 449 
 450     // Convert to big endian
 451     be = _cmsAdjustEndianess32((cmsUInt32Number) sig);
 452 
 453     // Move chars
 454     memmove(String, &be, 4);
 455 
 456     // Make sure of terminator
 457     String[4] = 0;
 458 }
 459