helpers.cpp 15 KB

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