helpers.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. #include "config.h"
  2. #include "helpers.h"
  3. #if defined(_WIN32)
  4. #define WIN32_LEAN_AND_MEAN
  5. #include <windows.h>
  6. #endif
  7. #include <algorithm>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <filesystem>
  11. #include <limits>
  12. #include <mutex>
  13. #include <optional>
  14. #include <string>
  15. #include <system_error>
  16. #include "almalloc.h"
  17. #include "alnumeric.h"
  18. #include "alspan.h"
  19. #include "alstring.h"
  20. #include "logging.h"
  21. #include "strutils.h"
  22. namespace {
  23. using namespace std::string_view_literals;
  24. std::mutex gSearchLock;
  25. void DirectorySearch(const std::filesystem::path &path, const std::string_view ext,
  26. std::vector<std::string> *const results)
  27. {
  28. namespace fs = std::filesystem;
  29. const auto base = static_cast<std::make_signed_t<size_t>>(results->size());
  30. try {
  31. auto fpath = path.lexically_normal();
  32. if(!fs::exists(fpath))
  33. return;
  34. TRACE("Searching %s for *%.*s\n", fpath.u8string().c_str(), al::sizei(ext), ext.data());
  35. for(auto&& dirent : fs::directory_iterator{fpath})
  36. {
  37. auto&& entrypath = dirent.path();
  38. if(!entrypath.has_extension())
  39. continue;
  40. if(fs::status(entrypath).type() == fs::file_type::regular
  41. && al::case_compare(entrypath.extension().u8string(), ext) == 0)
  42. results->emplace_back(entrypath.u8string());
  43. }
  44. }
  45. catch(std::exception& e) {
  46. ERR("Exception enumerating files: %s\n", e.what());
  47. }
  48. /* HACK: Without the size check this trips up range-checked iterators, as
  49. * al::span uses al::to_address to get the first iterator's data pointer,
  50. * which relies on operator->(), which can assert on end iterators. The
  51. * check shouldn't be needed with C++20's std::span.
  52. */
  53. if(static_cast<size_t>(base) < results->size())
  54. {
  55. const al::span newlist{results->begin()+base, results->end()};
  56. std::sort(newlist.begin(), newlist.end());
  57. for(const auto &name : newlist)
  58. TRACE(" got %s\n", name.c_str());
  59. }
  60. }
  61. } // namespace
  62. #ifdef _WIN32
  63. #include <cctype>
  64. #include <shlobj.h>
  65. const PathNamePair &GetProcBinary()
  66. {
  67. auto get_procbin = []
  68. {
  69. #if !defined(ALSOFT_UWP)
  70. DWORD pathlen{256};
  71. auto fullpath = std::wstring(pathlen, L'\0');
  72. DWORD len{GetModuleFileNameW(nullptr, fullpath.data(), pathlen)};
  73. while(len == fullpath.size())
  74. {
  75. pathlen <<= 1;
  76. if(pathlen == 0)
  77. {
  78. /* pathlen overflow (more than 4 billion characters??) */
  79. len = 0;
  80. break;
  81. }
  82. fullpath.resize(pathlen);
  83. len = GetModuleFileNameW(nullptr, fullpath.data(), pathlen);
  84. }
  85. if(len == 0)
  86. {
  87. ERR("Failed to get process name: error %lu\n", GetLastError());
  88. return PathNamePair{};
  89. }
  90. fullpath.resize(len);
  91. #else
  92. const WCHAR *exePath{__wargv[0]};
  93. if(!exePath)
  94. {
  95. ERR("Failed to get process name: __wargv[0] == nullptr\n");
  96. return PathNamePair{};
  97. }
  98. std::wstring fullpath{exePath};
  99. #endif
  100. std::replace(fullpath.begin(), fullpath.end(), L'/', L'\\');
  101. PathNamePair res{};
  102. if(auto seppos = fullpath.rfind(L'\\'); seppos < fullpath.size())
  103. {
  104. res.path = wstr_to_utf8(std::wstring_view{fullpath}.substr(0, seppos));
  105. res.fname = wstr_to_utf8(std::wstring_view{fullpath}.substr(seppos+1));
  106. }
  107. else
  108. res.fname = wstr_to_utf8(fullpath);
  109. TRACE("Got binary: %s, %s\n", res.path.c_str(), res.fname.c_str());
  110. return res;
  111. };
  112. static const PathNamePair procbin{get_procbin()};
  113. return procbin;
  114. }
  115. namespace {
  116. #if !defined(ALSOFT_UWP) && !defined(_GAMING_XBOX)
  117. struct CoTaskMemDeleter {
  118. void operator()(void *mem) const { CoTaskMemFree(mem); }
  119. };
  120. #endif
  121. } // namespace
  122. std::vector<std::string> SearchDataFiles(const std::string_view ext, const std::string_view subdir)
  123. {
  124. std::lock_guard<std::mutex> srchlock{gSearchLock};
  125. /* If the path is absolute, use it directly. */
  126. std::vector<std::string> results;
  127. auto path = std::filesystem::u8path(subdir);
  128. if(path.is_absolute())
  129. {
  130. DirectorySearch(path, ext, &results);
  131. return results;
  132. }
  133. /* Search the app-local directory. */
  134. if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH"))
  135. DirectorySearch(*localpath, ext, &results);
  136. else if(auto curpath = std::filesystem::current_path(); !curpath.empty())
  137. DirectorySearch(curpath, ext, &results);
  138. #if !defined(ALSOFT_UWP) && !defined(_GAMING_XBOX)
  139. /* Search the local and global data dirs. */
  140. for(const auto &folderid : std::array{FOLDERID_RoamingAppData, FOLDERID_ProgramData})
  141. {
  142. std::unique_ptr<WCHAR,CoTaskMemDeleter> buffer;
  143. const HRESULT hr{SHGetKnownFolderPath(folderid, KF_FLAG_DONT_UNEXPAND, nullptr,
  144. al::out_ptr(buffer))};
  145. if(FAILED(hr) || !buffer || !*buffer)
  146. continue;
  147. DirectorySearch(std::filesystem::path{buffer.get()}/path, ext, &results);
  148. }
  149. #endif
  150. return results;
  151. }
  152. void SetRTPriority()
  153. {
  154. #if !defined(ALSOFT_UWP)
  155. if(RTPrioLevel > 0)
  156. {
  157. if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
  158. ERR("Failed to set priority level for thread\n");
  159. }
  160. #endif
  161. }
  162. #else
  163. #include <cerrno>
  164. #include <dirent.h>
  165. #include <unistd.h>
  166. #ifdef __FreeBSD__
  167. #include <sys/sysctl.h>
  168. #endif
  169. #ifdef __HAIKU__
  170. #include <FindDirectory.h>
  171. #endif
  172. #ifdef HAVE_PROC_PIDPATH
  173. #include <libproc.h>
  174. #endif
  175. #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  176. #include <pthread.h>
  177. #include <sched.h>
  178. #endif
  179. #ifdef HAVE_RTKIT
  180. #include <sys/resource.h>
  181. #include "dbus_wrap.h"
  182. #include "rtkit.h"
  183. #ifndef RLIMIT_RTTIME
  184. #define RLIMIT_RTTIME 15
  185. #endif
  186. #endif
  187. const PathNamePair &GetProcBinary()
  188. {
  189. auto get_procbin = []
  190. {
  191. std::string pathname;
  192. #ifdef __FreeBSD__
  193. size_t pathlen{};
  194. std::array<int,4> mib{{CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}};
  195. if(sysctl(mib.data(), mib.size(), nullptr, &pathlen, nullptr, 0) == -1)
  196. WARN("Failed to sysctl kern.proc.pathname: %s\n",
  197. std::generic_category().message(errno).c_str());
  198. else
  199. {
  200. auto procpath = std::vector<char>(pathlen+1, '\0');
  201. sysctl(mib.data(), mib.size(), procpath.data(), &pathlen, nullptr, 0);
  202. pathname = procpath.data();
  203. }
  204. #endif
  205. #ifdef HAVE_PROC_PIDPATH
  206. if(pathname.empty())
  207. {
  208. std::array<char,PROC_PIDPATHINFO_MAXSIZE> procpath{};
  209. const pid_t pid{getpid()};
  210. if(proc_pidpath(pid, procpath.data(), procpath.size()) < 1)
  211. ERR("proc_pidpath(%d, ...) failed: %s\n", pid,
  212. std::generic_category().message(errno).c_str());
  213. else
  214. pathname = procpath.data();
  215. }
  216. #endif
  217. #ifdef __HAIKU__
  218. if(pathname.empty())
  219. {
  220. std::array<char,PATH_MAX> procpath{};
  221. if(find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, procpath.data(), procpath.size()) == B_OK)
  222. pathname = procpath.data();
  223. }
  224. #endif
  225. #ifndef __SWITCH__
  226. if(pathname.empty())
  227. {
  228. const std::array SelfLinkNames{
  229. "/proc/self/exe"sv,
  230. "/proc/self/file"sv,
  231. "/proc/curproc/exe"sv,
  232. "/proc/curproc/file"sv,
  233. };
  234. for(const std::string_view name : SelfLinkNames)
  235. {
  236. try {
  237. if(!std::filesystem::exists(name))
  238. continue;
  239. if(auto path = std::filesystem::read_symlink(name); !path.empty())
  240. {
  241. pathname = path.u8string();
  242. break;
  243. }
  244. }
  245. catch(std::exception& e) {
  246. WARN("Exception getting symlink %.*s: %s\n", al::sizei(name), name.data(),
  247. e.what());
  248. }
  249. }
  250. }
  251. #endif
  252. PathNamePair res{};
  253. if(auto seppos = pathname.rfind('/'); seppos < pathname.size())
  254. {
  255. res.path = std::string_view{pathname}.substr(0, seppos);
  256. res.fname = std::string_view{pathname}.substr(seppos+1);
  257. }
  258. else
  259. res.fname = pathname;
  260. TRACE("Got binary: \"%s\", \"%s\"\n", res.path.c_str(), res.fname.c_str());
  261. return res;
  262. };
  263. static const PathNamePair procbin{get_procbin()};
  264. return procbin;
  265. }
  266. std::vector<std::string> SearchDataFiles(const std::string_view ext, const std::string_view subdir)
  267. {
  268. std::lock_guard<std::mutex> srchlock{gSearchLock};
  269. std::vector<std::string> results;
  270. auto path = std::filesystem::u8path(subdir);
  271. if(path.is_absolute())
  272. {
  273. DirectorySearch(path, ext, &results);
  274. return results;
  275. }
  276. /* Search the app-local directory. */
  277. if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH"))
  278. DirectorySearch(*localpath, ext, &results);
  279. else if(auto curpath = std::filesystem::current_path(); !curpath.empty())
  280. DirectorySearch(curpath, ext, &results);
  281. /* Search local data dir */
  282. if(auto datapath = al::getenv("XDG_DATA_HOME"))
  283. DirectorySearch(std::filesystem::path{*datapath}/path, ext, &results);
  284. else if(auto homepath = al::getenv("HOME"))
  285. DirectorySearch(std::filesystem::path{*homepath}/".local/share"/path, ext, &results);
  286. /* Search global data dirs */
  287. std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
  288. size_t curpos{0u};
  289. while(curpos < datadirs.size())
  290. {
  291. size_t nextpos{datadirs.find(':', curpos)};
  292. std::string_view pathname{(nextpos != std::string::npos)
  293. ? std::string_view{datadirs}.substr(curpos, nextpos++ - curpos)
  294. : std::string_view{datadirs}.substr(curpos)};
  295. curpos = nextpos;
  296. if(!pathname.empty())
  297. DirectorySearch(std::filesystem::path{pathname}/path, ext, &results);
  298. }
  299. #ifdef ALSOFT_INSTALL_DATADIR
  300. /* Search the installation data directory */
  301. if(auto instpath = std::filesystem::path{ALSOFT_INSTALL_DATADIR}; !instpath.empty())
  302. DirectorySearch(instpath/path, ext, &results);
  303. #endif
  304. return results;
  305. }
  306. namespace {
  307. bool SetRTPriorityPthread(int prio [[maybe_unused]])
  308. {
  309. int err{ENOTSUP};
  310. #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  311. /* Get the min and max priority for SCHED_RR. Limit the max priority to
  312. * half, for now, to ensure the thread can't take the highest priority and
  313. * go rogue.
  314. */
  315. int rtmin{sched_get_priority_min(SCHED_RR)};
  316. int rtmax{sched_get_priority_max(SCHED_RR)};
  317. rtmax = (rtmax-rtmin)/2 + rtmin;
  318. struct sched_param param{};
  319. param.sched_priority = std::clamp(prio, rtmin, rtmax);
  320. #ifdef SCHED_RESET_ON_FORK
  321. err = pthread_setschedparam(pthread_self(), SCHED_RR|SCHED_RESET_ON_FORK, &param);
  322. if(err == EINVAL)
  323. #endif
  324. err = pthread_setschedparam(pthread_self(), SCHED_RR, &param);
  325. if(err == 0) return true;
  326. #endif
  327. WARN("pthread_setschedparam failed: %s (%d)\n", std::generic_category().message(err).c_str(),
  328. err);
  329. return false;
  330. }
  331. bool SetRTPriorityRTKit(int prio [[maybe_unused]])
  332. {
  333. #ifdef HAVE_RTKIT
  334. if(!HasDBus())
  335. {
  336. WARN("D-Bus not available\n");
  337. return false;
  338. }
  339. dbus::Error error;
  340. dbus::ConnectionPtr conn{dbus_bus_get(DBUS_BUS_SYSTEM, &error.get())};
  341. if(!conn)
  342. {
  343. WARN("D-Bus connection failed with %s: %s\n", error->name, error->message);
  344. return false;
  345. }
  346. /* Don't stupidly exit if the connection dies while doing this. */
  347. dbus_connection_set_exit_on_disconnect(conn.get(), false);
  348. int nicemin{};
  349. int err{rtkit_get_min_nice_level(conn.get(), &nicemin)};
  350. if(err == -ENOENT)
  351. {
  352. err = std::abs(err);
  353. ERR("Could not query RTKit: %s (%d)\n", std::generic_category().message(err).c_str(), err);
  354. return false;
  355. }
  356. int rtmax{rtkit_get_max_realtime_priority(conn.get())};
  357. TRACE("Maximum real-time priority: %d, minimum niceness: %d\n", rtmax, nicemin);
  358. auto limit_rttime = [](DBusConnection *c) -> int
  359. {
  360. using ulonglong = unsigned long long;
  361. long long maxrttime{rtkit_get_rttime_usec_max(c)};
  362. if(maxrttime <= 0) return static_cast<int>(std::abs(maxrttime));
  363. const ulonglong umaxtime{static_cast<ulonglong>(maxrttime)};
  364. struct rlimit rlim{};
  365. if(getrlimit(RLIMIT_RTTIME, &rlim) != 0)
  366. return errno;
  367. TRACE("RTTime max: %llu (hard: %llu, soft: %llu)\n", umaxtime,
  368. static_cast<ulonglong>(rlim.rlim_max), static_cast<ulonglong>(rlim.rlim_cur));
  369. if(rlim.rlim_max > umaxtime)
  370. {
  371. rlim.rlim_max = static_cast<rlim_t>(std::min<ulonglong>(umaxtime,
  372. std::numeric_limits<rlim_t>::max()));
  373. rlim.rlim_cur = std::min(rlim.rlim_cur, rlim.rlim_max);
  374. if(setrlimit(RLIMIT_RTTIME, &rlim) != 0)
  375. return errno;
  376. }
  377. return 0;
  378. };
  379. if(rtmax > 0)
  380. {
  381. if(AllowRTTimeLimit)
  382. {
  383. err = limit_rttime(conn.get());
  384. if(err != 0)
  385. WARN("Failed to set RLIMIT_RTTIME for RTKit: %s (%d)\n",
  386. std::generic_category().message(err).c_str(), err);
  387. }
  388. /* Limit the maximum real-time priority to half. */
  389. rtmax = (rtmax+1)/2;
  390. prio = std::clamp(prio, 1, rtmax);
  391. TRACE("Making real-time with priority %d (max: %d)\n", prio, rtmax);
  392. err = rtkit_make_realtime(conn.get(), 0, prio);
  393. if(err == 0) return true;
  394. err = std::abs(err);
  395. WARN("Failed to set real-time priority: %s (%d)\n",
  396. std::generic_category().message(err).c_str(), err);
  397. }
  398. /* Don't try to set the niceness for non-Linux systems. Standard POSIX has
  399. * niceness as a per-process attribute, while the intent here is for the
  400. * audio processing thread only to get a priority boost. Currently only
  401. * Linux is known to have per-thread niceness.
  402. */
  403. #ifdef __linux__
  404. if(nicemin < 0)
  405. {
  406. TRACE("Making high priority with niceness %d\n", nicemin);
  407. err = rtkit_make_high_priority(conn.get(), 0, nicemin);
  408. if(err == 0) return true;
  409. err = std::abs(err);
  410. WARN("Failed to set high priority: %s (%d)\n",
  411. std::generic_category().message(err).c_str(), err);
  412. }
  413. #endif /* __linux__ */
  414. #else
  415. WARN("D-Bus not supported\n");
  416. #endif
  417. return false;
  418. }
  419. } // namespace
  420. void SetRTPriority()
  421. {
  422. if(RTPrioLevel <= 0)
  423. return;
  424. if(SetRTPriorityPthread(RTPrioLevel))
  425. return;
  426. if(SetRTPriorityRTKit(RTPrioLevel))
  427. return;
  428. }
  429. #endif