helpers.c 32 KB

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