helpers.cpp 14 KB

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