🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

557 lines
15 KiB

  1. #include "config.h"
  2. #include "helpers.h"
  3. #include <algorithm>
  4. #include <cerrno>
  5. #include <cstdarg>
  6. #include <cstdlib>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <mutex>
  10. #include <limits>
  11. #include <string>
  12. #include <tuple>
  13. #include "almalloc.h"
  14. #include "alfstream.h"
  15. #include "alnumeric.h"
  16. #include "aloptional.h"
  17. #include "alspan.h"
  18. #include "alstring.h"
  19. #include "logging.h"
  20. #include "strutils.h"
  21. #include "vector.h"
  22. /* Mixing thread piority level */
  23. int RTPrioLevel{1};
  24. /* Allow reducing the process's RTTime limit for RTKit. */
  25. bool AllowRTTimeLimit{true};
  26. #ifdef _WIN32
  27. #include <shlobj.h>
  28. const PathNamePair &GetProcBinary()
  29. {
  30. static al::optional<PathNamePair> procbin;
  31. if(procbin) return *procbin;
  32. auto fullpath = al::vector<WCHAR>(256);
  33. DWORD len{GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()))};
  34. while(len == fullpath.size())
  35. {
  36. fullpath.resize(fullpath.size() << 1);
  37. len = GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()));
  38. }
  39. if(len == 0)
  40. {
  41. ERR("Failed to get process name: error %lu\n", GetLastError());
  42. procbin = al::make_optional<PathNamePair>();
  43. return *procbin;
  44. }
  45. fullpath.resize(len);
  46. if(fullpath.back() != 0)
  47. fullpath.push_back(0);
  48. auto sep = std::find(fullpath.rbegin()+1, fullpath.rend(), '\\');
  49. sep = std::find(fullpath.rbegin()+1, sep, '/');
  50. if(sep != fullpath.rend())
  51. {
  52. *sep = 0;
  53. procbin = al::make_optional<PathNamePair>(wstr_to_utf8(fullpath.data()),
  54. wstr_to_utf8(&*sep + 1));
  55. }
  56. else
  57. procbin = al::make_optional<PathNamePair>(std::string{}, wstr_to_utf8(fullpath.data()));
  58. TRACE("Got binary: %s, %s\n", procbin->path.c_str(), procbin->fname.c_str());
  59. return *procbin;
  60. }
  61. namespace {
  62. void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
  63. {
  64. std::string pathstr{path};
  65. pathstr += "\\*";
  66. pathstr += ext;
  67. TRACE("Searching %s\n", pathstr.c_str());
  68. std::wstring wpath{utf8_to_wstr(pathstr.c_str())};
  69. WIN32_FIND_DATAW fdata;
  70. HANDLE hdl{FindFirstFileW(wpath.c_str(), &fdata)};
  71. if(hdl == INVALID_HANDLE_VALUE) return;
  72. const auto base = results->size();
  73. do {
  74. results->emplace_back();
  75. std::string &str = results->back();
  76. str = path;
  77. str += '\\';
  78. str += wstr_to_utf8(fdata.cFileName);
  79. } while(FindNextFileW(hdl, &fdata));
  80. FindClose(hdl);
  81. const al::span<std::string> newlist{results->data()+base, results->size()-base};
  82. std::sort(newlist.begin(), newlist.end());
  83. for(const auto &name : newlist)
  84. TRACE(" got %s\n", name.c_str());
  85. }
  86. } // namespace
  87. al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
  88. {
  89. auto is_slash = [](int c) noexcept -> int { return (c == '\\' || c == '/'); };
  90. static std::mutex search_lock;
  91. std::lock_guard<std::mutex> _{search_lock};
  92. /* If the path is absolute, use it directly. */
  93. al::vector<std::string> results;
  94. if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
  95. {
  96. std::string path{subdir};
  97. std::replace(path.begin(), path.end(), '/', '\\');
  98. DirectorySearch(path.c_str(), ext, &results);
  99. return results;
  100. }
  101. if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
  102. {
  103. DirectorySearch(subdir, ext, &results);
  104. return results;
  105. }
  106. std::string path;
  107. /* Search the app-local directory. */
  108. if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH"))
  109. {
  110. path = wstr_to_utf8(localpath->c_str());
  111. if(is_slash(path.back()))
  112. path.pop_back();
  113. }
  114. else if(WCHAR *cwdbuf{_wgetcwd(nullptr, 0)})
  115. {
  116. path = wstr_to_utf8(cwdbuf);
  117. if(is_slash(path.back()))
  118. path.pop_back();
  119. free(cwdbuf);
  120. }
  121. else
  122. path = ".";
  123. std::replace(path.begin(), path.end(), '/', '\\');
  124. DirectorySearch(path.c_str(), ext, &results);
  125. /* Search the local and global data dirs. */
  126. static const int ids[2]{ CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
  127. for(int id : ids)
  128. {
  129. WCHAR buffer[MAX_PATH];
  130. if(SHGetSpecialFolderPathW(nullptr, buffer, id, FALSE) == FALSE)
  131. continue;
  132. path = wstr_to_utf8(buffer);
  133. if(!is_slash(path.back()))
  134. path += '\\';
  135. path += subdir;
  136. std::replace(path.begin(), path.end(), '/', '\\');
  137. DirectorySearch(path.c_str(), ext, &results);
  138. }
  139. return results;
  140. }
  141. void SetRTPriority(void)
  142. {
  143. if(RTPrioLevel > 0)
  144. {
  145. if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
  146. ERR("Failed to set priority level for thread\n");
  147. }
  148. }
  149. #else
  150. #include <sys/types.h>
  151. #include <unistd.h>
  152. #include <dirent.h>
  153. #ifdef __FreeBSD__
  154. #include <sys/sysctl.h>
  155. #endif
  156. #ifdef __HAIKU__
  157. #include <FindDirectory.h>
  158. #endif
  159. #ifdef HAVE_PROC_PIDPATH
  160. #include <libproc.h>
  161. #endif
  162. #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  163. #include <pthread.h>
  164. #include <sched.h>
  165. #endif
  166. #ifdef HAVE_RTKIT
  167. #include <sys/time.h>
  168. #include <sys/resource.h>
  169. #include "dbus_wrap.h"
  170. #include "rtkit.h"
  171. #ifndef RLIMIT_RTTIME
  172. #define RLIMIT_RTTIME 15
  173. #endif
  174. #endif
  175. const PathNamePair &GetProcBinary()
  176. {
  177. static al::optional<PathNamePair> procbin;
  178. if(procbin) return *procbin;
  179. al::vector<char> pathname;
  180. #ifdef __FreeBSD__
  181. size_t pathlen;
  182. int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
  183. if(sysctl(mib, 4, nullptr, &pathlen, nullptr, 0) == -1)
  184. WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno));
  185. else
  186. {
  187. pathname.resize(pathlen + 1);
  188. sysctl(mib, 4, pathname.data(), &pathlen, nullptr, 0);
  189. pathname.resize(pathlen);
  190. }
  191. #endif
  192. #ifdef HAVE_PROC_PIDPATH
  193. if(pathname.empty())
  194. {
  195. char procpath[PROC_PIDPATHINFO_MAXSIZE]{};
  196. const pid_t pid{getpid()};
  197. if(proc_pidpath(pid, procpath, sizeof(procpath)) < 1)
  198. ERR("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
  199. else
  200. pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
  201. }
  202. #endif
  203. #ifdef __HAIKU__
  204. if(pathname.empty())
  205. {
  206. char procpath[PATH_MAX];
  207. if(find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, procpath, sizeof(procpath)) == B_OK)
  208. pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
  209. }
  210. #endif
  211. #ifndef __SWITCH__
  212. if(pathname.empty())
  213. {
  214. static const char SelfLinkNames[][32]{
  215. "/proc/self/exe",
  216. "/proc/self/file",
  217. "/proc/curproc/exe",
  218. "/proc/curproc/file"
  219. };
  220. pathname.resize(256);
  221. const char *selfname{};
  222. ssize_t len{};
  223. for(const char *name : SelfLinkNames)
  224. {
  225. selfname = name;
  226. len = readlink(selfname, pathname.data(), pathname.size());
  227. if(len >= 0 || errno != ENOENT) break;
  228. }
  229. while(len > 0 && static_cast<size_t>(len) == pathname.size())
  230. {
  231. pathname.resize(pathname.size() << 1);
  232. len = readlink(selfname, pathname.data(), pathname.size());
  233. }
  234. if(len <= 0)
  235. {
  236. WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
  237. len = 0;
  238. }
  239. pathname.resize(static_cast<size_t>(len));
  240. }
  241. #endif
  242. while(!pathname.empty() && pathname.back() == 0)
  243. pathname.pop_back();
  244. auto sep = std::find(pathname.crbegin(), pathname.crend(), '/');
  245. if(sep != pathname.crend())
  246. procbin = al::make_optional<PathNamePair>(std::string(pathname.cbegin(), sep.base()-1),
  247. std::string(sep.base(), pathname.cend()));
  248. else
  249. procbin = al::make_optional<PathNamePair>(std::string{},
  250. std::string(pathname.cbegin(), pathname.cend()));
  251. TRACE("Got binary: \"%s\", \"%s\"\n", procbin->path.c_str(), procbin->fname.c_str());
  252. return *procbin;
  253. }
  254. namespace {
  255. void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
  256. {
  257. TRACE("Searching %s for *%s\n", path, ext);
  258. DIR *dir{opendir(path)};
  259. if(!dir) return;
  260. const auto base = results->size();
  261. const size_t extlen{strlen(ext)};
  262. while(struct dirent *dirent{readdir(dir)})
  263. {
  264. if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
  265. continue;
  266. const size_t len{strlen(dirent->d_name)};
  267. if(len <= extlen) continue;
  268. if(al::strcasecmp(dirent->d_name+len-extlen, ext) != 0)
  269. continue;
  270. results->emplace_back();
  271. std::string &str = results->back();
  272. str = path;
  273. if(str.back() != '/')
  274. str.push_back('/');
  275. str += dirent->d_name;
  276. }
  277. closedir(dir);
  278. const al::span<std::string> newlist{results->data()+base, results->size()-base};
  279. std::sort(newlist.begin(), newlist.end());
  280. for(const auto &name : newlist)
  281. TRACE(" got %s\n", name.c_str());
  282. }
  283. } // namespace
  284. al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
  285. {
  286. static std::mutex search_lock;
  287. std::lock_guard<std::mutex> _{search_lock};
  288. al::vector<std::string> results;
  289. if(subdir[0] == '/')
  290. {
  291. DirectorySearch(subdir, ext, &results);
  292. return results;
  293. }
  294. /* Search the app-local directory. */
  295. if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH"))
  296. DirectorySearch(localpath->c_str(), ext, &results);
  297. else
  298. {
  299. al::vector<char> cwdbuf(256);
  300. while(!getcwd(cwdbuf.data(), cwdbuf.size()))
  301. {
  302. if(errno != ERANGE)
  303. {
  304. cwdbuf.clear();
  305. break;
  306. }
  307. cwdbuf.resize(cwdbuf.size() << 1);
  308. }
  309. if(cwdbuf.empty())
  310. DirectorySearch(".", ext, &results);
  311. else
  312. {
  313. DirectorySearch(cwdbuf.data(), ext, &results);
  314. cwdbuf.clear();
  315. }
  316. }
  317. // Search local data dir
  318. if(auto datapath = al::getenv("XDG_DATA_HOME"))
  319. {
  320. std::string &path = *datapath;
  321. if(path.back() != '/')
  322. path += '/';
  323. path += subdir;
  324. DirectorySearch(path.c_str(), ext, &results);
  325. }
  326. else if(auto homepath = al::getenv("HOME"))
  327. {
  328. std::string &path = *homepath;
  329. if(path.back() == '/')
  330. path.pop_back();
  331. path += "/.local/share/";
  332. path += subdir;
  333. DirectorySearch(path.c_str(), ext, &results);
  334. }
  335. // Search global data dirs
  336. std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
  337. size_t curpos{0u};
  338. while(curpos < datadirs.size())
  339. {
  340. size_t nextpos{datadirs.find(':', curpos)};
  341. std::string path{(nextpos != std::string::npos) ?
  342. datadirs.substr(curpos, nextpos++ - curpos) : datadirs.substr(curpos)};
  343. curpos = nextpos;
  344. if(path.empty()) continue;
  345. if(path.back() != '/')
  346. path += '/';
  347. path += subdir;
  348. DirectorySearch(path.c_str(), ext, &results);
  349. }
  350. return results;
  351. }
  352. namespace {
  353. bool SetRTPriorityPthread(int prio)
  354. {
  355. int err{ENOTSUP};
  356. #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  357. /* Get the min and max priority for SCHED_RR. Limit the max priority to
  358. * half, for now, to ensure the thread can't take the highest priority and
  359. * go rogue.
  360. */
  361. int rtmin{sched_get_priority_min(SCHED_RR)};
  362. int rtmax{sched_get_priority_max(SCHED_RR)};
  363. rtmax = (rtmax-rtmin)/2 + rtmin;
  364. struct sched_param param{};
  365. param.sched_priority = clampi(prio, rtmin, rtmax);
  366. #ifdef SCHED_RESET_ON_FORK
  367. err = pthread_setschedparam(pthread_self(), SCHED_RR|SCHED_RESET_ON_FORK, &param);
  368. if(err == EINVAL)
  369. #endif
  370. err = pthread_setschedparam(pthread_self(), SCHED_RR, &param);
  371. if(err == 0) return true;
  372. #else
  373. std::ignore = prio;
  374. #endif
  375. WARN("pthread_setschedparam failed: %s (%d)\n", std::strerror(err), err);
  376. return false;
  377. }
  378. bool SetRTPriorityRTKit(int prio)
  379. {
  380. #ifdef HAVE_RTKIT
  381. if(!HasDBus())
  382. {
  383. WARN("D-Bus not available\n");
  384. return false;
  385. }
  386. dbus::Error error;
  387. dbus::ConnectionPtr conn{dbus_bus_get(DBUS_BUS_SYSTEM, &error.get())};
  388. if(!conn)
  389. {
  390. WARN("D-Bus connection failed with %s: %s\n", error->name, error->message);
  391. return false;
  392. }
  393. /* Don't stupidly exit if the connection dies while doing this. */
  394. dbus_connection_set_exit_on_disconnect(conn.get(), false);
  395. auto limit_rttime = [](DBusConnection *c) -> int
  396. {
  397. using ulonglong = unsigned long long;
  398. long long maxrttime{rtkit_get_rttime_usec_max(c)};
  399. if(maxrttime <= 0) return static_cast<int>(std::abs(maxrttime));
  400. const ulonglong umaxtime{static_cast<ulonglong>(maxrttime)};
  401. struct rlimit rlim{};
  402. if(getrlimit(RLIMIT_RTTIME, &rlim) != 0)
  403. return errno;
  404. TRACE("RTTime max: %llu (hard: %llu, soft: %llu)\n", umaxtime, ulonglong{rlim.rlim_max},
  405. ulonglong{rlim.rlim_cur});
  406. if(rlim.rlim_max > umaxtime)
  407. {
  408. rlim.rlim_max = static_cast<rlim_t>(umaxtime);
  409. rlim.rlim_cur = std::min(rlim.rlim_cur, rlim.rlim_max);
  410. if(setrlimit(RLIMIT_RTTIME, &rlim) != 0)
  411. return errno;
  412. }
  413. return 0;
  414. };
  415. int nicemin{};
  416. int err{rtkit_get_min_nice_level(conn.get(), &nicemin)};
  417. if(err == -ENOENT)
  418. {
  419. err = std::abs(err);
  420. ERR("Could not query RTKit: %s (%d)\n", std::strerror(err), err);
  421. return false;
  422. }
  423. int rtmax{rtkit_get_max_realtime_priority(conn.get())};
  424. TRACE("Maximum real-time priority: %d, minimum niceness: %d\n", rtmax, nicemin);
  425. if(rtmax > 0)
  426. {
  427. if(AllowRTTimeLimit)
  428. {
  429. err = limit_rttime(conn.get());
  430. if(err != 0)
  431. WARN("Failed to set RLIMIT_RTTIME for RTKit: %s (%d)\n",
  432. std::strerror(err), err);
  433. }
  434. /* Limit the maximum real-time priority to half. */
  435. rtmax = (rtmax+1)/2;
  436. prio = clampi(prio, 1, rtmax);
  437. TRACE("Making real-time with priority %d (max: %d)\n", prio, rtmax);
  438. err = rtkit_make_realtime(conn.get(), 0, prio);
  439. if(err == 0) return true;
  440. err = std::abs(err);
  441. WARN("Failed to set real-time priority: %s (%d)\n", std::strerror(err), err);
  442. }
  443. /* Don't try to set the niceness for non-Linux systems. Standard POSIX has
  444. * niceness as a per-process attribute, while the intent here is for the
  445. * audio processing thread only to get a priority boost. Currently only
  446. * Linux is known to have per-thread niceness.
  447. */
  448. #ifdef __linux__
  449. if(nicemin < 0)
  450. {
  451. TRACE("Making high priority with niceness %d\n", nicemin);
  452. err = rtkit_make_high_priority(conn.get(), 0, nicemin);
  453. if(err == 0) return true;
  454. err = std::abs(err);
  455. WARN("Failed to set high priority: %s (%d)\n", std::strerror(err), err);
  456. }
  457. #endif /* __linux__ */
  458. #else
  459. std::ignore = prio;
  460. WARN("D-Bus not supported\n");
  461. #endif
  462. return false;
  463. }
  464. } // namespace
  465. void SetRTPriority()
  466. {
  467. if(RTPrioLevel <= 0)
  468. return;
  469. if(SetRTPriorityPthread(RTPrioLevel))
  470. return;
  471. if(SetRTPriorityRTKit(RTPrioLevel))
  472. return;
  473. }
  474. #endif