3 * Standard C library function wrappers.
5 * Imports are services which the device driver or window system or
6 * operating system provides to the core renderer. The core renderer (Mesa)
7 * will call these functions in order to do memory allocation, simple I/O,
10 * Some drivers will want to override/replace this file with something
11 * specialized, but that'll be rare.
13 * Eventually, I want to move roll the glheader.h file into this.
15 * \todo Functions still needed:
22 * Mesa 3-D graphics library
25 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
27 * Permission is hereby granted, free of charge, to any person obtaining a
28 * copy of this software and associated documentation files (the "Software"),
29 * to deal in the Software without restriction, including without limitation
30 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
31 * and/or sell copies of the Software, and to permit persons to whom the
32 * Software is furnished to do so, subject to the following conditions:
34 * The above copyright notice and this permission notice shall be included
35 * in all copies or substantial portions of the Software.
37 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
38 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
40 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
41 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
42 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
55 #define MAXSTRING 4000 /* for vsnprintf() */
58 #define vsnprintf _vsnprintf
59 #elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
60 extern int vsnprintf(char *str
, size_t count
, const char *fmt
, va_list arg
);
62 #include "vsnprintf.c"
66 /**********************************************************************/
71 * Allocate aligned memory.
73 * \param bytes number of bytes to allocate.
74 * \param alignment alignment (must be greater than zero).
76 * Allocates extra memory to accommodate rounding up the address for
77 * alignment and to record the real malloc address.
79 * \sa _mesa_align_free().
82 _mesa_align_malloc(size_t bytes
, unsigned long alignment
)
84 #if defined(HAVE_POSIX_MEMALIGN)
86 int err
= posix_memalign(& mem
, alignment
, bytes
);
90 #elif defined(_WIN32) && defined(_MSC_VER)
91 return _aligned_malloc(bytes
, alignment
);
95 ASSERT( alignment
> 0 );
97 ptr
= (uintptr_t) malloc(bytes
+ alignment
+ sizeof(void *));
101 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
102 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
105 /* mark the non-aligned area */
106 while ( ptr
< buf
- sizeof(void *) ) {
107 *(unsigned long *)ptr
= 0xcdcdcdcd;
108 ptr
+= sizeof(unsigned long);
113 #endif /* defined(HAVE_POSIX_MEMALIGN) */
117 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
121 _mesa_align_calloc(size_t bytes
, unsigned long alignment
)
123 #if defined(HAVE_POSIX_MEMALIGN)
126 mem
= _mesa_align_malloc(bytes
, alignment
);
128 (void) memset(mem
, 0, bytes
);
132 #elif defined(_WIN32) && defined(_MSC_VER)
135 mem
= _aligned_malloc(bytes
, alignment
);
137 (void) memset(mem
, 0, bytes
);
144 ASSERT( alignment
> 0 );
146 ptr
= (uintptr_t) calloc(1, bytes
+ alignment
+ sizeof(void *));
150 buf
= (ptr
+ alignment
+ sizeof(void *)) & ~(uintptr_t)(alignment
- 1);
151 *(uintptr_t *)(buf
- sizeof(void *)) = ptr
;
154 /* mark the non-aligned area */
155 while ( ptr
< buf
- sizeof(void *) ) {
156 *(unsigned long *)ptr
= 0xcdcdcdcd;
157 ptr
+= sizeof(unsigned long);
162 #endif /* defined(HAVE_POSIX_MEMALIGN) */
166 * Free memory which was allocated with either _mesa_align_malloc()
167 * or _mesa_align_calloc().
168 * \param ptr pointer to the memory to be freed.
169 * The actual address to free is stored in the word immediately before the
170 * address the client sees.
173 _mesa_align_free(void *ptr
)
175 #if defined(HAVE_POSIX_MEMALIGN)
177 #elif defined(_WIN32) && defined(_MSC_VER)
180 void **cubbyHole
= (void **) ((char *) ptr
- sizeof(void *));
181 void *realAddr
= *cubbyHole
;
183 #endif /* defined(HAVE_POSIX_MEMALIGN) */
187 * Reallocate memory, with alignment.
190 _mesa_align_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
,
191 unsigned long alignment
)
193 #if defined(_WIN32) && defined(_MSC_VER)
195 return _aligned_realloc(oldBuffer
, newSize
, alignment
);
197 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
198 void *newBuf
= _mesa_align_malloc(newSize
, alignment
);
199 if (newBuf
&& oldBuffer
&& copySize
> 0) {
200 memcpy(newBuf
, oldBuffer
, copySize
);
203 _mesa_align_free(oldBuffer
);
210 /** Reallocate memory */
212 _mesa_realloc(void *oldBuffer
, size_t oldSize
, size_t newSize
)
214 const size_t copySize
= (oldSize
< newSize
) ? oldSize
: newSize
;
215 void *newBuffer
= malloc(newSize
);
216 if (newBuffer
&& oldBuffer
&& copySize
> 0)
217 memcpy(newBuffer
, oldBuffer
, copySize
);
224 * Fill memory with a constant 16bit word.
225 * \param dst destination pointer.
227 * \param n number of words.
230 _mesa_memset16( unsigned short *dst
, unsigned short val
, size_t n
)
239 /**********************************************************************/
243 /** Wrapper around sqrt() */
245 _mesa_sqrtd(double x
)
252 * A High Speed, Low Precision Square Root
253 * by Paul Lalonde and Robert Dawson
254 * from "Graphics Gems", Academic Press, 1990
256 * SPARC implementation of a fast square root by table
258 * SPARC floating point format is as follows:
261 * sign exponent mantissa
263 static short sqrttab
[0x100]; /* declare table of square roots */
266 _mesa_init_sqrt_table(void)
268 #if defined(USE_IEEE) && !defined(DEBUG)
270 fi_type fi
; /* to access the bits of a float in C quickly */
271 /* we use a union defined in glheader.h */
273 for(i
=0; i
<= 0x7f; i
++) {
277 * Build a float with the bit pattern i as mantissa
278 * and an exponent of 0, stored as 127
281 fi
.i
= (i
<< 16) | (127 << 23);
282 fi
.f
= _mesa_sqrtd(fi
.f
);
285 * Take the square root then strip the first 7 bits of
286 * the mantissa into the table
289 sqrttab
[i
] = (fi
.i
& 0x7fffff) >> 16;
292 * Repeat the process, this time with an exponent of
297 fi
.i
= (i
<< 16) | (128 << 23);
299 sqrttab
[i
+0x80] = (fi
.i
& 0x7fffff) >> 16;
302 (void) sqrttab
; /* silence compiler warnings */
303 #endif /*HAVE_FAST_MATH*/
308 * Single precision square root.
311 _mesa_sqrtf( float x
)
313 #if defined(USE_IEEE) && !defined(DEBUG)
315 /* to access the bits of a float in C
316 * we use a union from glheader.h */
318 short e
; /* the exponent */
319 if (x
== 0.0F
) return 0.0F
; /* check for square root of 0 */
321 e
= (num
.i
>> 23) - 127; /* get the exponent - on a SPARC the */
322 /* exponent is stored with 127 added */
323 num
.i
&= 0x7fffff; /* leave only the mantissa */
324 if (e
& 0x01) num
.i
|= 0x800000;
325 /* the exponent is odd so we have to */
326 /* look it up in the second half of */
327 /* the lookup table, so we set the */
329 e
>>= 1; /* divide the exponent by two */
330 /* note that in C the shift */
331 /* operators are sign preserving */
332 /* for signed operands */
333 /* Do the table lookup, based on the quaternary mantissa,
334 * then reconstruct the result back into a float
336 num
.i
= ((sqrttab
[num
.i
>> 16]) << 16) | ((e
+ 127) << 23);
340 return (float) _mesa_sqrtd((double) x
);
346 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
347 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
351 _mesa_inv_sqrtf(float n
)
353 #if defined(USE_IEEE) && !defined(DEBUG)
357 #if 0 /* not used, see below -BP */
364 Exponent part of the magic number -
367 1. subtract the bias from the exponent,
369 3. divide by two (rounding towards -inf)
372 Which is the same as subtracting the exponent from 381 and dividing
375 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
381 Significand part of magic number -
383 With the current magic number, "(magic - u.i) >> 1" will give you:
385 for 1 <= u.f <= 2: 1.25 - u.f / 4
386 for 2 <= u.f <= 4: 1.00 - u.f / 8
388 This isn't a bad approximation of 1/sqrt. The maximum difference from
389 1/sqrt will be around .06. After three Newton-Raphson iterations, the
390 maximum difference is less than 4.5e-8. (Which is actually close
391 enough to make the following bias academic...)
393 To get a better approximation you can add a bias to the magic
394 number. For example, if you subtract 1/2 of the maximum difference in
395 the first approximation (.03), you will get the following function:
397 for 1 <= u.f <= 2: 1.22 - u.f / 4
398 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
399 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
400 (The 3.76 to 4 range is where the result is < .5.)
402 This is the closest possible initial approximation, but with a maximum
403 error of 8e-11 after three NR iterations, it is still not perfect. If
404 you subtract 0.0332281 instead of .03, the maximum error will be
405 2.5e-11 after three NR iterations, which should be about as close as
408 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
409 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
410 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
414 magic
-= (int)(0.0332281 * (1 << 25));
417 u
.i
= (magic
- u
.i
) >> 1;
420 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
421 allows more parallelism. From what I understand, the parallelism
422 comes at the cost of less precision, because it lets error
423 accumulate across iterations.
438 return x2
* r2
; /* we can stop here, and be conformant -BP */
447 return (float) (1.0 / sqrt(n
));
453 * Find the first bit set in a word.
458 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
459 register int bit
= 0;
461 if ((i
& 0xffff) == 0) {
465 if ((i
& 0xff) == 0) {
469 if ((i
& 0xf) == 0) {
473 while ((i
& 1) == 0) {
487 * Find position of first bit set in given value.
488 * XXX Warning: this function can only be used on 64-bit systems!
489 * \return position of least-significant bit set, starting at 1, return zero
493 _mesa_ffsll(int64_t val
)
497 assert(sizeof(val
) == 8);
499 bit
= _mesa_ffs((int32_t)val
);
503 bit
= _mesa_ffs((int32_t)(val
>> 32));
511 #if !defined(__GNUC__) ||\
512 ((__GNUC__ * 100 + __GNUC_MINOR__) < 304) /* Not gcc 3.4 or later */
514 * Return number of bits set in given GLuint.
517 _mesa_bitcount(unsigned int n
)
520 for (bits
= 0; n
> 0; n
= n
>> 1) {
527 * Return number of bits set in given 64-bit uint.
530 _mesa_bitcount_64(uint64_t n
)
533 for (bits
= 0; n
> 0; n
= n
>> 1) {
543 /**********************************************************************/
544 /** \name Sort & Search */
548 * Wrapper for bsearch().
551 _mesa_bsearch( const void *key
, const void *base
, size_t nmemb
, size_t size
,
552 int (*compar
)(const void *, const void *) )
554 #if defined(_WIN32_WCE)
559 mid
= (char *)base
+ nmemb
* size
;
560 cmp
= (*compar
)(key
, mid
);
564 base
= (char *)mid
+ size
;
570 return bsearch(key
, base
, nmemb
, size
, compar
);
577 /**********************************************************************/
578 /** \name Environment vars */
582 * Wrapper for getenv().
585 _mesa_getenv( const char *var
)
587 #if defined(_XBOX) || defined(_WIN32_WCE)
597 /**********************************************************************/
602 * Implemented using malloc() and strcpy.
603 * Note that NULL is handled accordingly.
606 _mesa_strdup( const char *s
)
609 size_t l
= strlen(s
);
610 char *s2
= (char *) malloc(l
+ 1);
620 /** Wrapper around strtof() */
622 _mesa_strtof( const char *s
, char **end
)
624 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__) && \
625 !defined(ANDROID) && !defined(__HAIKU__)
626 static locale_t loc
= NULL
;
628 loc
= newlocale(LC_CTYPE_MASK
, "C", NULL
);
630 return strtof_l(s
, end
, loc
);
631 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
632 return strtof(s
, end
);
634 return (float)strtod(s
, end
);
638 /** Compute simple checksum/hash for a string */
640 _mesa_str_checksum(const char *str
)
642 /* This could probably be much better */
646 for (c
= str
; *c
; c
++, i
++)
647 sum
+= *c
* (i
% 100);
655 /** Wrapper around vsnprintf() */
657 _mesa_snprintf( char *str
, size_t size
, const char *fmt
, ... )
661 va_start( args
, fmt
);
662 r
= vsnprintf( str
, size
, fmt
, args
);
668 /**********************************************************************/
669 /** \name Diagnostics */
673 output_if_debug(const char *prefixString
, const char *outputString
,
676 static int debug
= -1;
678 /* Check the MESA_DEBUG environment variable if it hasn't
679 * been checked yet. We only have to check it once...
682 char *env
= _mesa_getenv("MESA_DEBUG");
684 /* In a debug build, we print warning messages *unless*
685 * MESA_DEBUG is 0. In a non-debug build, we don't
686 * print warning messages *unless* MESA_DEBUG is
687 * set *to any value*.
690 debug
= (env
!= NULL
&& atoi(env
) == 0) ? 0 : 1;
692 debug
= (env
!= NULL
) ? 1 : 0;
696 /* Now only print the string if we're required to do so. */
698 fprintf(stderr
, "%s: %s", prefixString
, outputString
);
700 fprintf(stderr
, "\n");
702 #if defined(_WIN32) && !defined(_WIN32_WCE)
703 /* stderr from windows applications without console is not usually
704 * visible, so communicate with the debugger instead */
707 _mesa_snprintf(buf
, sizeof(buf
), "%s: %s%s", prefixString
, outputString
, newline
? "\n" : "");
708 OutputDebugStringA(buf
);
716 * Return string version of GL error code.
719 error_string( GLenum error
)
723 return "GL_NO_ERROR";
724 case GL_INVALID_VALUE
:
725 return "GL_INVALID_VALUE";
726 case GL_INVALID_ENUM
:
727 return "GL_INVALID_ENUM";
728 case GL_INVALID_OPERATION
:
729 return "GL_INVALID_OPERATION";
730 case GL_STACK_OVERFLOW
:
731 return "GL_STACK_OVERFLOW";
732 case GL_STACK_UNDERFLOW
:
733 return "GL_STACK_UNDERFLOW";
734 case GL_OUT_OF_MEMORY
:
735 return "GL_OUT_OF_MEMORY";
736 case GL_TABLE_TOO_LARGE
:
737 return "GL_TABLE_TOO_LARGE";
738 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT
:
739 return "GL_INVALID_FRAMEBUFFER_OPERATION";
747 * When a new type of error is recorded, print a message describing
748 * previous errors which were accumulated.
751 flush_delayed_errors( struct gl_context
*ctx
)
755 if (ctx
->ErrorDebugCount
) {
756 _mesa_snprintf(s
, MAXSTRING
, "%d similar %s errors",
757 ctx
->ErrorDebugCount
,
758 error_string(ctx
->ErrorValue
));
760 output_if_debug("Mesa", s
, GL_TRUE
);
762 ctx
->ErrorDebugCount
= 0;
768 * Report a warning (a recoverable error condition) to stderr if
769 * either DEBUG is defined or the MESA_DEBUG env var is set.
771 * \param ctx GL context.
772 * \param fmtString printf()-like format string.
775 _mesa_warning( struct gl_context
*ctx
, const char *fmtString
, ... )
779 va_start( args
, fmtString
);
780 (void) vsnprintf( str
, MAXSTRING
, fmtString
, args
);
784 flush_delayed_errors( ctx
);
786 output_if_debug("Mesa warning", str
, GL_TRUE
);
791 * Report an internal implementation problem.
792 * Prints the message to stderr via fprintf().
794 * \param ctx GL context.
795 * \param fmtString problem description string.
798 _mesa_problem( const struct gl_context
*ctx
, const char *fmtString
, ... )
802 static int numCalls
= 0;
809 va_start( args
, fmtString
);
810 vsnprintf( str
, MAXSTRING
, fmtString
, args
);
812 fprintf(stderr
, "Mesa %s implementation error: %s\n",
813 MESA_VERSION_STRING
, str
);
814 fprintf(stderr
, "Please report at bugs.freedesktop.org\n");
820 * Record an OpenGL state error. These usually occur when the user
821 * passes invalid parameters to a GL function.
823 * If debugging is enabled (either at compile-time via the DEBUG macro, or
824 * run-time via the MESA_DEBUG environment variable), report the error with
827 * \param ctx the GL context.
828 * \param error the error value.
829 * \param fmtString printf() style format string, followed by optional args
832 _mesa_error( struct gl_context
*ctx
, GLenum error
, const char *fmtString
, ... )
834 static GLint debug
= -1;
836 /* Check debug environment variable only once:
839 const char *debugEnv
= _mesa_getenv("MESA_DEBUG");
842 if (debugEnv
&& strstr(debugEnv
, "silent"))
855 if (ctx
->ErrorValue
== error
&&
856 ctx
->ErrorDebugFmtString
== fmtString
) {
857 ctx
->ErrorDebugCount
++;
860 char s
[MAXSTRING
], s2
[MAXSTRING
];
863 flush_delayed_errors( ctx
);
865 va_start(args
, fmtString
);
866 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
869 _mesa_snprintf(s2
, MAXSTRING
, "%s in %s", error_string(error
), s
);
870 output_if_debug("Mesa: User error", s2
, GL_TRUE
);
872 ctx
->ErrorDebugFmtString
= fmtString
;
873 ctx
->ErrorDebugCount
= 0;
877 _mesa_record_error(ctx
, error
);
882 * Report debug information. Print error message to stderr via fprintf().
883 * No-op if DEBUG mode not enabled.
885 * \param ctx GL context.
886 * \param fmtString printf()-style format string, followed by optional args.
889 _mesa_debug( const struct gl_context
*ctx
, const char *fmtString
, ... )
894 va_start(args
, fmtString
);
895 vsnprintf(s
, MAXSTRING
, fmtString
, args
);
897 output_if_debug("Mesa", s
, GL_FALSE
);