Fix potential buffer overflow with temp sample space
[openal-soft.git] / Alc / helpers.c
blob03672a17715d11a0b7ab9328004f44d9d343bebf
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2011 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <stdlib.h>
24 #include <time.h>
25 #include <errno.h>
26 #include <stdarg.h>
27 #ifdef HAVE_DLFCN_H
28 #include <dlfcn.h>
29 #endif
30 #ifdef HAVE_CPUID_H
31 #include <cpuid.h>
32 #endif
33 #ifdef HAVE_FLOAT_H
34 #include <float.h>
35 #endif
36 #ifdef HAVE_IEEEFP_H
37 #include <ieeefp.h>
38 #endif
40 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
41 #define INITGUID
42 #include <windows.h>
43 #ifdef HAVE_GUIDDEF_H
44 #include <guiddef.h>
45 #else
46 #include <initguid.h>
47 #endif
49 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
50 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
52 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
54 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
55 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
56 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
57 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
59 #ifdef HAVE_MMDEVAPI
60 #include <devpropdef.h>
62 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
63 #endif
65 #endif
67 #include "alMain.h"
69 ALuint CPUCapFlags = 0;
72 void FillCPUCaps(ALuint capfilter)
74 ALuint caps = 0;
76 #if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)
77 /* FIXME: We really should get this for all available CPUs in case different
78 * CPUs have different caps (is that possible on one machine?). */
79 #ifdef HAVE_CPUID_H
80 union {
81 unsigned int regs[4];
82 char str[sizeof(unsigned int[4])];
83 } cpuinf[3];
85 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
86 ERR("Failed to get CPUID\n");
87 else
89 unsigned int maxfunc = cpuinf[0].regs[0];
90 unsigned int maxextfunc = 0;
92 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
93 maxextfunc = cpuinf[0].regs[0];
94 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
96 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
97 if(maxextfunc >= 0x80000004 &&
98 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
99 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
100 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
101 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
103 if(maxfunc >= 1 &&
104 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
106 #ifdef bit_SSE
107 if((cpuinf[0].regs[3]&bit_SSE))
108 caps |= CPU_CAP_SSE;
109 #endif
112 #endif
113 #endif
114 #ifdef HAVE_NEON
115 /* Assume Neon support if compiled with it */
116 caps |= CPU_CAP_NEON;
117 #endif
119 TRACE("Got caps:%s%s%s\n", ((caps&CPU_CAP_SSE)?((capfilter&CPU_CAP_SSE)?" SSE":" (SSE)"):""),
120 ((caps&CPU_CAP_NEON)?((capfilter&CPU_CAP_NEON)?" Neon":" (Neon)"):""),
121 ((!caps)?" -none-":""));
122 CPUCapFlags = caps & capfilter;
126 void *al_malloc(size_t alignment, size_t size)
128 #if defined(HAVE_ALIGNED_ALLOC)
129 size = (size+(alignment-1))&~(alignment-1);
130 return aligned_alloc(alignment, size);
131 #elif defined(HAVE_POSIX_MEMALIGN)
132 void *ret;
133 if(posix_memalign(&ret, alignment, size) == 0)
134 return ret;
135 return NULL;
136 #elif defined(HAVE__ALIGNED_MALLOC)
137 return _aligned_malloc(size, alignment);
138 #else
139 char *ret = malloc(size+alignment);
140 if(ret != NULL)
142 *(ret++) = 0x00;
143 while(((ALintptrEXT)ret&(alignment-1)) != 0)
144 *(ret++) = 0x55;
146 return ret;
147 #endif
150 void *al_calloc(size_t alignment, size_t size)
152 void *ret = al_malloc(alignment, size);
153 if(ret) memset(ret, 0, size);
154 return ret;
157 void al_free(void *ptr)
159 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
160 free(ptr);
161 #elif defined(HAVE__ALIGNED_MALLOC)
162 _aligned_free(ptr);
163 #else
164 if(ptr != NULL)
166 char *finder = ptr;
167 do {
168 --finder;
169 } while(*finder == 0x55);
170 free(finder);
172 #endif
176 #if (defined(HAVE___CONTROL87_2) || defined(HAVE__CONTROLFP)) && (defined(__x86_64__) || defined(_M_X64))
177 /* Win64 doesn't allow us to set the precision control. */
178 #undef _MCW_PC
179 #define _MCW_PC 0
180 #endif
182 void SetMixerFPUMode(FPUCtl *ctl)
184 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
185 unsigned short fpuState;
186 __asm__ __volatile__("fnstcw %0" : "=m" (*&fpuState));
187 ctl->state = fpuState;
188 fpuState &= ~0x300; /* clear precision to single */
189 fpuState |= 0xC00; /* set round-to-zero */
190 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
191 #ifdef HAVE_SSE
192 if((CPUCapFlags&CPU_CAP_SSE))
194 int sseState;
195 __asm__ __volatile__("stmxcsr %0" : "=m" (*&sseState));
196 ctl->sse_state = sseState;
197 sseState |= 0x0C00; /* set round-to-zero */
198 sseState |= 0x8000; /* set flush-to-zero */
199 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
201 #endif
202 #elif defined(HAVE___CONTROL87_2)
203 int mode;
204 __control87_2(0, 0, &ctl->state, &ctl->sse_state);
205 __control87_2(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC, &mode, NULL);
206 #ifdef HAVE_SSE
207 if((CPUCapFlags&CPU_CAP_SSE))
208 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
209 #endif
210 #elif defined(HAVE__CONTROLFP)
211 ctl->state = _controlfp(0, 0);
212 (void)_controlfp(_RC_CHOP|_PC_24, _MCW_RC|_MCW_PC);
213 #elif defined(HAVE_FESETROUND)
214 ctl->state = fegetround();
215 #ifdef FE_TOWARDZERO
216 fesetround(FE_TOWARDZERO);
217 #endif
218 #endif
221 void RestoreFPUMode(const FPUCtl *ctl)
223 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
224 unsigned short fpuState = ctl->state;
225 __asm__ __volatile__("fldcw %0" : : "m" (*&fpuState));
226 #ifdef HAVE_SSE
227 if((CPUCapFlags&CPU_CAP_SSE))
228 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
229 #endif
230 #elif defined(HAVE___CONTROL87_2)
231 int mode;
232 __control87_2(ctl->state, _MCW_RC|_MCW_PC, &mode, NULL);
233 #ifdef HAVE_SSE
234 if((CPUCapFlags&CPU_CAP_SSE))
235 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
236 #endif
237 #elif defined(HAVE__CONTROLFP)
238 _controlfp(ctl->state, _MCW_RC|_MCW_PC);
239 #elif defined(HAVE_FESETROUND)
240 fesetround(ctl->state);
241 #endif
245 #ifdef _WIN32
246 void pthread_once(pthread_once_t *once, void (*callback)(void))
248 LONG ret;
249 while((ret=InterlockedExchange(once, 1)) == 1)
250 sched_yield();
251 if(ret == 0)
252 callback();
253 InterlockedExchange(once, 2);
257 int pthread_key_create(pthread_key_t *key, void (*callback)(void*))
259 *key = TlsAlloc();
260 if(callback)
261 InsertUIntMapEntry(&TlsDestructor, *key, callback);
262 return 0;
265 int pthread_key_delete(pthread_key_t key)
267 InsertUIntMapEntry(&TlsDestructor, key, NULL);
268 TlsFree(key);
269 return 0;
272 void *pthread_getspecific(pthread_key_t key)
273 { return TlsGetValue(key); }
275 int pthread_setspecific(pthread_key_t key, void *val)
277 TlsSetValue(key, val);
278 return 0;
282 void *LoadLib(const char *name)
283 { return LoadLibraryA(name); }
284 void CloseLib(void *handle)
285 { FreeLibrary((HANDLE)handle); }
286 void *GetSymbol(void *handle, const char *name)
288 void *ret;
290 ret = (void*)GetProcAddress((HANDLE)handle, name);
291 if(ret == NULL)
292 ERR("Failed to load %s\n", name);
293 return ret;
296 WCHAR *strdupW(const WCHAR *str)
298 const WCHAR *n;
299 WCHAR *ret;
300 size_t len;
302 n = str;
303 while(*n) n++;
304 len = n - str;
306 ret = calloc(sizeof(WCHAR), len+1);
307 if(ret != NULL)
308 memcpy(ret, str, sizeof(WCHAR)*len);
309 return ret;
312 #else
314 #include <pthread.h>
315 #ifdef HAVE_PTHREAD_NP_H
316 #include <pthread_np.h>
317 #endif
318 #include <sched.h>
320 void InitializeCriticalSection(CRITICAL_SECTION *cs)
322 pthread_mutexattr_t attrib;
323 int ret;
325 ret = pthread_mutexattr_init(&attrib);
326 assert(ret == 0);
328 ret = pthread_mutexattr_settype(&attrib, PTHREAD_MUTEX_RECURSIVE);
329 #ifdef HAVE_PTHREAD_NP_H
330 if(ret != 0)
331 ret = pthread_mutexattr_setkind_np(&attrib, PTHREAD_MUTEX_RECURSIVE);
332 #endif
333 assert(ret == 0);
334 ret = pthread_mutex_init(cs, &attrib);
335 assert(ret == 0);
337 pthread_mutexattr_destroy(&attrib);
339 void DeleteCriticalSection(CRITICAL_SECTION *cs)
341 int ret;
342 ret = pthread_mutex_destroy(cs);
343 assert(ret == 0);
345 void EnterCriticalSection(CRITICAL_SECTION *cs)
347 int ret;
348 ret = pthread_mutex_lock(cs);
349 assert(ret == 0);
351 void LeaveCriticalSection(CRITICAL_SECTION *cs)
353 int ret;
354 ret = pthread_mutex_unlock(cs);
355 assert(ret == 0);
358 /* NOTE: This wrapper isn't quite accurate as it returns an ALuint, as opposed
359 * to the expected DWORD. Both are defined as unsigned 32-bit types, however.
360 * Additionally, Win32 is supposed to measure the time since Windows started,
361 * as opposed to the actual time. */
362 ALuint timeGetTime(void)
364 #if _POSIX_TIMERS > 0
365 struct timespec ts;
366 int ret = -1;
368 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK >= 0)
369 #if _POSIX_MONOTONIC_CLOCK == 0
370 static int hasmono = 0;
371 if(hasmono > 0 || (hasmono == 0 &&
372 (hasmono=sysconf(_SC_MONOTONIC_CLOCK)) > 0))
373 #endif
374 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
375 #endif
376 if(ret != 0)
377 ret = clock_gettime(CLOCK_REALTIME, &ts);
378 assert(ret == 0);
380 return ts.tv_nsec/1000000 + ts.tv_sec*1000;
381 #else
382 struct timeval tv;
383 int ret;
385 ret = gettimeofday(&tv, NULL);
386 assert(ret == 0);
388 return tv.tv_usec/1000 + tv.tv_sec*1000;
389 #endif
392 void Sleep(ALuint t)
394 struct timespec tv, rem;
395 tv.tv_nsec = (t*1000000)%1000000000;
396 tv.tv_sec = t/1000;
398 while(nanosleep(&tv, &rem) == -1 && errno == EINTR)
399 tv = rem;
402 #ifdef HAVE_DLFCN_H
404 void *LoadLib(const char *name)
406 const char *err;
407 void *handle;
409 dlerror();
410 handle = dlopen(name, RTLD_NOW);
411 if((err=dlerror()) != NULL)
412 handle = NULL;
413 return handle;
415 void CloseLib(void *handle)
416 { dlclose(handle); }
417 void *GetSymbol(void *handle, const char *name)
419 const char *err;
420 void *sym;
422 dlerror();
423 sym = dlsym(handle, name);
424 if((err=dlerror()) != NULL)
426 WARN("Failed to load %s: %s\n", name, err);
427 sym = NULL;
429 return sym;
432 #endif
433 #endif
436 void al_print(const char *func, const char *fmt, ...)
438 char str[256];
439 int i;
441 i = snprintf(str, sizeof(str), "AL lib: %s: ", func);
442 if(i < (int)sizeof(str) && i > 0)
444 va_list ap;
445 va_start(ap, fmt);
446 vsnprintf(str+i, sizeof(str)-i, fmt, ap);
447 va_end(ap);
449 str[sizeof(str)-1] = 0;
451 fprintf(LogFile, "%s", str);
452 fflush(LogFile);
456 void SetRTPriority(void)
458 ALboolean failed = AL_FALSE;
460 #ifdef _WIN32
461 if(RTPrioLevel > 0)
462 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
463 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
464 if(RTPrioLevel > 0)
466 struct sched_param param;
467 /* Use the minimum real-time priority possible for now (on Linux this
468 * should be 1 for SCHED_RR) */
469 param.sched_priority = sched_get_priority_min(SCHED_RR);
470 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
472 #else
473 /* Real-time priority not available */
474 failed = (RTPrioLevel>0);
475 #endif
476 if(failed)
477 ERR("Failed to set priority level for thread\n");
481 static void Lock(volatile ALenum *l)
483 while(ExchangeInt(l, AL_TRUE) == AL_TRUE)
484 sched_yield();
487 static void Unlock(volatile ALenum *l)
489 ExchangeInt(l, AL_FALSE);
492 void RWLockInit(RWLock *lock)
494 lock->read_count = 0;
495 lock->write_count = 0;
496 lock->read_lock = AL_FALSE;
497 lock->read_entry_lock = AL_FALSE;
498 lock->write_lock = AL_FALSE;
501 void ReadLock(RWLock *lock)
503 Lock(&lock->read_entry_lock);
504 Lock(&lock->read_lock);
505 if(IncrementRef(&lock->read_count) == 1)
506 Lock(&lock->write_lock);
507 Unlock(&lock->read_lock);
508 Unlock(&lock->read_entry_lock);
511 void ReadUnlock(RWLock *lock)
513 if(DecrementRef(&lock->read_count) == 0)
514 Unlock(&lock->write_lock);
517 void WriteLock(RWLock *lock)
519 if(IncrementRef(&lock->write_count) == 1)
520 Lock(&lock->read_lock);
521 Lock(&lock->write_lock);
524 void WriteUnlock(RWLock *lock)
526 Unlock(&lock->write_lock);
527 if(DecrementRef(&lock->write_count) == 0)
528 Unlock(&lock->read_lock);
532 void InitUIntMap(UIntMap *map, ALsizei limit)
534 map->array = NULL;
535 map->size = 0;
536 map->maxsize = 0;
537 map->limit = limit;
538 RWLockInit(&map->lock);
541 void ResetUIntMap(UIntMap *map)
543 WriteLock(&map->lock);
544 free(map->array);
545 map->array = NULL;
546 map->size = 0;
547 map->maxsize = 0;
548 WriteUnlock(&map->lock);
551 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
553 ALsizei pos = 0;
555 WriteLock(&map->lock);
556 if(map->size > 0)
558 ALsizei low = 0;
559 ALsizei high = map->size - 1;
560 while(low < high)
562 ALsizei mid = low + (high-low)/2;
563 if(map->array[mid].key < key)
564 low = mid + 1;
565 else
566 high = mid;
568 if(map->array[low].key < key)
569 low++;
570 pos = low;
573 if(pos == map->size || map->array[pos].key != key)
575 if(map->size == map->limit)
577 WriteUnlock(&map->lock);
578 return AL_OUT_OF_MEMORY;
581 if(map->size == map->maxsize)
583 ALvoid *temp = NULL;
584 ALsizei newsize;
586 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
587 if(newsize >= map->maxsize)
588 temp = realloc(map->array, newsize*sizeof(map->array[0]));
589 if(!temp)
591 WriteUnlock(&map->lock);
592 return AL_OUT_OF_MEMORY;
594 map->array = temp;
595 map->maxsize = newsize;
598 if(pos < map->size)
599 memmove(&map->array[pos+1], &map->array[pos],
600 (map->size-pos)*sizeof(map->array[0]));
601 map->size++;
603 map->array[pos].key = key;
604 map->array[pos].value = value;
605 WriteUnlock(&map->lock);
607 return AL_NO_ERROR;
610 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
612 ALvoid *ptr = NULL;
613 WriteLock(&map->lock);
614 if(map->size > 0)
616 ALsizei low = 0;
617 ALsizei high = map->size - 1;
618 while(low < high)
620 ALsizei mid = low + (high-low)/2;
621 if(map->array[mid].key < key)
622 low = mid + 1;
623 else
624 high = mid;
626 if(map->array[low].key == key)
628 ptr = map->array[low].value;
629 if(low < map->size-1)
630 memmove(&map->array[low], &map->array[low+1],
631 (map->size-1-low)*sizeof(map->array[0]));
632 map->size--;
635 WriteUnlock(&map->lock);
636 return ptr;
639 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
641 ALvoid *ptr = NULL;
642 ReadLock(&map->lock);
643 if(map->size > 0)
645 ALsizei low = 0;
646 ALsizei high = map->size - 1;
647 while(low < high)
649 ALsizei mid = low + (high-low)/2;
650 if(map->array[mid].key < key)
651 low = mid + 1;
652 else
653 high = mid;
655 if(map->array[low].key == key)
656 ptr = map->array[low].value;
658 ReadUnlock(&map->lock);
659 return ptr;