helpers.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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.
  8. *
  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.
  13. *
  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
  19. */
  20. #ifdef _WIN32
  21. #ifdef __MINGW32__
  22. #define _WIN32_IE 0x501
  23. #else
  24. #define _WIN32_IE 0x400
  25. #endif
  26. #endif
  27. #include "config.h"
  28. #include <stdlib.h>
  29. #include <time.h>
  30. #include <errno.h>
  31. #include <stdarg.h>
  32. #include <ctype.h>
  33. #ifdef HAVE_MALLOC_H
  34. #include <malloc.h>
  35. #endif
  36. #ifdef HAVE_DIRENT_H
  37. #include <dirent.h>
  38. #endif
  39. #ifdef HAVE_PROC_PIDPATH
  40. #include <libproc.h>
  41. #endif
  42. #ifdef __FreeBSD__
  43. #include <sys/types.h>
  44. #include <sys/sysctl.h>
  45. #endif
  46. #ifndef AL_NO_UID_DEFS
  47. #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
  48. #define INITGUID
  49. #include <windows.h>
  50. #ifdef HAVE_GUIDDEF_H
  51. #include <guiddef.h>
  52. #else
  53. #include <initguid.h>
  54. #endif
  55. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
  56. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
  57. DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
  58. DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
  59. DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
  60. DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
  61. DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
  62. DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
  63. #ifdef HAVE_WASAPI
  64. #include <wtypes.h>
  65. #include <devpropdef.h>
  66. #include <propkeydef.h>
  67. DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
  68. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
  69. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
  70. #endif
  71. #endif
  72. #endif /* AL_NO_UID_DEFS */
  73. #ifdef HAVE_DLFCN_H
  74. #include <dlfcn.h>
  75. #endif
  76. #ifdef HAVE_INTRIN_H
  77. #include <intrin.h>
  78. #endif
  79. #ifdef HAVE_CPUID_H
  80. #include <cpuid.h>
  81. #endif
  82. #ifdef HAVE_SYS_SYSCONF_H
  83. #include <sys/sysconf.h>
  84. #endif
  85. #ifdef HAVE_FLOAT_H
  86. #include <float.h>
  87. #endif
  88. #ifdef HAVE_IEEEFP_H
  89. #include <ieeefp.h>
  90. #endif
  91. #ifndef _WIN32
  92. #include <sys/types.h>
  93. #include <sys/stat.h>
  94. #include <sys/mman.h>
  95. #include <fcntl.h>
  96. #include <unistd.h>
  97. #elif defined(_WIN32_IE)
  98. #include <shlobj.h>
  99. #endif
  100. #include "alMain.h"
  101. #include "alu.h"
  102. #include "cpu_caps.h"
  103. #include "fpu_modes.h"
  104. #include "atomic.h"
  105. #include "uintmap.h"
  106. #include "vector.h"
  107. #include "alstring.h"
  108. #include "compat.h"
  109. #include "threads.h"
  110. extern inline ALuint NextPowerOf2(ALuint value);
  111. extern inline size_t RoundUp(size_t value, size_t r);
  112. extern inline ALint fastf2i(ALfloat f);
  113. extern inline int float2int(float f);
  114. #ifndef __GNUC__
  115. #if defined(HAVE_BITSCANFORWARD64_INTRINSIC)
  116. extern inline int msvc64_ctz64(ALuint64 v);
  117. #elif defined(HAVE_BITSCANFORWARD_INTRINSIC)
  118. extern inline int msvc_ctz64(ALuint64 v);
  119. #else
  120. extern inline int fallback_popcnt64(ALuint64 v);
  121. extern inline int fallback_ctz64(ALuint64 value);
  122. #endif
  123. #endif
  124. #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
  125. defined(_M_IX86) || defined(_M_X64))
  126. typedef unsigned int reg_type;
  127. static inline void get_cpuid(int f, reg_type *regs)
  128. { __get_cpuid(f, &regs[0], &regs[1], &regs[2], &regs[3]); }
  129. #define CAN_GET_CPUID
  130. #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
  131. defined(_M_IX86) || defined(_M_X64))
  132. typedef int reg_type;
  133. static inline void get_cpuid(int f, reg_type *regs)
  134. { (__cpuid)(regs, f); }
  135. #define CAN_GET_CPUID
  136. #endif
  137. int CPUCapFlags = 0;
  138. void FillCPUCaps(int capfilter)
  139. {
  140. int caps = 0;
  141. /* FIXME: We really should get this for all available CPUs in case different
  142. * CPUs have different caps (is that possible on one machine?). */
  143. #ifdef CAN_GET_CPUID
  144. union {
  145. reg_type regs[4];
  146. char str[sizeof(reg_type[4])];
  147. } cpuinf[3] = {{ { 0, 0, 0, 0 } }};
  148. get_cpuid(0, cpuinf[0].regs);
  149. if(cpuinf[0].regs[0] == 0)
  150. ERR("Failed to get CPUID\n");
  151. else
  152. {
  153. unsigned int maxfunc = cpuinf[0].regs[0];
  154. unsigned int maxextfunc;
  155. get_cpuid(0x80000000, cpuinf[0].regs);
  156. maxextfunc = cpuinf[0].regs[0];
  157. TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
  158. TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
  159. if(maxextfunc >= 0x80000004)
  160. {
  161. get_cpuid(0x80000002, cpuinf[0].regs);
  162. get_cpuid(0x80000003, cpuinf[1].regs);
  163. get_cpuid(0x80000004, cpuinf[2].regs);
  164. TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
  165. }
  166. if(maxfunc >= 1)
  167. {
  168. get_cpuid(1, cpuinf[0].regs);
  169. if((cpuinf[0].regs[3]&(1<<25)))
  170. caps |= CPU_CAP_SSE;
  171. if((caps&CPU_CAP_SSE) && (cpuinf[0].regs[3]&(1<<26)))
  172. caps |= CPU_CAP_SSE2;
  173. if((caps&CPU_CAP_SSE2) && (cpuinf[0].regs[2]&(1<<0)))
  174. caps |= CPU_CAP_SSE3;
  175. if((caps&CPU_CAP_SSE3) && (cpuinf[0].regs[2]&(1<<19)))
  176. caps |= CPU_CAP_SSE4_1;
  177. }
  178. }
  179. #else
  180. /* Assume support for whatever's supported if we can't check for it */
  181. #if defined(HAVE_SSE4_1)
  182. #warning "Assuming SSE 4.1 run-time support!"
  183. caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
  184. #elif defined(HAVE_SSE3)
  185. #warning "Assuming SSE 3 run-time support!"
  186. caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
  187. #elif defined(HAVE_SSE2)
  188. #warning "Assuming SSE 2 run-time support!"
  189. caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
  190. #elif defined(HAVE_SSE)
  191. #warning "Assuming SSE run-time support!"
  192. caps |= CPU_CAP_SSE;
  193. #endif
  194. #endif
  195. #ifdef HAVE_NEON
  196. FILE *file = fopen("/proc/cpuinfo", "rt");
  197. if(!file)
  198. ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
  199. else
  200. {
  201. char buf[256];
  202. while(fgets(buf, sizeof(buf), file) != NULL)
  203. {
  204. size_t len;
  205. char *str;
  206. if(strncmp(buf, "Features\t:", 10) != 0)
  207. continue;
  208. len = strlen(buf);
  209. while(len > 0 && isspace(buf[len-1]))
  210. buf[--len] = 0;
  211. TRACE("Got features string:%s\n", buf+10);
  212. str = buf;
  213. while((str=strstr(str, "neon")) != NULL)
  214. {
  215. if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
  216. {
  217. caps |= CPU_CAP_NEON;
  218. break;
  219. }
  220. str++;
  221. }
  222. break;
  223. }
  224. fclose(file);
  225. file = NULL;
  226. }
  227. #endif
  228. TRACE("Extensions:%s%s%s%s%s%s\n",
  229. ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
  230. ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
  231. ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
  232. ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
  233. ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
  234. ((!capfilter) ? " -none-" : "")
  235. );
  236. CPUCapFlags = caps & capfilter;
  237. }
  238. void SetMixerFPUMode(FPUCtl *ctl)
  239. {
  240. #if defined(__GNUC__) && defined(HAVE_SSE)
  241. if((CPUCapFlags&CPU_CAP_SSE))
  242. {
  243. __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
  244. unsigned int sseState = ctl->sse_state;
  245. sseState |= 0x8000; /* set flush-to-zero */
  246. if((CPUCapFlags&CPU_CAP_SSE2))
  247. sseState |= 0x0040; /* set denormals-are-zero */
  248. __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
  249. }
  250. #elif defined(HAVE___CONTROL87_2)
  251. __control87_2(0, 0, &ctl->state, &ctl->sse_state);
  252. _control87(_DN_FLUSH, _MCW_DN);
  253. #elif defined(HAVE__CONTROLFP)
  254. ctl->state = _controlfp(0, 0);
  255. _controlfp(_DN_FLUSH, _MCW_DN);
  256. #endif
  257. }
  258. void RestoreFPUMode(const FPUCtl *ctl)
  259. {
  260. #if defined(__GNUC__) && defined(HAVE_SSE)
  261. if((CPUCapFlags&CPU_CAP_SSE))
  262. __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
  263. #elif defined(HAVE___CONTROL87_2)
  264. int mode;
  265. __control87_2(ctl->state, _MCW_DN, &mode, NULL);
  266. __control87_2(ctl->sse_state, _MCW_DN, NULL, &mode);
  267. #elif defined(HAVE__CONTROLFP)
  268. _controlfp(ctl->state, _MCW_DN);
  269. #endif
  270. }
  271. static int StringSortCompare(const void *str1, const void *str2)
  272. {
  273. return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
  274. }
  275. #ifdef _WIN32
  276. static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
  277. {
  278. WCHAR *ret = NULL;
  279. while(*str)
  280. {
  281. if(*str == ch)
  282. ret = str;
  283. ++str;
  284. }
  285. return ret;
  286. }
  287. void GetProcBinary(al_string *path, al_string *fname)
  288. {
  289. WCHAR *pathname, *sep;
  290. DWORD pathlen;
  291. DWORD len;
  292. pathlen = 256;
  293. pathname = malloc(pathlen * sizeof(pathname[0]));
  294. while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
  295. {
  296. free(pathname);
  297. pathlen <<= 1;
  298. pathname = malloc(pathlen * sizeof(pathname[0]));
  299. }
  300. if(len == 0)
  301. {
  302. free(pathname);
  303. ERR("Failed to get process name: error %lu\n", GetLastError());
  304. return;
  305. }
  306. pathname[len] = 0;
  307. if((sep=strrchrW(pathname, '\\')) != NULL)
  308. {
  309. WCHAR *sep2 = strrchrW(sep+1, '/');
  310. if(sep2) sep = sep2;
  311. }
  312. else
  313. sep = strrchrW(pathname, '/');
  314. if(sep)
  315. {
  316. if(path) alstr_copy_wrange(path, pathname, sep);
  317. if(fname) alstr_copy_wcstr(fname, sep+1);
  318. }
  319. else
  320. {
  321. if(path) alstr_clear(path);
  322. if(fname) alstr_copy_wcstr(fname, pathname);
  323. }
  324. free(pathname);
  325. if(path && fname)
  326. TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
  327. else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
  328. else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
  329. }
  330. static WCHAR *FromUTF8(const char *str)
  331. {
  332. WCHAR *out = NULL;
  333. int len;
  334. if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
  335. {
  336. out = calloc(sizeof(WCHAR), len);
  337. MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
  338. }
  339. return out;
  340. }
  341. void *LoadLib(const char *name)
  342. {
  343. HANDLE hdl = NULL;
  344. WCHAR *wname;
  345. wname = FromUTF8(name);
  346. if(!wname)
  347. ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
  348. else
  349. {
  350. hdl = LoadLibraryW(wname);
  351. free(wname);
  352. }
  353. return hdl;
  354. }
  355. void CloseLib(void *handle)
  356. { FreeLibrary((HANDLE)handle); }
  357. void *GetSymbol(void *handle, const char *name)
  358. {
  359. void *ret;
  360. ret = (void*)GetProcAddress((HANDLE)handle, name);
  361. if(ret == NULL)
  362. ERR("Failed to load %s\n", name);
  363. return ret;
  364. }
  365. WCHAR *strdupW(const WCHAR *str)
  366. {
  367. const WCHAR *n;
  368. WCHAR *ret;
  369. size_t len;
  370. n = str;
  371. while(*n) n++;
  372. len = n - str;
  373. ret = calloc(sizeof(WCHAR), len+1);
  374. if(ret != NULL)
  375. memcpy(ret, str, sizeof(WCHAR)*len);
  376. return ret;
  377. }
  378. FILE *al_fopen(const char *fname, const char *mode)
  379. {
  380. WCHAR *wname=NULL, *wmode=NULL;
  381. FILE *file = NULL;
  382. wname = FromUTF8(fname);
  383. wmode = FromUTF8(mode);
  384. if(!wname)
  385. ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
  386. else if(!wmode)
  387. ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
  388. else
  389. file = _wfopen(wname, wmode);
  390. free(wname);
  391. free(wmode);
  392. return file;
  393. }
  394. void al_print(const char *type, const char *func, const char *fmt, ...)
  395. {
  396. char str[1024];
  397. WCHAR *wstr;
  398. va_list ap;
  399. va_start(ap, fmt);
  400. vsnprintf(str, sizeof(str), fmt, ap);
  401. va_end(ap);
  402. str[sizeof(str)-1] = 0;
  403. wstr = FromUTF8(str);
  404. if(!wstr)
  405. fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
  406. else
  407. {
  408. fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
  409. free(wstr);
  410. wstr = NULL;
  411. }
  412. fflush(LogFile);
  413. }
  414. static inline int is_slash(int c)
  415. { return (c == '\\' || c == '/'); }
  416. static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
  417. {
  418. al_string pathstr = AL_STRING_INIT_STATIC();
  419. WIN32_FIND_DATAW fdata;
  420. WCHAR *wpath;
  421. HANDLE hdl;
  422. alstr_copy_cstr(&pathstr, path);
  423. alstr_append_cstr(&pathstr, "\\*");
  424. alstr_append_cstr(&pathstr, ext);
  425. TRACE("Searching %s\n", alstr_get_cstr(pathstr));
  426. wpath = FromUTF8(alstr_get_cstr(pathstr));
  427. hdl = FindFirstFileW(wpath, &fdata);
  428. if(hdl != INVALID_HANDLE_VALUE)
  429. {
  430. size_t base = VECTOR_SIZE(*results);
  431. do {
  432. al_string str = AL_STRING_INIT_STATIC();
  433. alstr_copy_cstr(&str, path);
  434. alstr_append_char(&str, '\\');
  435. alstr_append_wcstr(&str, fdata.cFileName);
  436. TRACE("Got result %s\n", alstr_get_cstr(str));
  437. VECTOR_PUSH_BACK(*results, str);
  438. } while(FindNextFileW(hdl, &fdata));
  439. FindClose(hdl);
  440. if(VECTOR_SIZE(*results) > base)
  441. qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
  442. sizeof(VECTOR_FRONT(*results)), StringSortCompare);
  443. }
  444. free(wpath);
  445. alstr_reset(&pathstr);
  446. }
  447. vector_al_string SearchDataFiles(const char *ext, const char *subdir)
  448. {
  449. static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
  450. static RefCount search_lock;
  451. vector_al_string results = VECTOR_INIT_STATIC();
  452. size_t i;
  453. while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
  454. althrd_yield();
  455. /* If the path is absolute, use it directly. */
  456. if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
  457. {
  458. al_string path = AL_STRING_INIT_STATIC();
  459. alstr_copy_cstr(&path, subdir);
  460. #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
  461. VECTOR_FOR_EACH(char, path, FIX_SLASH);
  462. #undef FIX_SLASH
  463. DirectorySearch(alstr_get_cstr(path), ext, &results);
  464. alstr_reset(&path);
  465. }
  466. else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
  467. DirectorySearch(subdir, ext, &results);
  468. else
  469. {
  470. al_string path = AL_STRING_INIT_STATIC();
  471. WCHAR *cwdbuf;
  472. /* Search the app-local directory. */
  473. if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
  474. {
  475. alstr_copy_wcstr(&path, cwdbuf);
  476. if(is_slash(VECTOR_BACK(path)))
  477. {
  478. VECTOR_POP_BACK(path);
  479. *VECTOR_END(path) = 0;
  480. }
  481. }
  482. else if(!(cwdbuf=_wgetcwd(NULL, 0)))
  483. alstr_copy_cstr(&path, ".");
  484. else
  485. {
  486. alstr_copy_wcstr(&path, cwdbuf);
  487. if(is_slash(VECTOR_BACK(path)))
  488. {
  489. VECTOR_POP_BACK(path);
  490. *VECTOR_END(path) = 0;
  491. }
  492. free(cwdbuf);
  493. }
  494. #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
  495. VECTOR_FOR_EACH(char, path, FIX_SLASH);
  496. #undef FIX_SLASH
  497. DirectorySearch(alstr_get_cstr(path), ext, &results);
  498. /* Search the local and global data dirs. */
  499. for(i = 0;i < COUNTOF(ids);i++)
  500. {
  501. WCHAR buffer[MAX_PATH];
  502. if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
  503. {
  504. alstr_copy_wcstr(&path, buffer);
  505. if(!is_slash(VECTOR_BACK(path)))
  506. alstr_append_char(&path, '\\');
  507. alstr_append_cstr(&path, subdir);
  508. #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
  509. VECTOR_FOR_EACH(char, path, FIX_SLASH);
  510. #undef FIX_SLASH
  511. DirectorySearch(alstr_get_cstr(path), ext, &results);
  512. }
  513. }
  514. alstr_reset(&path);
  515. }
  516. ATOMIC_STORE_SEQ(&search_lock, 0);
  517. return results;
  518. }
  519. struct FileMapping MapFileToMem(const char *fname)
  520. {
  521. struct FileMapping ret = { NULL, NULL, NULL, 0 };
  522. MEMORY_BASIC_INFORMATION meminfo;
  523. HANDLE file, fmap;
  524. WCHAR *wname;
  525. void *ptr;
  526. wname = FromUTF8(fname);
  527. file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
  528. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  529. if(file == INVALID_HANDLE_VALUE)
  530. {
  531. ERR("Failed to open %s: %lu\n", fname, GetLastError());
  532. free(wname);
  533. return ret;
  534. }
  535. free(wname);
  536. wname = NULL;
  537. fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
  538. if(!fmap)
  539. {
  540. ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
  541. CloseHandle(file);
  542. return ret;
  543. }
  544. ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
  545. if(!ptr)
  546. {
  547. ERR("Failed to map %s: %lu\n", fname, GetLastError());
  548. CloseHandle(fmap);
  549. CloseHandle(file);
  550. return ret;
  551. }
  552. if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
  553. {
  554. ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
  555. UnmapViewOfFile(ptr);
  556. CloseHandle(fmap);
  557. CloseHandle(file);
  558. return ret;
  559. }
  560. ret.file = file;
  561. ret.fmap = fmap;
  562. ret.ptr = ptr;
  563. ret.len = meminfo.RegionSize;
  564. return ret;
  565. }
  566. void UnmapFileMem(const struct FileMapping *mapping)
  567. {
  568. UnmapViewOfFile(mapping->ptr);
  569. CloseHandle(mapping->fmap);
  570. CloseHandle(mapping->file);
  571. }
  572. #else
  573. void GetProcBinary(al_string *path, al_string *fname)
  574. {
  575. char *pathname = NULL;
  576. size_t pathlen;
  577. #ifdef __FreeBSD__
  578. int mib[4] = { CTL_KERN, KERN_PROC_ARGS, getpid() };
  579. if(sysctl(mib, 3, NULL, &pathlen, NULL, 0) == -1)
  580. WARN("Failed to sysctl kern.procargs.%d: %s\n", mib[2], strerror(errno));
  581. else
  582. {
  583. pathname = malloc(pathlen + 1);
  584. sysctl(mib, 3, (void*)pathname, &pathlen, NULL, 0);
  585. pathname[pathlen] = 0;
  586. }
  587. #endif
  588. #ifdef HAVE_PROC_PIDPATH
  589. if(!pathname)
  590. {
  591. const pid_t pid = getpid();
  592. char procpath[PROC_PIDPATHINFO_MAXSIZE];
  593. int ret;
  594. ret = proc_pidpath(pid, procpath, sizeof(procpath));
  595. if(ret < 1)
  596. {
  597. WARN("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
  598. free(pathname);
  599. pathname = NULL;
  600. }
  601. else
  602. {
  603. pathlen = strlen(procpath);
  604. pathname = strdup(procpath);
  605. }
  606. }
  607. #endif
  608. if(!pathname)
  609. {
  610. const char *selfname;
  611. ssize_t len;
  612. pathlen = 256;
  613. pathname = malloc(pathlen);
  614. selfname = "/proc/self/exe";
  615. len = readlink(selfname, pathname, pathlen);
  616. if(len == -1 && errno == ENOENT)
  617. {
  618. selfname = "/proc/self/file";
  619. len = readlink(selfname, pathname, pathlen);
  620. }
  621. if(len == -1 && errno == ENOENT)
  622. {
  623. selfname = "/proc/curproc/exe";
  624. len = readlink(selfname, pathname, pathlen);
  625. }
  626. if(len == -1 && errno == ENOENT)
  627. {
  628. selfname = "/proc/curproc/file";
  629. len = readlink(selfname, pathname, pathlen);
  630. }
  631. while(len > 0 && (size_t)len == pathlen)
  632. {
  633. free(pathname);
  634. pathlen <<= 1;
  635. pathname = malloc(pathlen);
  636. len = readlink(selfname, pathname, pathlen);
  637. }
  638. if(len <= 0)
  639. {
  640. free(pathname);
  641. WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
  642. return;
  643. }
  644. pathname[len] = 0;
  645. }
  646. char *sep = strrchr(pathname, '/');
  647. if(sep)
  648. {
  649. if(path) alstr_copy_range(path, pathname, sep);
  650. if(fname) alstr_copy_cstr(fname, sep+1);
  651. }
  652. else
  653. {
  654. if(path) alstr_clear(path);
  655. if(fname) alstr_copy_cstr(fname, pathname);
  656. }
  657. free(pathname);
  658. if(path && fname)
  659. TRACE("Got: %s, %s\n", alstr_get_cstr(*path), alstr_get_cstr(*fname));
  660. else if(path) TRACE("Got path: %s\n", alstr_get_cstr(*path));
  661. else if(fname) TRACE("Got filename: %s\n", alstr_get_cstr(*fname));
  662. }
  663. #ifdef HAVE_DLFCN_H
  664. void *LoadLib(const char *name)
  665. {
  666. const char *err;
  667. void *handle;
  668. dlerror();
  669. handle = dlopen(name, RTLD_NOW);
  670. if((err=dlerror()) != NULL)
  671. handle = NULL;
  672. return handle;
  673. }
  674. void CloseLib(void *handle)
  675. { dlclose(handle); }
  676. void *GetSymbol(void *handle, const char *name)
  677. {
  678. const char *err;
  679. void *sym;
  680. dlerror();
  681. sym = dlsym(handle, name);
  682. if((err=dlerror()) != NULL)
  683. {
  684. WARN("Failed to load %s: %s\n", name, err);
  685. sym = NULL;
  686. }
  687. return sym;
  688. }
  689. #endif /* HAVE_DLFCN_H */
  690. void al_print(const char *type, const char *func, const char *fmt, ...)
  691. {
  692. va_list ap;
  693. va_start(ap, fmt);
  694. fprintf(LogFile, "AL lib: %s %s: ", type, func);
  695. vfprintf(LogFile, fmt, ap);
  696. va_end(ap);
  697. fflush(LogFile);
  698. }
  699. static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
  700. {
  701. size_t extlen = strlen(ext);
  702. DIR *dir;
  703. TRACE("Searching %s for *%s\n", path, ext);
  704. dir = opendir(path);
  705. if(dir != NULL)
  706. {
  707. size_t base = VECTOR_SIZE(*results);
  708. struct dirent *dirent;
  709. while((dirent=readdir(dir)) != NULL)
  710. {
  711. al_string str;
  712. size_t len;
  713. if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
  714. continue;
  715. len = strlen(dirent->d_name);
  716. if(!(len > extlen))
  717. continue;
  718. if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
  719. continue;
  720. AL_STRING_INIT(str);
  721. alstr_copy_cstr(&str, path);
  722. if(VECTOR_BACK(str) != '/')
  723. alstr_append_char(&str, '/');
  724. alstr_append_cstr(&str, dirent->d_name);
  725. TRACE("Got result %s\n", alstr_get_cstr(str));
  726. VECTOR_PUSH_BACK(*results, str);
  727. }
  728. closedir(dir);
  729. if(VECTOR_SIZE(*results) > base)
  730. qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
  731. sizeof(VECTOR_FRONT(*results)), StringSortCompare);
  732. }
  733. }
  734. vector_al_string SearchDataFiles(const char *ext, const char *subdir)
  735. {
  736. static RefCount search_lock;
  737. vector_al_string results = VECTOR_INIT_STATIC();
  738. while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
  739. althrd_yield();
  740. if(subdir[0] == '/')
  741. DirectorySearch(subdir, ext, &results);
  742. else
  743. {
  744. al_string path = AL_STRING_INIT_STATIC();
  745. const char *str, *next;
  746. /* Search the app-local directory. */
  747. if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
  748. DirectorySearch(str, ext, &results);
  749. else
  750. {
  751. size_t cwdlen = 256;
  752. char *cwdbuf = malloc(cwdlen);
  753. while(!getcwd(cwdbuf, cwdlen))
  754. {
  755. free(cwdbuf);
  756. cwdbuf = NULL;
  757. if(errno != ERANGE)
  758. break;
  759. cwdlen <<= 1;
  760. cwdbuf = malloc(cwdlen);
  761. }
  762. if(!cwdbuf)
  763. DirectorySearch(".", ext, &results);
  764. else
  765. {
  766. DirectorySearch(cwdbuf, ext, &results);
  767. free(cwdbuf);
  768. cwdbuf = NULL;
  769. }
  770. }
  771. // Search local data dir
  772. if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
  773. {
  774. alstr_copy_cstr(&path, str);
  775. if(VECTOR_BACK(path) != '/')
  776. alstr_append_char(&path, '/');
  777. alstr_append_cstr(&path, subdir);
  778. DirectorySearch(alstr_get_cstr(path), ext, &results);
  779. }
  780. else if((str=getenv("HOME")) != NULL && str[0] != '\0')
  781. {
  782. alstr_copy_cstr(&path, str);
  783. if(VECTOR_BACK(path) == '/')
  784. {
  785. VECTOR_POP_BACK(path);
  786. *VECTOR_END(path) = 0;
  787. }
  788. alstr_append_cstr(&path, "/.local/share/");
  789. alstr_append_cstr(&path, subdir);
  790. DirectorySearch(alstr_get_cstr(path), ext, &results);
  791. }
  792. // Search global data dirs
  793. if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
  794. str = "/usr/local/share/:/usr/share/";
  795. next = str;
  796. while((str=next) != NULL && str[0] != '\0')
  797. {
  798. next = strchr(str, ':');
  799. if(!next)
  800. alstr_copy_cstr(&path, str);
  801. else
  802. {
  803. alstr_copy_range(&path, str, next);
  804. ++next;
  805. }
  806. if(!alstr_empty(path))
  807. {
  808. if(VECTOR_BACK(path) != '/')
  809. alstr_append_char(&path, '/');
  810. alstr_append_cstr(&path, subdir);
  811. DirectorySearch(alstr_get_cstr(path), ext, &results);
  812. }
  813. }
  814. alstr_reset(&path);
  815. }
  816. ATOMIC_STORE_SEQ(&search_lock, 0);
  817. return results;
  818. }
  819. struct FileMapping MapFileToMem(const char *fname)
  820. {
  821. struct FileMapping ret = { -1, NULL, 0 };
  822. struct stat sbuf;
  823. void *ptr;
  824. int fd;
  825. fd = open(fname, O_RDONLY, 0);
  826. if(fd == -1)
  827. {
  828. ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
  829. return ret;
  830. }
  831. if(fstat(fd, &sbuf) == -1)
  832. {
  833. ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
  834. close(fd);
  835. return ret;
  836. }
  837. ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  838. if(ptr == MAP_FAILED)
  839. {
  840. ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
  841. close(fd);
  842. return ret;
  843. }
  844. ret.fd = fd;
  845. ret.ptr = ptr;
  846. ret.len = sbuf.st_size;
  847. return ret;
  848. }
  849. void UnmapFileMem(const struct FileMapping *mapping)
  850. {
  851. munmap(mapping->ptr, mapping->len);
  852. close(mapping->fd);
  853. }
  854. #endif
  855. void SetRTPriority(void)
  856. {
  857. ALboolean failed = AL_FALSE;
  858. #ifdef _WIN32
  859. if(RTPrioLevel > 0)
  860. failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  861. #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  862. if(RTPrioLevel > 0)
  863. {
  864. struct sched_param param;
  865. /* Use the minimum real-time priority possible for now (on Linux this
  866. * should be 1 for SCHED_RR) */
  867. param.sched_priority = sched_get_priority_min(SCHED_RR);
  868. failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
  869. }
  870. #else
  871. /* Real-time priority not available */
  872. failed = (RTPrioLevel>0);
  873. #endif
  874. if(failed)
  875. ERR("Failed to set priority level for thread\n");
  876. }
  877. extern inline void alstr_reset(al_string *str);
  878. extern inline size_t alstr_length(const_al_string str);
  879. extern inline ALboolean alstr_empty(const_al_string str);
  880. extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
  881. void alstr_clear(al_string *str)
  882. {
  883. if(!alstr_empty(*str))
  884. {
  885. /* Reserve one more character than the total size of the string. This
  886. * is to ensure we have space to add a null terminator in the string
  887. * data so it can be used as a C-style string.
  888. */
  889. VECTOR_RESIZE(*str, 0, 1);
  890. VECTOR_ELEM(*str, 0) = 0;
  891. }
  892. }
  893. static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
  894. const al_string_char_type *str2, size_t str2len)
  895. {
  896. size_t complen = (str1len < str2len) ? str1len : str2len;
  897. int ret = memcmp(str1, str2, complen);
  898. if(ret == 0)
  899. {
  900. if(str1len > str2len) return 1;
  901. if(str1len < str2len) return -1;
  902. }
  903. return ret;
  904. }
  905. int alstr_cmp(const_al_string str1, const_al_string str2)
  906. {
  907. return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
  908. &VECTOR_FRONT(str2), alstr_length(str2));
  909. }
  910. int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
  911. {
  912. return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
  913. str2, strlen(str2));
  914. }
  915. void alstr_copy(al_string *str, const_al_string from)
  916. {
  917. size_t len = alstr_length(from);
  918. size_t i;
  919. VECTOR_RESIZE(*str, len, len+1);
  920. for(i = 0;i < len;i++)
  921. VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
  922. VECTOR_ELEM(*str, i) = 0;
  923. }
  924. void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
  925. {
  926. size_t len = strlen(from);
  927. size_t i;
  928. VECTOR_RESIZE(*str, len, len+1);
  929. for(i = 0;i < len;i++)
  930. VECTOR_ELEM(*str, i) = from[i];
  931. VECTOR_ELEM(*str, i) = 0;
  932. }
  933. void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
  934. {
  935. size_t len = to - from;
  936. size_t i;
  937. VECTOR_RESIZE(*str, len, len+1);
  938. for(i = 0;i < len;i++)
  939. VECTOR_ELEM(*str, i) = from[i];
  940. VECTOR_ELEM(*str, i) = 0;
  941. }
  942. void alstr_append_char(al_string *str, const al_string_char_type c)
  943. {
  944. size_t len = alstr_length(*str);
  945. VECTOR_RESIZE(*str, len, len+2);
  946. VECTOR_PUSH_BACK(*str, c);
  947. VECTOR_ELEM(*str, len+1) = 0;
  948. }
  949. void alstr_append_cstr(al_string *str, const al_string_char_type *from)
  950. {
  951. size_t len = strlen(from);
  952. if(len != 0)
  953. {
  954. size_t base = alstr_length(*str);
  955. size_t i;
  956. VECTOR_RESIZE(*str, base+len, base+len+1);
  957. for(i = 0;i < len;i++)
  958. VECTOR_ELEM(*str, base+i) = from[i];
  959. VECTOR_ELEM(*str, base+i) = 0;
  960. }
  961. }
  962. void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
  963. {
  964. size_t len = to - from;
  965. if(len != 0)
  966. {
  967. size_t base = alstr_length(*str);
  968. size_t i;
  969. VECTOR_RESIZE(*str, base+len, base+len+1);
  970. for(i = 0;i < len;i++)
  971. VECTOR_ELEM(*str, base+i) = from[i];
  972. VECTOR_ELEM(*str, base+i) = 0;
  973. }
  974. }
  975. #ifdef _WIN32
  976. void alstr_copy_wcstr(al_string *str, const wchar_t *from)
  977. {
  978. int len;
  979. if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
  980. {
  981. VECTOR_RESIZE(*str, len-1, len);
  982. WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
  983. VECTOR_ELEM(*str, len-1) = 0;
  984. }
  985. }
  986. void alstr_append_wcstr(al_string *str, const wchar_t *from)
  987. {
  988. int len;
  989. if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
  990. {
  991. size_t base = alstr_length(*str);
  992. VECTOR_RESIZE(*str, base+len-1, base+len);
  993. WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
  994. VECTOR_ELEM(*str, base+len-1) = 0;
  995. }
  996. }
  997. void alstr_copy_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
  998. {
  999. int len;
  1000. if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
  1001. {
  1002. VECTOR_RESIZE(*str, len, len+1);
  1003. WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_FRONT(*str), len+1, NULL, NULL);
  1004. VECTOR_ELEM(*str, len) = 0;
  1005. }
  1006. }
  1007. void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
  1008. {
  1009. int len;
  1010. if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
  1011. {
  1012. size_t base = alstr_length(*str);
  1013. VECTOR_RESIZE(*str, base+len, base+len+1);
  1014. WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
  1015. VECTOR_ELEM(*str, base+len) = 0;
  1016. }
  1017. }
  1018. #endif