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