Manually save and restore the FPU rounding mode on Windows
[openal-soft.git] / Alc / helpers.c
blobe9eb5fafdd3771e4f4232fde603bc5e82eb42769
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.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #ifdef _WIN32
22 #ifdef __MINGW32__
23 #define _WIN32_IE 0x501
24 #else
25 #define _WIN32_IE 0x400
26 #endif
27 #endif
29 #include "config.h"
31 #include <stdlib.h>
32 #include <time.h>
33 #include <errno.h>
34 #include <stdarg.h>
35 #include <ctype.h>
36 #ifdef HAVE_MALLOC_H
37 #include <malloc.h>
38 #endif
39 #ifdef HAVE_DIRENT_H
40 #include <dirent.h>
41 #endif
43 #ifdef __FreeBSD__
44 #include <sys/sysctl.h>
45 #endif
47 #ifndef AL_NO_UID_DEFS
48 #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
49 #define INITGUID
50 #include <windows.h>
51 #ifdef HAVE_GUIDDEF_H
52 #include <guiddef.h>
53 #else
54 #include <initguid.h>
55 #endif
57 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
58 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
60 DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
62 DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
63 DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
64 DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
65 DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
66 DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
68 #ifdef HAVE_MMDEVAPI
69 #include <wtypes.h>
70 #include <devpropdef.h>
71 #include <propkeydef.h>
72 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
73 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
74 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
75 #endif
76 #endif
77 #endif /* AL_NO_UID_DEFS */
79 #ifdef HAVE_DLFCN_H
80 #include <dlfcn.h>
81 #endif
82 #ifdef HAVE_INTRIN_H
83 #include <intrin.h>
84 #endif
85 #ifdef HAVE_CPUID_H
86 #include <cpuid.h>
87 #endif
88 #ifdef HAVE_SYS_SYSCONF_H
89 #include <sys/sysconf.h>
90 #endif
91 #ifdef HAVE_FLOAT_H
92 #include <float.h>
93 #endif
94 #ifdef HAVE_IEEEFP_H
95 #include <ieeefp.h>
96 #endif
98 #ifndef _WIN32
99 #include <sys/types.h>
100 #include <sys/stat.h>
101 #include <sys/mman.h>
102 #include <fcntl.h>
103 #include <unistd.h>
104 #elif defined(_WIN32_IE)
105 #include <shlobj.h>
106 #endif
108 #include "alMain.h"
109 #include "alu.h"
110 #include "atomic.h"
111 #include "uintmap.h"
112 #include "vector.h"
113 #include "alstring.h"
114 #include "compat.h"
115 #include "threads.h"
118 extern inline ALuint NextPowerOf2(ALuint value);
119 extern inline size_t RoundUp(size_t value, size_t r);
120 extern inline ALuint64 ScaleRound(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
121 extern inline ALuint64 ScaleFloor(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
122 extern inline ALuint64 ScaleCeil(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
123 extern inline ALint fastf2i(ALfloat f);
126 ALuint CPUCapFlags = 0;
129 void FillCPUCaps(ALuint capfilter)
131 ALuint caps = 0;
133 /* FIXME: We really should get this for all available CPUs in case different
134 * CPUs have different caps (is that possible on one machine?). */
135 #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
136 defined(_M_IX86) || defined(_M_X64))
137 union {
138 unsigned int regs[4];
139 char str[sizeof(unsigned int[4])];
140 } cpuinf[3];
142 if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
143 ERR("Failed to get CPUID\n");
144 else
146 unsigned int maxfunc = cpuinf[0].regs[0];
147 unsigned int maxextfunc = 0;
149 if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
150 maxextfunc = cpuinf[0].regs[0];
151 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
153 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
154 if(maxextfunc >= 0x80000004 &&
155 __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
156 __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
157 __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
158 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
160 if(maxfunc >= 1 &&
161 __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
163 if((cpuinf[0].regs[3]&(1<<25)))
165 caps |= CPU_CAP_SSE;
166 if((cpuinf[0].regs[3]&(1<<26)))
168 caps |= CPU_CAP_SSE2;
169 if((cpuinf[0].regs[2]&(1<<0)))
171 caps |= CPU_CAP_SSE3;
172 if((cpuinf[0].regs[2]&(1<<19)))
173 caps |= CPU_CAP_SSE4_1;
179 #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
180 defined(_M_IX86) || defined(_M_X64))
181 union {
182 int regs[4];
183 char str[sizeof(int[4])];
184 } cpuinf[3];
186 (__cpuid)(cpuinf[0].regs, 0);
187 if(cpuinf[0].regs[0] == 0)
188 ERR("Failed to get CPUID\n");
189 else
191 unsigned int maxfunc = cpuinf[0].regs[0];
192 unsigned int maxextfunc;
194 (__cpuid)(cpuinf[0].regs, 0x80000000);
195 maxextfunc = cpuinf[0].regs[0];
197 TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
199 TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
200 if(maxextfunc >= 0x80000004)
202 (__cpuid)(cpuinf[0].regs, 0x80000002);
203 (__cpuid)(cpuinf[1].regs, 0x80000003);
204 (__cpuid)(cpuinf[2].regs, 0x80000004);
205 TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
208 if(maxfunc >= 1)
210 (__cpuid)(cpuinf[0].regs, 1);
211 if((cpuinf[0].regs[3]&(1<<25)))
213 caps |= CPU_CAP_SSE;
214 if((cpuinf[0].regs[3]&(1<<26)))
216 caps |= CPU_CAP_SSE2;
217 if((cpuinf[0].regs[2]&(1<<0)))
219 caps |= CPU_CAP_SSE3;
220 if((cpuinf[0].regs[2]&(1<<19)))
221 caps |= CPU_CAP_SSE4_1;
227 #else
228 /* Assume support for whatever's supported if we can't check for it */
229 #if defined(HAVE_SSE4_1)
230 #warning "Assuming SSE 4.1 run-time support!"
231 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
232 #elif defined(HAVE_SSE3)
233 #warning "Assuming SSE 3 run-time support!"
234 caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
235 #elif defined(HAVE_SSE2)
236 #warning "Assuming SSE 2 run-time support!"
237 caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
238 #elif defined(HAVE_SSE)
239 #warning "Assuming SSE run-time support!"
240 caps |= CPU_CAP_SSE;
241 #endif
242 #endif
243 #ifdef HAVE_NEON
244 FILE *file = fopen("/proc/cpuinfo", "rt");
245 if(!file)
246 ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
247 else
249 char buf[256];
250 while(fgets(buf, sizeof(buf), file) != NULL)
252 size_t len;
253 char *str;
255 if(strncmp(buf, "Features\t:", 10) != 0)
256 continue;
258 len = strlen(buf);
259 while(len > 0 && isspace(buf[len-1]))
260 buf[--len] = 0;
262 TRACE("Got features string:%s\n", buf+10);
264 str = buf;
265 while((str=strstr(str, "neon")) != NULL)
267 if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
269 caps |= CPU_CAP_NEON;
270 break;
272 str++;
274 break;
277 fclose(file);
278 file = NULL;
280 #endif
282 TRACE("Extensions:%s%s%s%s%s%s\n",
283 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
284 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
285 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
286 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
287 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
288 ((!capfilter) ? " -none-" : "")
290 CPUCapFlags = caps & capfilter;
294 void SetMixerFPUMode(FPUCtl *ctl)
296 #ifdef HAVE_FENV_H
297 fegetenv(STATIC_CAST(fenv_t, ctl));
298 #ifdef _WIN32
299 /* HACK: A nasty bug in MinGW-W64 causes fegetenv and fesetenv to not save
300 * and restore the FPU rounding mode, so we have to do it manually. Don't
301 * know if this also applies to MSVC.
303 ctl->round_mode = fegetround();
304 #endif
305 #if defined(__GNUC__) && defined(HAVE_SSE)
306 /* FIXME: Some fegetenv implementations can get the SSE environment too?
307 * How to tell when it does? */
308 if((CPUCapFlags&CPU_CAP_SSE))
309 __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
310 #endif
312 #ifdef FE_TOWARDZERO
313 fesetround(FE_TOWARDZERO);
314 #endif
315 #if defined(__GNUC__) && defined(HAVE_SSE)
316 if((CPUCapFlags&CPU_CAP_SSE))
318 int sseState = ctl->sse_state;
319 sseState |= 0x6000; /* set round-to-zero */
320 sseState |= 0x8000; /* set flush-to-zero */
321 if((CPUCapFlags&CPU_CAP_SSE2))
322 sseState |= 0x0040; /* set denormals-are-zero */
323 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
325 #endif
327 #elif defined(HAVE___CONTROL87_2)
329 int mode;
330 __control87_2(0, 0, &ctl->state, NULL);
331 __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
332 #ifdef HAVE_SSE
333 if((CPUCapFlags&CPU_CAP_SSE))
335 __control87_2(0, 0, NULL, &ctl->sse_state);
336 __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
338 #endif
340 #elif defined(HAVE__CONTROLFP)
342 ctl->state = _controlfp(0, 0);
343 (void)_controlfp(_RC_CHOP, _MCW_RC);
344 #endif
347 void RestoreFPUMode(const FPUCtl *ctl)
349 #ifdef HAVE_FENV_H
350 fesetenv(STATIC_CAST(fenv_t, ctl));
351 #ifdef _WIN32
352 fesetround(ctl->round_mode);
353 #endif
354 #if defined(__GNUC__) && defined(HAVE_SSE)
355 if((CPUCapFlags&CPU_CAP_SSE))
356 __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
357 #endif
359 #elif defined(HAVE___CONTROL87_2)
361 int mode;
362 __control87_2(ctl->state, _MCW_RC, &mode, NULL);
363 #ifdef HAVE_SSE
364 if((CPUCapFlags&CPU_CAP_SSE))
365 __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
366 #endif
368 #elif defined(HAVE__CONTROLFP)
370 _controlfp(ctl->state, _MCW_RC);
371 #endif
375 static int StringSortCompare(const void *str1, const void *str2)
377 return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
380 #ifdef _WIN32
382 static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
384 WCHAR *ret = NULL;
385 while(*str)
387 if(*str == ch)
388 ret = str;
389 ++str;
391 return ret;
394 al_string GetProcPath(void)
396 al_string ret = AL_STRING_INIT_STATIC();
397 WCHAR *pathname, *sep;
398 DWORD pathlen;
399 DWORD len;
401 pathlen = 256;
402 pathname = malloc(pathlen * sizeof(pathname[0]));
403 while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
405 free(pathname);
406 pathlen <<= 1;
407 pathname = malloc(pathlen * sizeof(pathname[0]));
409 if(len == 0)
411 free(pathname);
412 ERR("Failed to get process name: error %lu\n", GetLastError());
413 return ret;
416 pathname[len] = 0;
417 if((sep = strrchrW(pathname, '\\')))
419 WCHAR *sep2 = strrchrW(pathname, '/');
420 if(sep2) *sep2 = 0;
421 else *sep = 0;
423 else if((sep = strrchrW(pathname, '/')))
424 *sep = 0;
425 alstr_copy_wcstr(&ret, pathname);
426 free(pathname);
428 TRACE("Got: %s\n", alstr_get_cstr(ret));
429 return ret;
433 static WCHAR *FromUTF8(const char *str)
435 WCHAR *out = NULL;
436 int len;
438 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
440 out = calloc(sizeof(WCHAR), len);
441 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
443 return out;
447 void *LoadLib(const char *name)
449 HANDLE hdl = NULL;
450 WCHAR *wname;
452 wname = FromUTF8(name);
453 if(!wname)
454 ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
455 else
457 hdl = LoadLibraryW(wname);
458 free(wname);
460 return hdl;
462 void CloseLib(void *handle)
463 { FreeLibrary((HANDLE)handle); }
464 void *GetSymbol(void *handle, const char *name)
466 void *ret;
468 ret = (void*)GetProcAddress((HANDLE)handle, name);
469 if(ret == NULL)
470 ERR("Failed to load %s\n", name);
471 return ret;
474 WCHAR *strdupW(const WCHAR *str)
476 const WCHAR *n;
477 WCHAR *ret;
478 size_t len;
480 n = str;
481 while(*n) n++;
482 len = n - str;
484 ret = calloc(sizeof(WCHAR), len+1);
485 if(ret != NULL)
486 memcpy(ret, str, sizeof(WCHAR)*len);
487 return ret;
490 FILE *al_fopen(const char *fname, const char *mode)
492 WCHAR *wname=NULL, *wmode=NULL;
493 FILE *file = NULL;
495 wname = FromUTF8(fname);
496 wmode = FromUTF8(mode);
497 if(!wname)
498 ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
499 else if(!wmode)
500 ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
501 else
502 file = _wfopen(wname, wmode);
504 free(wname);
505 free(wmode);
507 return file;
511 void al_print(const char *type, const char *func, const char *fmt, ...)
513 char str[1024];
514 WCHAR *wstr;
515 va_list ap;
517 va_start(ap, fmt);
518 vsnprintf(str, sizeof(str), fmt, ap);
519 va_end(ap);
521 str[sizeof(str)-1] = 0;
522 wstr = FromUTF8(str);
523 if(!wstr)
524 fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
525 else
527 fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
528 free(wstr);
529 wstr = NULL;
531 fflush(LogFile);
535 static inline int is_slash(int c)
536 { return (c == '\\' || c == '/'); }
538 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
540 al_string pathstr = AL_STRING_INIT_STATIC();
541 WIN32_FIND_DATAW fdata;
542 WCHAR *wpath;
543 HANDLE hdl;
545 alstr_copy_cstr(&pathstr, path);
546 alstr_append_cstr(&pathstr, "\\*");
547 alstr_append_cstr(&pathstr, ext);
549 TRACE("Searching %s\n", alstr_get_cstr(pathstr));
551 wpath = FromUTF8(alstr_get_cstr(pathstr));
553 hdl = FindFirstFileW(wpath, &fdata);
554 if(hdl != INVALID_HANDLE_VALUE)
556 size_t base = VECTOR_SIZE(*results);
557 do {
558 al_string str = AL_STRING_INIT_STATIC();
559 alstr_copy_cstr(&str, path);
560 alstr_append_char(&str, '\\');
561 alstr_append_wcstr(&str, fdata.cFileName);
562 TRACE("Got result %s\n", alstr_get_cstr(str));
563 VECTOR_PUSH_BACK(*results, str);
564 } while(FindNextFileW(hdl, &fdata));
565 FindClose(hdl);
567 if(VECTOR_SIZE(*results) > base)
568 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
569 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
572 free(wpath);
573 alstr_reset(&pathstr);
576 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
578 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
579 static RefCount search_lock;
580 vector_al_string results = VECTOR_INIT_STATIC();
581 size_t i;
583 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
584 althrd_yield();
586 /* If the path is absolute, use it directly. */
587 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
589 al_string path = AL_STRING_INIT_STATIC();
590 alstr_copy_cstr(&path, subdir);
591 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
592 VECTOR_FOR_EACH(char, path, FIX_SLASH);
593 #undef FIX_SLASH
595 DirectorySearch(alstr_get_cstr(path), ext, &results);
597 alstr_reset(&path);
599 else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
600 DirectorySearch(subdir, ext, &results);
601 else
603 al_string path = AL_STRING_INIT_STATIC();
604 WCHAR *cwdbuf;
606 /* Search the app-local directory. */
607 if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
609 alstr_copy_wcstr(&path, cwdbuf);
610 if(is_slash(VECTOR_BACK(path)))
612 VECTOR_POP_BACK(path);
613 *VECTOR_END(path) = 0;
616 else if(!(cwdbuf=_wgetcwd(NULL, 0)))
617 alstr_copy_cstr(&path, ".");
618 else
620 alstr_copy_wcstr(&path, cwdbuf);
621 if(is_slash(VECTOR_BACK(path)))
623 VECTOR_POP_BACK(path);
624 *VECTOR_END(path) = 0;
626 free(cwdbuf);
628 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
629 VECTOR_FOR_EACH(char, path, FIX_SLASH);
630 #undef FIX_SLASH
631 DirectorySearch(alstr_get_cstr(path), ext, &results);
633 /* Search the local and global data dirs. */
634 for(i = 0;i < COUNTOF(ids);i++)
636 WCHAR buffer[PATH_MAX];
637 if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
639 alstr_copy_wcstr(&path, buffer);
640 if(!is_slash(VECTOR_BACK(path)))
641 alstr_append_char(&path, '\\');
642 alstr_append_cstr(&path, subdir);
643 #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
644 VECTOR_FOR_EACH(char, path, FIX_SLASH);
645 #undef FIX_SLASH
647 DirectorySearch(alstr_get_cstr(path), ext, &results);
651 alstr_reset(&path);
654 ATOMIC_STORE_SEQ(&search_lock, 0);
656 return results;
660 struct FileMapping MapFileToMem(const char *fname)
662 struct FileMapping ret = { NULL, NULL, NULL, 0 };
663 MEMORY_BASIC_INFORMATION meminfo;
664 HANDLE file, fmap;
665 WCHAR *wname;
666 void *ptr;
668 wname = FromUTF8(fname);
670 file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
671 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
672 if(file == INVALID_HANDLE_VALUE)
674 ERR("Failed to open %s: %lu\n", fname, GetLastError());
675 free(wname);
676 return ret;
678 free(wname);
679 wname = NULL;
681 fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
682 if(!fmap)
684 ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
685 CloseHandle(file);
686 return ret;
689 ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
690 if(!ptr)
692 ERR("Failed to map %s: %lu\n", fname, GetLastError());
693 CloseHandle(fmap);
694 CloseHandle(file);
695 return ret;
698 if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
700 ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
701 UnmapViewOfFile(ptr);
702 CloseHandle(fmap);
703 CloseHandle(file);
704 return ret;
707 ret.file = file;
708 ret.fmap = fmap;
709 ret.ptr = ptr;
710 ret.len = meminfo.RegionSize;
711 return ret;
714 void UnmapFileMem(const struct FileMapping *mapping)
716 UnmapViewOfFile(mapping->ptr);
717 CloseHandle(mapping->fmap);
718 CloseHandle(mapping->file);
721 #else
723 al_string GetProcPath(void)
725 al_string ret = AL_STRING_INIT_STATIC();
726 char *pathname, *sep;
727 size_t pathlen;
729 #ifdef __FreeBSD__
730 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
731 mib[3] = getpid();
732 if (sysctl(mib, 4, NULL, &pathlen, NULL, 0) == -1) {
733 WARN("Failed to sysctl kern.proc.pathname.%d: %s\n", mib[3], strerror(errno));
734 return ret;
737 pathname = malloc(pathlen + 1);
738 sysctl(mib, 4, (void*)pathname, &pathlen, NULL, 0);
739 pathname[pathlen] = 0;
740 #else
741 const char *fname;
742 ssize_t len;
744 pathlen = 256;
745 pathname = malloc(pathlen);
747 fname = "/proc/self/exe";
748 len = readlink(fname, pathname, pathlen);
749 if(len == -1 && errno == ENOENT)
751 fname = "/proc/self/file";
752 len = readlink(fname, pathname, pathlen);
755 while(len > 0 && (size_t)len == pathlen)
757 free(pathname);
758 pathlen <<= 1;
759 pathname = malloc(pathlen);
760 len = readlink(fname, pathname, pathlen);
762 if(len <= 0)
764 free(pathname);
765 WARN("Failed to readlink %s: %s\n", fname, strerror(errno));
766 return ret;
769 pathname[len] = 0;
770 #endif
772 sep = strrchr(pathname, '/');
773 if(sep)
774 alstr_copy_range(&ret, pathname, sep);
775 else
776 alstr_copy_cstr(&ret, pathname);
777 free(pathname);
779 TRACE("Got: %s\n", alstr_get_cstr(ret));
780 return ret;
784 #ifdef HAVE_DLFCN_H
786 void *LoadLib(const char *name)
788 const char *err;
789 void *handle;
791 dlerror();
792 handle = dlopen(name, RTLD_NOW);
793 if((err=dlerror()) != NULL)
794 handle = NULL;
795 return handle;
797 void CloseLib(void *handle)
798 { dlclose(handle); }
799 void *GetSymbol(void *handle, const char *name)
801 const char *err;
802 void *sym;
804 dlerror();
805 sym = dlsym(handle, name);
806 if((err=dlerror()) != NULL)
808 WARN("Failed to load %s: %s\n", name, err);
809 sym = NULL;
811 return sym;
814 #endif /* HAVE_DLFCN_H */
816 void al_print(const char *type, const char *func, const char *fmt, ...)
818 va_list ap;
820 va_start(ap, fmt);
821 fprintf(LogFile, "AL lib: %s %s: ", type, func);
822 vfprintf(LogFile, fmt, ap);
823 va_end(ap);
825 fflush(LogFile);
829 static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
831 size_t extlen = strlen(ext);
832 DIR *dir;
834 TRACE("Searching %s for *%s\n", path, ext);
835 dir = opendir(path);
836 if(dir != NULL)
838 size_t base = VECTOR_SIZE(*results);
839 struct dirent *dirent;
840 while((dirent=readdir(dir)) != NULL)
842 al_string str;
843 size_t len;
844 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
845 continue;
847 len = strlen(dirent->d_name);
848 if(!(len > extlen))
849 continue;
850 if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
851 continue;
853 AL_STRING_INIT(str);
854 alstr_copy_cstr(&str, path);
855 if(VECTOR_BACK(str) != '/')
856 alstr_append_char(&str, '/');
857 alstr_append_cstr(&str, dirent->d_name);
858 TRACE("Got result %s\n", alstr_get_cstr(str));
859 VECTOR_PUSH_BACK(*results, str);
861 closedir(dir);
863 if(VECTOR_SIZE(*results) > base)
864 qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
865 sizeof(VECTOR_FRONT(*results)), StringSortCompare);
869 vector_al_string SearchDataFiles(const char *ext, const char *subdir)
871 static RefCount search_lock;
872 vector_al_string results = VECTOR_INIT_STATIC();
874 while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
875 althrd_yield();
877 if(subdir[0] == '/')
878 DirectorySearch(subdir, ext, &results);
879 else
881 al_string path = AL_STRING_INIT_STATIC();
882 const char *str, *next;
883 char cwdbuf[PATH_MAX];
885 /* Search the app-local directory. */
886 if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
887 DirectorySearch(str, ext, &results);
888 else if(getcwd(cwdbuf, sizeof(cwdbuf)))
889 DirectorySearch(cwdbuf, ext, &results);
890 else
891 DirectorySearch(".", ext, &results);
893 // Search local data dir
894 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
896 alstr_copy_cstr(&path, str);
897 if(VECTOR_BACK(path) != '/')
898 alstr_append_char(&path, '/');
899 alstr_append_cstr(&path, subdir);
900 DirectorySearch(alstr_get_cstr(path), ext, &results);
902 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
904 alstr_copy_cstr(&path, str);
905 if(VECTOR_BACK(path) == '/')
907 VECTOR_POP_BACK(path);
908 *VECTOR_END(path) = 0;
910 alstr_append_cstr(&path, "/.local/share/");
911 alstr_append_cstr(&path, subdir);
912 DirectorySearch(alstr_get_cstr(path), ext, &results);
915 // Search global data dirs
916 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
917 str = "/usr/local/share/:/usr/share/";
919 next = str;
920 while((str=next) != NULL && str[0] != '\0')
922 next = strchr(str, ':');
923 if(!next)
924 alstr_copy_cstr(&path, str);
925 else
927 alstr_copy_range(&path, str, next);
928 ++next;
930 if(!alstr_empty(path))
932 if(VECTOR_BACK(path) != '/')
933 alstr_append_char(&path, '/');
934 alstr_append_cstr(&path, subdir);
936 DirectorySearch(alstr_get_cstr(path), ext, &results);
940 alstr_reset(&path);
943 ATOMIC_STORE_SEQ(&search_lock, 0);
945 return results;
949 struct FileMapping MapFileToMem(const char *fname)
951 struct FileMapping ret = { -1, NULL, 0 };
952 struct stat sbuf;
953 void *ptr;
954 int fd;
956 fd = open(fname, O_RDONLY, 0);
957 if(fd == -1)
959 ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
960 return ret;
962 if(fstat(fd, &sbuf) == -1)
964 ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
965 close(fd);
966 return ret;
969 ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
970 if(ptr == MAP_FAILED)
972 ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
973 close(fd);
974 return ret;
977 ret.fd = fd;
978 ret.ptr = ptr;
979 ret.len = sbuf.st_size;
980 return ret;
983 void UnmapFileMem(const struct FileMapping *mapping)
985 munmap(mapping->ptr, mapping->len);
986 close(mapping->fd);
989 #endif
992 void SetRTPriority(void)
994 ALboolean failed = AL_FALSE;
996 #ifdef _WIN32
997 if(RTPrioLevel > 0)
998 failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
999 #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
1000 if(RTPrioLevel > 0)
1002 struct sched_param param;
1003 /* Use the minimum real-time priority possible for now (on Linux this
1004 * should be 1 for SCHED_RR) */
1005 param.sched_priority = sched_get_priority_min(SCHED_RR);
1006 failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
1008 #else
1009 /* Real-time priority not available */
1010 failed = (RTPrioLevel>0);
1011 #endif
1012 if(failed)
1013 ERR("Failed to set priority level for thread\n");
1017 extern inline void alstr_reset(al_string *str);
1018 extern inline size_t alstr_length(const_al_string str);
1019 extern inline ALboolean alstr_empty(const_al_string str);
1020 extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
1022 void alstr_clear(al_string *str)
1024 if(!alstr_empty(*str))
1026 /* Reserve one more character than the total size of the string. This
1027 * is to ensure we have space to add a null terminator in the string
1028 * data so it can be used as a C-style string.
1030 VECTOR_RESIZE(*str, 0, 1);
1031 VECTOR_ELEM(*str, 0) = 0;
1035 static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
1036 const al_string_char_type *str2, size_t str2len)
1038 size_t complen = (str1len < str2len) ? str1len : str2len;
1039 int ret = memcmp(str1, str2, complen);
1040 if(ret == 0)
1042 if(str1len > str2len) return 1;
1043 if(str1len < str2len) return -1;
1045 return ret;
1047 int alstr_cmp(const_al_string str1, const_al_string str2)
1049 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1050 &VECTOR_FRONT(str2), alstr_length(str2));
1052 int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
1054 return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
1055 str2, strlen(str2));
1058 void alstr_copy(al_string *str, const_al_string from)
1060 size_t len = alstr_length(from);
1061 size_t i;
1063 VECTOR_RESIZE(*str, len, len+1);
1064 for(i = 0;i < len;i++)
1065 VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
1066 VECTOR_ELEM(*str, i) = 0;
1069 void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
1071 size_t len = strlen(from);
1072 size_t i;
1074 VECTOR_RESIZE(*str, len, len+1);
1075 for(i = 0;i < len;i++)
1076 VECTOR_ELEM(*str, i) = from[i];
1077 VECTOR_ELEM(*str, i) = 0;
1080 void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1082 size_t len = to - from;
1083 size_t i;
1085 VECTOR_RESIZE(*str, len, len+1);
1086 for(i = 0;i < len;i++)
1087 VECTOR_ELEM(*str, i) = from[i];
1088 VECTOR_ELEM(*str, i) = 0;
1091 void alstr_append_char(al_string *str, const al_string_char_type c)
1093 size_t len = alstr_length(*str);
1094 VECTOR_RESIZE(*str, len, len+2);
1095 VECTOR_PUSH_BACK(*str, c);
1096 VECTOR_ELEM(*str, len+1) = 0;
1099 void alstr_append_cstr(al_string *str, const al_string_char_type *from)
1101 size_t len = strlen(from);
1102 if(len != 0)
1104 size_t base = alstr_length(*str);
1105 size_t i;
1107 VECTOR_RESIZE(*str, base+len, base+len+1);
1108 for(i = 0;i < len;i++)
1109 VECTOR_ELEM(*str, base+i) = from[i];
1110 VECTOR_ELEM(*str, base+i) = 0;
1114 void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
1116 size_t len = to - from;
1117 if(len != 0)
1119 size_t base = alstr_length(*str);
1120 size_t i;
1122 VECTOR_RESIZE(*str, base+len, base+len+1);
1123 for(i = 0;i < len;i++)
1124 VECTOR_ELEM(*str, base+i) = from[i];
1125 VECTOR_ELEM(*str, base+i) = 0;
1129 #ifdef _WIN32
1130 void alstr_copy_wcstr(al_string *str, const wchar_t *from)
1132 int len;
1133 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1135 VECTOR_RESIZE(*str, len-1, len);
1136 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
1137 VECTOR_ELEM(*str, len-1) = 0;
1141 void alstr_append_wcstr(al_string *str, const wchar_t *from)
1143 int len;
1144 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
1146 size_t base = alstr_length(*str);
1147 VECTOR_RESIZE(*str, base+len-1, base+len);
1148 WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
1149 VECTOR_ELEM(*str, base+len-1) = 0;
1153 void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
1155 int len;
1156 if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
1158 size_t base = alstr_length(*str);
1159 VECTOR_RESIZE(*str, base+len, base+len+1);
1160 WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
1161 VECTOR_ELEM(*str, base+len) = 0;
1164 #endif