mesa: Restore 78-column wrapping of license text in C-style comments.
[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 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
41 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
42 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
43 * OTHER DEALINGS IN THE SOFTWARE.
44 */
45
46
47
48 #include "imports.h"
49 #include "context.h"
50 #include "mtypes.h"
51 #include "version.h"
52
53 #ifdef _GNU_SOURCE
54 #include <locale.h>
55 #ifdef __APPLE__
56 #include <xlocale.h>
57 #endif
58 #endif
59
60
61 #ifdef _WIN32
62 #define vsnprintf _vsnprintf
63 #elif defined(__IBMC__) || defined(__IBMCPP__)
64 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list arg);
65 #endif
66
67 /**********************************************************************/
68 /** \name Memory */
69 /*@{*/
70
71 /**
72 * Allocate aligned memory.
73 *
74 * \param bytes number of bytes to allocate.
75 * \param alignment alignment (must be greater than zero).
76 *
77 * Allocates extra memory to accommodate rounding up the address for
78 * alignment and to record the real malloc address.
79 *
80 * \sa _mesa_align_free().
81 */
82 void *
83 _mesa_align_malloc(size_t bytes, unsigned long alignment)
84 {
85 #if defined(HAVE_POSIX_MEMALIGN)
86 void *mem;
87 int err = posix_memalign(& mem, alignment, bytes);
88 if (err)
89 return NULL;
90 return mem;
91 #elif defined(_WIN32) && defined(_MSC_VER)
92 return _aligned_malloc(bytes, alignment);
93 #else
94 uintptr_t ptr, buf;
95
96 ASSERT( alignment > 0 );
97
98 ptr = (uintptr_t)malloc(bytes + alignment + sizeof(void *));
99 if (!ptr)
100 return NULL;
101
102 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
103 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
104
105 #ifdef DEBUG
106 /* mark the non-aligned area */
107 while ( ptr < buf - sizeof(void *) ) {
108 *(unsigned long *)ptr = 0xcdcdcdcd;
109 ptr += sizeof(unsigned long);
110 }
111 #endif
112
113 return (void *) buf;
114 #endif /* defined(HAVE_POSIX_MEMALIGN) */
115 }
116
117 /**
118 * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
119 * malloc()
120 */
121 void *
122 _mesa_align_calloc(size_t bytes, unsigned long alignment)
123 {
124 #if defined(HAVE_POSIX_MEMALIGN)
125 void *mem;
126
127 mem = _mesa_align_malloc(bytes, alignment);
128 if (mem != NULL) {
129 (void) memset(mem, 0, bytes);
130 }
131
132 return mem;
133 #elif defined(_WIN32) && defined(_MSC_VER)
134 void *mem;
135
136 mem = _aligned_malloc(bytes, alignment);
137 if (mem != NULL) {
138 (void) memset(mem, 0, bytes);
139 }
140
141 return mem;
142 #else
143 uintptr_t ptr, buf;
144
145 ASSERT( alignment > 0 );
146
147 ptr = (uintptr_t)calloc(1, bytes + alignment + sizeof(void *));
148 if (!ptr)
149 return NULL;
150
151 buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
152 *(uintptr_t *)(buf - sizeof(void *)) = ptr;
153
154 #ifdef DEBUG
155 /* mark the non-aligned area */
156 while ( ptr < buf - sizeof(void *) ) {
157 *(unsigned long *)ptr = 0xcdcdcdcd;
158 ptr += sizeof(unsigned long);
159 }
160 #endif
161
162 return (void *)buf;
163 #endif /* defined(HAVE_POSIX_MEMALIGN) */
164 }
165
166 /**
167 * Free memory which was allocated with either _mesa_align_malloc()
168 * or _mesa_align_calloc().
169 * \param ptr pointer to the memory to be freed.
170 * The actual address to free is stored in the word immediately before the
171 * address the client sees.
172 */
173 void
174 _mesa_align_free(void *ptr)
175 {
176 #if defined(HAVE_POSIX_MEMALIGN)
177 free(ptr);
178 #elif defined(_WIN32) && defined(_MSC_VER)
179 _aligned_free(ptr);
180 #else
181 void **cubbyHole = (void **) ((char *) ptr - sizeof(void *));
182 void *realAddr = *cubbyHole;
183 free(realAddr);
184 #endif /* defined(HAVE_POSIX_MEMALIGN) */
185 }
186
187 /**
188 * Reallocate memory, with alignment.
189 */
190 void *
191 _mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
192 unsigned long alignment)
193 {
194 #if defined(_WIN32) && defined(_MSC_VER)
195 (void) oldSize;
196 return _aligned_realloc(oldBuffer, newSize, alignment);
197 #else
198 const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
199 void *newBuf = _mesa_align_malloc(newSize, alignment);
200 if (newBuf && oldBuffer && copySize > 0) {
201 memcpy(newBuf, oldBuffer, copySize);
202 }
203 if (oldBuffer)
204 _mesa_align_free(oldBuffer);
205 return newBuf;
206 #endif
207 }
208
209
210
211 /** Reallocate memory */
212 void *
213 _mesa_realloc(void *oldBuffer, size_t oldSize, size_t newSize)
214 {
215 const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
216 void *newBuffer = malloc(newSize);
217 if (newBuffer && oldBuffer && copySize > 0)
218 memcpy(newBuffer, oldBuffer, copySize);
219 free(oldBuffer);
220 return newBuffer;
221 }
222
223 /*@}*/
224
225
226 /**********************************************************************/
227 /** \name Math */
228 /*@{*/
229
230
231 #ifndef __GNUC__
232 /**
233 * Find the first bit set in a word.
234 */
235 int
236 ffs(int i)
237 {
238 register int bit = 0;
239 if (i != 0) {
240 if ((i & 0xffff) == 0) {
241 bit += 16;
242 i >>= 16;
243 }
244 if ((i & 0xff) == 0) {
245 bit += 8;
246 i >>= 8;
247 }
248 if ((i & 0xf) == 0) {
249 bit += 4;
250 i >>= 4;
251 }
252 while ((i & 1) == 0) {
253 bit++;
254 i >>= 1;
255 }
256 bit++;
257 }
258 return bit;
259 }
260
261
262 /**
263 * Find position of first bit set in given value.
264 * XXX Warning: this function can only be used on 64-bit systems!
265 * \return position of least-significant bit set, starting at 1, return zero
266 * if no bits set.
267 */
268 int
269 ffsll(long long int val)
270 {
271 int bit;
272
273 assert(sizeof(val) == 8);
274
275 bit = ffs((int) val);
276 if (bit != 0)
277 return bit;
278
279 bit = ffs((int) (val >> 32));
280 if (bit != 0)
281 return 32 + bit;
282
283 return 0;
284 }
285 #endif /* __GNUC__ */
286
287
288 #if !defined(__GNUC__) ||\
289 ((__GNUC__ * 100 + __GNUC_MINOR__) < 304) /* Not gcc 3.4 or later */
290 /**
291 * Return number of bits set in given GLuint.
292 */
293 unsigned int
294 _mesa_bitcount(unsigned int n)
295 {
296 unsigned int bits;
297 for (bits = 0; n > 0; n = n >> 1) {
298 bits += (n & 1);
299 }
300 return bits;
301 }
302
303 /**
304 * Return number of bits set in given 64-bit uint.
305 */
306 unsigned int
307 _mesa_bitcount_64(uint64_t n)
308 {
309 unsigned int bits;
310 for (bits = 0; n > 0; n = n >> 1) {
311 bits += (n & 1);
312 }
313 return bits;
314 }
315 #endif
316
317
318 /* Using C99 rounding functions for roundToEven() implementation is
319 * difficult, because round(), rint, and nearbyint() are affected by
320 * fesetenv(), which the application may have done for its own
321 * purposes. Mesa's IROUND macro is close to what we want, but it
322 * rounds away from 0 on n + 0.5.
323 */
324 int
325 _mesa_round_to_even(float val)
326 {
327 int rounded = IROUND(val);
328
329 if (val - floor(val) == 0.5) {
330 if (rounded % 2 != 0)
331 rounded += val > 0 ? -1 : 1;
332 }
333
334 return rounded;
335 }
336
337
338 /**
339 * Convert a 4-byte float to a 2-byte half float.
340 *
341 * Not all float32 values can be represented exactly as a float16 value. We
342 * round such intermediate float32 values to the nearest float16. When the
343 * float32 lies exactly between to float16 values, we round to the one with
344 * an even mantissa.
345 *
346 * This rounding behavior has several benefits:
347 * - It has no sign bias.
348 *
349 * - It reproduces the behavior of real hardware: opcode F32TO16 in Intel's
350 * GPU ISA.
351 *
352 * - By reproducing the behavior of the GPU (at least on Intel hardware),
353 * compile-time evaluation of constant packHalf2x16 GLSL expressions will
354 * result in the same value as if the expression were executed on the GPU.
355 */
356 GLhalfARB
357 _mesa_float_to_half(float val)
358 {
359 const fi_type fi = {val};
360 const int flt_m = fi.i & 0x7fffff;
361 const int flt_e = (fi.i >> 23) & 0xff;
362 const int flt_s = (fi.i >> 31) & 0x1;
363 int s, e, m = 0;
364 GLhalfARB result;
365
366 /* sign bit */
367 s = flt_s;
368
369 /* handle special cases */
370 if ((flt_e == 0) && (flt_m == 0)) {
371 /* zero */
372 /* m = 0; - already set */
373 e = 0;
374 }
375 else if ((flt_e == 0) && (flt_m != 0)) {
376 /* denorm -- denorm float maps to 0 half */
377 /* m = 0; - already set */
378 e = 0;
379 }
380 else if ((flt_e == 0xff) && (flt_m == 0)) {
381 /* infinity */
382 /* m = 0; - already set */
383 e = 31;
384 }
385 else if ((flt_e == 0xff) && (flt_m != 0)) {
386 /* NaN */
387 m = 1;
388 e = 31;
389 }
390 else {
391 /* regular number */
392 const int new_exp = flt_e - 127;
393 if (new_exp < -14) {
394 /* The float32 lies in the range (0.0, min_normal16) and is rounded
395 * to a nearby float16 value. The result will be either zero, subnormal,
396 * or normal.
397 */
398 e = 0;
399 m = _mesa_round_to_even((1 << 24) * fabsf(fi.f));
400 }
401 else if (new_exp > 15) {
402 /* map this value to infinity */
403 /* m = 0; - already set */
404 e = 31;
405 }
406 else {
407 /* The float32 lies in the range
408 * [min_normal16, max_normal16 + max_step16)
409 * and is rounded to a nearby float16 value. The result will be
410 * either normal or infinite.
411 */
412 e = new_exp + 15;
413 m = _mesa_round_to_even(flt_m / (float) (1 << 13));
414 }
415 }
416
417 assert(0 <= m && m <= 1024);
418 if (m == 1024) {
419 /* The float32 was rounded upwards into the range of the next exponent,
420 * so bump the exponent. This correctly handles the case where f32
421 * should be rounded up to float16 infinity.
422 */
423 ++e;
424 m = 0;
425 }
426
427 result = (s << 15) | (e << 10) | m;
428 return result;
429 }
430
431
432 /**
433 * Convert a 2-byte half float to a 4-byte float.
434 * Based on code from:
435 * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
436 */
437 float
438 _mesa_half_to_float(GLhalfARB val)
439 {
440 /* XXX could also use a 64K-entry lookup table */
441 const int m = val & 0x3ff;
442 const int e = (val >> 10) & 0x1f;
443 const int s = (val >> 15) & 0x1;
444 int flt_m, flt_e, flt_s;
445 fi_type fi;
446 float result;
447
448 /* sign bit */
449 flt_s = s;
450
451 /* handle special cases */
452 if ((e == 0) && (m == 0)) {
453 /* zero */
454 flt_m = 0;
455 flt_e = 0;
456 }
457 else if ((e == 0) && (m != 0)) {
458 /* denorm -- denorm half will fit in non-denorm single */
459 const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
460 float mantissa = ((float) (m)) / 1024.0f;
461 float sign = s ? -1.0f : 1.0f;
462 return sign * mantissa * half_denorm;
463 }
464 else if ((e == 31) && (m == 0)) {
465 /* infinity */
466 flt_e = 0xff;
467 flt_m = 0;
468 }
469 else if ((e == 31) && (m != 0)) {
470 /* NaN */
471 flt_e = 0xff;
472 flt_m = 1;
473 }
474 else {
475 /* regular */
476 flt_e = e + 112;
477 flt_m = m << 13;
478 }
479
480 fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
481 result = fi.f;
482 return result;
483 }
484
485 /*@}*/
486
487
488 /**********************************************************************/
489 /** \name Sort & Search */
490 /*@{*/
491
492 /**
493 * Wrapper for bsearch().
494 */
495 void *
496 _mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
497 int (*compar)(const void *, const void *) )
498 {
499 #if defined(_WIN32_WCE)
500 void *mid;
501 int cmp;
502 while (nmemb) {
503 nmemb >>= 1;
504 mid = (char *)base + nmemb * size;
505 cmp = (*compar)(key, mid);
506 if (cmp == 0)
507 return mid;
508 if (cmp > 0) {
509 base = (char *)mid + size;
510 --nmemb;
511 }
512 }
513 return NULL;
514 #else
515 return bsearch(key, base, nmemb, size, compar);
516 #endif
517 }
518
519 /*@}*/
520
521
522 /**********************************************************************/
523 /** \name Environment vars */
524 /*@{*/
525
526 /**
527 * Wrapper for getenv().
528 */
529 char *
530 _mesa_getenv( const char *var )
531 {
532 #if defined(_XBOX) || defined(_WIN32_WCE)
533 return NULL;
534 #else
535 return getenv(var);
536 #endif
537 }
538
539 /*@}*/
540
541
542 /**********************************************************************/
543 /** \name String */
544 /*@{*/
545
546 /**
547 * Implemented using malloc() and strcpy.
548 * Note that NULL is handled accordingly.
549 */
550 char *
551 _mesa_strdup( const char *s )
552 {
553 if (s) {
554 size_t l = strlen(s);
555 char *s2 = malloc(l + 1);
556 if (s2)
557 strcpy(s2, s);
558 return s2;
559 }
560 else {
561 return NULL;
562 }
563 }
564
565 /** Wrapper around strtof() */
566 float
567 _mesa_strtof( const char *s, char **end )
568 {
569 #if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__) && \
570 !defined(ANDROID) && !defined(__HAIKU__) && !defined(__UCLIBC__)
571 static locale_t loc = NULL;
572 if (!loc) {
573 loc = newlocale(LC_CTYPE_MASK, "C", NULL);
574 }
575 return strtof_l(s, end, loc);
576 #elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
577 return strtof(s, end);
578 #else
579 return (float)strtod(s, end);
580 #endif
581 }
582
583 /** Compute simple checksum/hash for a string */
584 unsigned int
585 _mesa_str_checksum(const char *str)
586 {
587 /* This could probably be much better */
588 unsigned int sum, i;
589 const char *c;
590 sum = i = 1;
591 for (c = str; *c; c++, i++)
592 sum += *c * (i % 100);
593 return sum + i;
594 }
595
596
597 /*@}*/
598
599
600 /** Needed due to #ifdef's, above. */
601 int
602 _mesa_vsnprintf(char *str, size_t size, const char *fmt, va_list args)
603 {
604 return vsnprintf( str, size, fmt, args);
605 }
606
607 /** Wrapper around vsnprintf() */
608 int
609 _mesa_snprintf( char *str, size_t size, const char *fmt, ... )
610 {
611 int r;
612 va_list args;
613 va_start( args, fmt );
614 r = vsnprintf( str, size, fmt, args );
615 va_end( args );
616 return r;
617 }
618
619