cefbf4d8c98772c1543167e97f1523383bad4733
[mesa.git] / src / mesa / main / imports.c
1 /**
2 * \file imports.c
3 * Standard C library function wrappers.
4 *
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,
8 * etc.
9 *
10 * Some drivers will want to override/replace this file with something
11 * specialized, but that'll be rare.
12 *
13 * Eventually, I want to move roll the glheader.h file into this.
14 *
15 * \todo Functions still needed:
16 * - scanf
17 * - qsort
18 * - rand and RAND_MAX
19 */
20
21 /*
22 * Mesa 3-D graphics library
23 * Version: 7.1
24 *
25 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
26 *
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:
33 *
34 * The above copyright notice and this permission notice shall be included
35 * in all copies or substantial portions of the Software.
36 *
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.
43 */
44
45
46
47 #include "imports.h"
48 #include "context.h"
49 #include "version.h"
50
51 #ifdef _GNU_SOURCE
52 #include <locale.h>
53 #ifdef __APPLE__
54 #include <xlocale.h>
55 #endif
56 #endif
57
58
59 #define MAXSTRING 4000 /* for vsnprintf() */
60
61 #ifdef WIN32
62 #define vsnprintf _vsnprintf
63 #elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
64 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list arg);
65 #ifdef __VMS
66 #include "vsnprintf.c"
67 #endif
68 #endif
69
70 /**********************************************************************/
71 /** \name Memory */
72 /*@{*/
73
74 /**
75 * Allocate aligned memory.
76 *
77 * \param bytes number of bytes to allocate.
78 * \param alignment alignment (must be greater than zero).
79 *
80 * Allocates extra memory to accommodate rounding up the address for
81 * alignment and to record the real malloc address.
82 *
83 * \sa _mesa_align_free().
84 */
85 void *
86 _mesa_align_malloc(size_t bytes, unsigned long alignment)
87 {
88 #if defined(HAVE_POSIX_MEMALIGN)
89 void *mem;
90 int err = posix_memalign(& mem, alignment, bytes);
91 if (err)
92 return NULL;
93 return mem;
94 #elif defined(_WIN32) && defined(_MSC_VER)
95 return _aligned_malloc(bytes, alignment);
96 #else
97 uintptr_t ptr, buf;
98
99 ASSERT( alignment > 0 );
100
101 ptr = (uintptr_t) malloc(bytes + alignment + sizeof(void *));
102 if (!ptr)
103 return NULL;
104
105 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
106 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
107
108 #ifdef DEBUG
109 /* mark the non-aligned area */
110 while ( ptr < buf - sizeof(void *) ) {
111 *(unsigned long *)ptr = 0xcdcdcdcd;
112 ptr += sizeof(unsigned long);
113 }
114 #endif
115
116 return (void *) buf;
117 #endif /* defined(HAVE_POSIX_MEMALIGN) */
118 }
119
120 /**
121 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
122 * malloc()
123 */
124 void *
125 _mesa_align_calloc(size_t bytes, unsigned long alignment)
126 {
127 #if defined(HAVE_POSIX_MEMALIGN)
128 void *mem;
129
130 mem = _mesa_align_malloc(bytes, alignment);
131 if (mem != NULL) {
132 (void) memset(mem, 0, bytes);
133 }
134
135 return mem;
136 #elif defined(_WIN32) && defined(_MSC_VER)
137 void *mem;
138
139 mem = _aligned_malloc(bytes, alignment);
140 if (mem != NULL) {
141 (void) memset(mem, 0, bytes);
142 }
143
144 return mem;
145 #else
146 uintptr_t ptr, buf;
147
148 ASSERT( alignment > 0 );
149
150 ptr = (uintptr_t) calloc(1, bytes + alignment + sizeof(void *));
151 if (!ptr)
152 return NULL;
153
154 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
155 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
156
157 #ifdef DEBUG
158 /* mark the non-aligned area */
159 while ( ptr < buf - sizeof(void *) ) {
160 *(unsigned long *)ptr = 0xcdcdcdcd;
161 ptr += sizeof(unsigned long);
162 }
163 #endif
164
165 return (void *)buf;
166 #endif /* defined(HAVE_POSIX_MEMALIGN) */
167 }
168
169 /**
170 * Free memory which was allocated with either _mesa_align_malloc()
171 * or _mesa_align_calloc().
172 * \param ptr pointer to the memory to be freed.
173 * The actual address to free is stored in the word immediately before the
174 * address the client sees.
175 */
176 void
177 _mesa_align_free(void *ptr)
178 {
179 #if defined(HAVE_POSIX_MEMALIGN)
180 free(ptr);
181 #elif defined(_WIN32) && defined(_MSC_VER)
182 _aligned_free(ptr);
183 #else
184 void **cubbyHole = (void **) ((char *) ptr - sizeof(void *));
185 void *realAddr = *cubbyHole;
186 free(realAddr);
187 #endif /* defined(HAVE_POSIX_MEMALIGN) */
188 }
189
190 /**
191 * Reallocate memory, with alignment.
192 */
193 void *
194 _mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
195 unsigned long alignment)
196 {
197 #if defined(_WIN32) && defined(_MSC_VER)
198 (void) oldSize;
199 return _aligned_realloc(oldBuffer, newSize, alignment);
200 #else
201 const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
202 void *newBuf = _mesa_align_malloc(newSize, alignment);
203 if (newBuf && oldBuffer && copySize > 0) {
204 memcpy(newBuf, oldBuffer, copySize);
205 }
206 if (oldBuffer)
207 _mesa_align_free(oldBuffer);
208 return newBuf;
209 #endif
210 }
211
212
213
214 /** Reallocate memory */
215 void *
216 _mesa_realloc(void *oldBuffer, size_t oldSize, size_t newSize)
217 {
218 const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
219 void *newBuffer = malloc(newSize);
220 if (newBuffer && oldBuffer && copySize > 0)
221 memcpy(newBuffer, oldBuffer, copySize);
222 if (oldBuffer)
223 free(oldBuffer);
224 return newBuffer;
225 }
226
227 /**
228 * Fill memory with a constant 16bit word.
229 * \param dst destination pointer.
230 * \param val value.
231 * \param n number of words.
232 */
233 void
234 _mesa_memset16( unsigned short *dst, unsigned short val, size_t n )
235 {
236 while (n-- > 0)
237 *dst++ = val;
238 }
239
240 /*@}*/
241
242
243 /**********************************************************************/
244 /** \name Math */
245 /*@{*/
246
247 /** Wrapper around sqrt() */
248 double
249 _mesa_sqrtd(double x)
250 {
251 return sqrt(x);
252 }
253
254
255 /*
256 * A High Speed, Low Precision Square Root
257 * by Paul Lalonde and Robert Dawson
258 * from "Graphics Gems", Academic Press, 1990
259 *
260 * SPARC implementation of a fast square root by table
261 * lookup.
262 * SPARC floating point format is as follows:
263 *
264 * BIT 31 30 23 22 0
265 * sign exponent mantissa
266 */
267 static short sqrttab[0x100]; /* declare table of square roots */
268
269 void
270 _mesa_init_sqrt_table(void)
271 {
272 #if defined(USE_IEEE) && !defined(DEBUG)
273 unsigned short i;
274 fi_type fi; /* to access the bits of a float in C quickly */
275 /* we use a union defined in glheader.h */
276
277 for(i=0; i<= 0x7f; i++) {
278 fi.i = 0;
279
280 /*
281 * Build a float with the bit pattern i as mantissa
282 * and an exponent of 0, stored as 127
283 */
284
285 fi.i = (i << 16) | (127 << 23);
286 fi.f = _mesa_sqrtd(fi.f);
287
288 /*
289 * Take the square root then strip the first 7 bits of
290 * the mantissa into the table
291 */
292
293 sqrttab[i] = (fi.i & 0x7fffff) >> 16;
294
295 /*
296 * Repeat the process, this time with an exponent of
297 * 1, stored as 128
298 */
299
300 fi.i = 0;
301 fi.i = (i << 16) | (128 << 23);
302 fi.f = sqrt(fi.f);
303 sqrttab[i+0x80] = (fi.i & 0x7fffff) >> 16;
304 }
305 #else
306 (void) sqrttab; /* silence compiler warnings */
307 #endif /*HAVE_FAST_MATH*/
308 }
309
310
311 /**
312 * Single precision square root.
313 */
314 float
315 _mesa_sqrtf( float x )
316 {
317 #if defined(USE_IEEE) && !defined(DEBUG)
318 fi_type num;
319 /* to access the bits of a float in C
320 * we use a union from glheader.h */
321
322 short e; /* the exponent */
323 if (x == 0.0F) return 0.0F; /* check for square root of 0 */
324 num.f = x;
325 e = (num.i >> 23) - 127; /* get the exponent - on a SPARC the */
326 /* exponent is stored with 127 added */
327 num.i &= 0x7fffff; /* leave only the mantissa */
328 if (e & 0x01) num.i |= 0x800000;
329 /* the exponent is odd so we have to */
330 /* look it up in the second half of */
331 /* the lookup table, so we set the */
332 /* high bit */
333 e >>= 1; /* divide the exponent by two */
334 /* note that in C the shift */
335 /* operators are sign preserving */
336 /* for signed operands */
337 /* Do the table lookup, based on the quaternary mantissa,
338 * then reconstruct the result back into a float
339 */
340 num.i = ((sqrttab[num.i >> 16]) << 16) | ((e + 127) << 23);
341
342 return num.f;
343 #else
344 return (float) _mesa_sqrtd((double) x);
345 #endif
346 }
347
348
349 /**
350 inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
351 written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
352 and Vesa Karvonen.
353 */
354 float
355 _mesa_inv_sqrtf(float n)
356 {
357 #if defined(USE_IEEE) && !defined(DEBUG)
358 float r0, x0, y0;
359 float r1, x1, y1;
360 float r2, x2, y2;
361 #if 0 /* not used, see below -BP */
362 float r3, x3, y3;
363 #endif
364 fi_type u;
365 unsigned int magic;
366
367 /*
368 Exponent part of the magic number -
369
370 We want to:
371 1. subtract the bias from the exponent,
372 2. negate it
373 3. divide by two (rounding towards -inf)
374 4. add the bias back
375
376 Which is the same as subtracting the exponent from 381 and dividing
377 by 2.
378
379 floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
380 */
381
382 magic = 381 << 23;
383
384 /*
385 Significand part of magic number -
386
387 With the current magic number, "(magic - u.i) >> 1" will give you:
388
389 for 1 <= u.f <= 2: 1.25 - u.f / 4
390 for 2 <= u.f <= 4: 1.00 - u.f / 8
391
392 This isn't a bad approximation of 1/sqrt. The maximum difference from
393 1/sqrt will be around .06. After three Newton-Raphson iterations, the
394 maximum difference is less than 4.5e-8. (Which is actually close
395 enough to make the following bias academic...)
396
397 To get a better approximation you can add a bias to the magic
398 number. For example, if you subtract 1/2 of the maximum difference in
399 the first approximation (.03), you will get the following function:
400
401 for 1 <= u.f <= 2: 1.22 - u.f / 4
402 for 2 <= u.f <= 3.76: 0.97 - u.f / 8
403 for 3.76 <= u.f <= 4: 0.72 - u.f / 16
404 (The 3.76 to 4 range is where the result is < .5.)
405
406 This is the closest possible initial approximation, but with a maximum
407 error of 8e-11 after three NR iterations, it is still not perfect. If
408 you subtract 0.0332281 instead of .03, the maximum error will be
409 2.5e-11 after three NR iterations, which should be about as close as
410 is possible.
411
412 for 1 <= u.f <= 2: 1.2167719 - u.f / 4
413 for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
414 for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
415
416 */
417
418 magic -= (int)(0.0332281 * (1 << 25));
419
420 u.f = n;
421 u.i = (magic - u.i) >> 1;
422
423 /*
424 Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
425 allows more parallelism. From what I understand, the parallelism
426 comes at the cost of less precision, because it lets error
427 accumulate across iterations.
428 */
429 x0 = 1.0f;
430 y0 = 0.5f * n;
431 r0 = u.f;
432
433 x1 = x0 * r0;
434 y1 = y0 * r0 * r0;
435 r1 = 1.5f - y1;
436
437 x2 = x1 * r1;
438 y2 = y1 * r1 * r1;
439 r2 = 1.5f - y2;
440
441 #if 1
442 return x2 * r2; /* we can stop here, and be conformant -BP */
443 #else
444 x3 = x2 * r2;
445 y3 = y2 * r2 * r2;
446 r3 = 1.5f - y3;
447
448 return x3 * r3;
449 #endif
450 #else
451 return (float) (1.0 / sqrt(n));
452 #endif
453 }
454
455 /**
456 * Find the first bit set in a word.
457 */
458 int
459 _mesa_ffs(int32_t i)
460 {
461 #if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
462 register int bit = 0;
463 if (i != 0) {
464 if ((i & 0xffff) == 0) {
465 bit += 16;
466 i >>= 16;
467 }
468 if ((i & 0xff) == 0) {
469 bit += 8;
470 i >>= 8;
471 }
472 if ((i & 0xf) == 0) {
473 bit += 4;
474 i >>= 4;
475 }
476 while ((i & 1) == 0) {
477 bit++;
478 i >>= 1;
479 }
480 bit++;
481 }
482 return bit;
483 #else
484 return ffs(i);
485 #endif
486 }
487
488
489 /**
490 * Find position of first bit set in given value.
491 * XXX Warning: this function can only be used on 64-bit systems!
492 * \return position of least-significant bit set, starting at 1, return zero
493 * if no bits set.
494 */
495 int
496 _mesa_ffsll(int64_t val)
497 {
498 #ifdef ffsll
499 return ffsll(val);
500 #else
501 int bit;
502
503 assert(sizeof(val) == 8);
504
505 bit = _mesa_ffs((int32_t)val);
506 if (bit != 0)
507 return bit;
508
509 bit = _mesa_ffs((int32_t)(val >> 32));
510 if (bit != 0)
511 return 32 + bit;
512
513 return 0;
514 #endif
515 }
516
517
518 /**
519 * Return number of bits set in given GLuint.
520 */
521 unsigned int
522 _mesa_bitcount(unsigned int n)
523 {
524 #if defined(__GNUC__) && \
525 ((_GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
526 return __builtin_popcount(n);
527 #else
528 unsigned int bits;
529 for (bits = 0; n > 0; n = n >> 1) {
530 bits += (n & 1);
531 }
532 return bits;
533 #endif
534 }
535
536
537 /**
538 * Convert a 4-byte float to a 2-byte half float.
539 * Based on code from:
540 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
541 */
542 GLhalfARB
543 _mesa_float_to_half(float val)
544 {
545 const fi_type fi = {val};
546 const int flt_m = fi.i & 0x7fffff;
547 const int flt_e = (fi.i >> 23) & 0xff;
548 const int flt_s = (fi.i >> 31) & 0x1;
549 int s, e, m = 0;
550 GLhalfARB result;
551
552 /* sign bit */
553 s = flt_s;
554
555 /* handle special cases */
556 if ((flt_e == 0) && (flt_m == 0)) {
557 /* zero */
558 /* m = 0; - already set */
559 e = 0;
560 }
561 else if ((flt_e == 0) && (flt_m != 0)) {
562 /* denorm -- denorm float maps to 0 half */
563 /* m = 0; - already set */
564 e = 0;
565 }
566 else if ((flt_e == 0xff) && (flt_m == 0)) {
567 /* infinity */
568 /* m = 0; - already set */
569 e = 31;
570 }
571 else if ((flt_e == 0xff) && (flt_m != 0)) {
572 /* NaN */
573 m = 1;
574 e = 31;
575 }
576 else {
577 /* regular number */
578 const int new_exp = flt_e - 127;
579 if (new_exp < -24) {
580 /* this maps to 0 */
581 /* m = 0; - already set */
582 e = 0;
583 }
584 else if (new_exp < -14) {
585 /* this maps to a denorm */
586 unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
587 e = 0;
588 switch (exp_val) {
589 case 0:
590 _mesa_warning(NULL,
591 "float_to_half: logical error in denorm creation!\n");
592 /* m = 0; - already set */
593 break;
594 case 1: m = 512 + (flt_m >> 14); break;
595 case 2: m = 256 + (flt_m >> 15); break;
596 case 3: m = 128 + (flt_m >> 16); break;
597 case 4: m = 64 + (flt_m >> 17); break;
598 case 5: m = 32 + (flt_m >> 18); break;
599 case 6: m = 16 + (flt_m >> 19); break;
600 case 7: m = 8 + (flt_m >> 20); break;
601 case 8: m = 4 + (flt_m >> 21); break;
602 case 9: m = 2 + (flt_m >> 22); break;
603 case 10: m = 1; break;
604 }
605 }
606 else if (new_exp > 15) {
607 /* map this value to infinity */
608 /* m = 0; - already set */
609 e = 31;
610 }
611 else {
612 /* regular */
613 e = new_exp + 15;
614 m = flt_m >> 13;
615 }
616 }
617
618 result = (s << 15) | (e << 10) | m;
619 return result;
620 }
621
622
623 /**
624 * Convert a 2-byte half float to a 4-byte float.
625 * Based on code from:
626 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
627 */
628 float
629 _mesa_half_to_float(GLhalfARB val)
630 {
631 /* XXX could also use a 64K-entry lookup table */
632 const int m = val & 0x3ff;
633 const int e = (val >> 10) & 0x1f;
634 const int s = (val >> 15) & 0x1;
635 int flt_m, flt_e, flt_s;
636 fi_type fi;
637 float result;
638
639 /* sign bit */
640 flt_s = s;
641
642 /* handle special cases */
643 if ((e == 0) && (m == 0)) {
644 /* zero */
645 flt_m = 0;
646 flt_e = 0;
647 }
648 else if ((e == 0) && (m != 0)) {
649 /* denorm -- denorm half will fit in non-denorm single */
650 const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
651 float mantissa = ((float) (m)) / 1024.0f;
652 float sign = s ? -1.0f : 1.0f;
653 return sign * mantissa * half_denorm;
654 }
655 else if ((e == 31) && (m == 0)) {
656 /* infinity */
657 flt_e = 0xff;
658 flt_m = 0;
659 }
660 else if ((e == 31) && (m != 0)) {
661 /* NaN */
662 flt_e = 0xff;
663 flt_m = 1;
664 }
665 else {
666 /* regular */
667 flt_e = e + 112;
668 flt_m = m << 13;
669 }
670
671 fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
672 result = fi.f;
673 return result;
674 }
675
676 /*@}*/
677
678
679 /**********************************************************************/
680 /** \name Sort & Search */
681 /*@{*/
682
683 /**
684 * Wrapper for bsearch().
685 */
686 void *
687 _mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
688 int (*compar)(const void *, const void *) )
689 {
690 #if defined(_WIN32_WCE)
691 void *mid;
692 int cmp;
693 while (nmemb) {
694 nmemb >>= 1;
695 mid = (char *)base + nmemb * size;
696 cmp = (*compar)(key, mid);
697 if (cmp == 0)
698 return mid;
699 if (cmp > 0) {
700 base = (char *)mid + size;
701 --nmemb;
702 }
703 }
704 return NULL;
705 #else
706 return bsearch(key, base, nmemb, size, compar);
707 #endif
708 }
709
710 /*@}*/
711
712
713 /**********************************************************************/
714 /** \name Environment vars */
715 /*@{*/
716
717 /**
718 * Wrapper for getenv().
719 */
720 char *
721 _mesa_getenv( const char *var )
722 {
723 #if defined(_XBOX) || defined(_WIN32_WCE)
724 return NULL;
725 #else
726 return getenv(var);
727 #endif
728 }
729
730 /*@}*/
731
732
733 /**********************************************************************/
734 /** \name String */
735 /*@{*/
736
737 /**
738 * Implemented using malloc() and strcpy.
739 * Note that NULL is handled accordingly.
740 */
741 char *
742 _mesa_strdup( const char *s )
743 {
744 if (s) {
745 size_t l = strlen(s);
746 char *s2 = (char *) malloc(l + 1);
747 if (s2)
748 strcpy(s2, s);
749 return s2;
750 }
751 else {
752 return NULL;
753 }
754 }
755
756 /** Wrapper around strtof() */
757 float
758 _mesa_strtof( const char *s, char **end )
759 {
760 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
761 static locale_t loc = NULL;
762 if (!loc) {
763 loc = newlocale(LC_CTYPE_MASK, "C", NULL);
764 }
765 return strtof_l(s, end, loc);
766 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
767 return strtof(s, end);
768 #else
769 return (float)strtod(s, end);
770 #endif
771 }
772
773 /** Compute simple checksum/hash for a string */
774 unsigned int
775 _mesa_str_checksum(const char *str)
776 {
777 /* This could probably be much better */
778 unsigned int sum, i;
779 const char *c;
780 sum = i = 1;
781 for (c = str; *c; c++, i++)
782 sum += *c * (i % 100);
783 return sum + i;
784 }
785
786
787 /*@}*/
788
789
790 /** Wrapper around vsnprintf() */
791 int
792 _mesa_snprintf( char *str, size_t size, const char *fmt, ... )
793 {
794 int r;
795 va_list args;
796 va_start( args, fmt );
797 r = vsnprintf( str, size, fmt, args );
798 va_end( args );
799 return r;
800 }
801
802
803 /**********************************************************************/
804 /** \name Diagnostics */
805 /*@{*/
806
807 static void
808 output_if_debug(const char *prefixString, const char *outputString,
809 GLboolean newline)
810 {
811 static int debug = -1;
812
813 /* Check the MESA_DEBUG environment variable if it hasn't
814 * been checked yet. We only have to check it once...
815 */
816 if (debug == -1) {
817 char *env = _mesa_getenv("MESA_DEBUG");
818
819 /* In a debug build, we print warning messages *unless*
820 * MESA_DEBUG is 0. In a non-debug build, we don't
821 * print warning messages *unless* MESA_DEBUG is
822 * set *to any value*.
823 */
824 #ifdef DEBUG
825 debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
826 #else
827 debug = (env != NULL) ? 1 : 0;
828 #endif
829 }
830
831 /* Now only print the string if we're required to do so. */
832 if (debug) {
833 fprintf(stderr, "%s: %s", prefixString, outputString);
834 if (newline)
835 fprintf(stderr, "\n");
836
837 #if defined(_WIN32) && !defined(_WIN32_WCE)
838 /* stderr from windows applications without console is not usually
839 * visible, so communicate with the debugger instead */
840 {
841 char buf[4096];
842 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
843 OutputDebugStringA(buf);
844 }
845 #endif
846 }
847 }
848
849
850 /**
851 * Return string version of GL error code.
852 */
853 static const char *
854 error_string( GLenum error )
855 {
856 switch (error) {
857 case GL_NO_ERROR:
858 return "GL_NO_ERROR";
859 case GL_INVALID_VALUE:
860 return "GL_INVALID_VALUE";
861 case GL_INVALID_ENUM:
862 return "GL_INVALID_ENUM";
863 case GL_INVALID_OPERATION:
864 return "GL_INVALID_OPERATION";
865 case GL_STACK_OVERFLOW:
866 return "GL_STACK_OVERFLOW";
867 case GL_STACK_UNDERFLOW:
868 return "GL_STACK_UNDERFLOW";
869 case GL_OUT_OF_MEMORY:
870 return "GL_OUT_OF_MEMORY";
871 case GL_TABLE_TOO_LARGE:
872 return "GL_TABLE_TOO_LARGE";
873 case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
874 return "GL_INVALID_FRAMEBUFFER_OPERATION";
875 default:
876 return "unknown";
877 }
878 }
879
880
881 /**
882 * When a new type of error is recorded, print a message describing
883 * previous errors which were accumulated.
884 */
885 static void
886 flush_delayed_errors( struct gl_context *ctx )
887 {
888 char s[MAXSTRING];
889
890 if (ctx->ErrorDebugCount) {
891 _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
892 ctx->ErrorDebugCount,
893 error_string(ctx->ErrorValue));
894
895 output_if_debug("Mesa", s, GL_TRUE);
896
897 ctx->ErrorDebugCount = 0;
898 }
899 }
900
901
902 /**
903 * Report a warning (a recoverable error condition) to stderr if
904 * either DEBUG is defined or the MESA_DEBUG env var is set.
905 *
906 * \param ctx GL context.
907 * \param fmtString printf()-like format string.
908 */
909 void
910 _mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
911 {
912 char str[MAXSTRING];
913 va_list args;
914 va_start( args, fmtString );
915 (void) vsnprintf( str, MAXSTRING, fmtString, args );
916 va_end( args );
917
918 if (ctx)
919 flush_delayed_errors( ctx );
920
921 output_if_debug("Mesa warning", str, GL_TRUE);
922 }
923
924
925 /**
926 * Report an internal implementation problem.
927 * Prints the message to stderr via fprintf().
928 *
929 * \param ctx GL context.
930 * \param fmtString problem description string.
931 */
932 void
933 _mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
934 {
935 va_list args;
936 char str[MAXSTRING];
937 (void) ctx;
938
939 va_start( args, fmtString );
940 vsnprintf( str, MAXSTRING, fmtString, args );
941 va_end( args );
942
943 fprintf(stderr, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING, str);
944 fprintf(stderr, "Please report at bugzilla.freedesktop.org\n");
945 }
946
947
948 /**
949 * Record an OpenGL state error. These usually occur when the user
950 * passes invalid parameters to a GL function.
951 *
952 * If debugging is enabled (either at compile-time via the DEBUG macro, or
953 * run-time via the MESA_DEBUG environment variable), report the error with
954 * _mesa_debug().
955 *
956 * \param ctx the GL context.
957 * \param error the error value.
958 * \param fmtString printf() style format string, followed by optional args
959 */
960 void
961 _mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
962 {
963 static GLint debug = -1;
964
965 /* Check debug environment variable only once:
966 */
967 if (debug == -1) {
968 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
969
970 #ifdef DEBUG
971 if (debugEnv && strstr(debugEnv, "silent"))
972 debug = GL_FALSE;
973 else
974 debug = GL_TRUE;
975 #else
976 if (debugEnv)
977 debug = GL_TRUE;
978 else
979 debug = GL_FALSE;
980 #endif
981 }
982
983 if (debug) {
984 if (ctx->ErrorValue == error &&
985 ctx->ErrorDebugFmtString == fmtString) {
986 ctx->ErrorDebugCount++;
987 }
988 else {
989 char s[MAXSTRING], s2[MAXSTRING];
990 va_list args;
991
992 flush_delayed_errors( ctx );
993
994 va_start(args, fmtString);
995 vsnprintf(s, MAXSTRING, fmtString, args);
996 va_end(args);
997
998 _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
999 output_if_debug("Mesa: User error", s2, GL_TRUE);
1000
1001 ctx->ErrorDebugFmtString = fmtString;
1002 ctx->ErrorDebugCount = 0;
1003 }
1004 }
1005
1006 _mesa_record_error(ctx, error);
1007 }
1008
1009
1010 /**
1011 * Report debug information. Print error message to stderr via fprintf().
1012 * No-op if DEBUG mode not enabled.
1013 *
1014 * \param ctx GL context.
1015 * \param fmtString printf()-style format string, followed by optional args.
1016 */
1017 void
1018 _mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
1019 {
1020 #ifdef DEBUG
1021 char s[MAXSTRING];
1022 va_list args;
1023 va_start(args, fmtString);
1024 vsnprintf(s, MAXSTRING, fmtString, args);
1025 va_end(args);
1026 output_if_debug("Mesa", s, GL_FALSE);
1027 #endif /* DEBUG */
1028 (void) ctx;
1029 (void) fmtString;
1030 }
1031
1032 /*@}*/