Make a couple more operator bools explicit
[openal-soft.git] / core / helpers.cpp
blob754e66c190651d6bf84549fdf4010d82201c6364
2 #include "config.h"
4 #include "helpers.h"
6 #include <algorithm>
7 #include <cerrno>
8 #include <cstdarg>
9 #include <cstdlib>
10 #include <cstdio>
11 #include <cstring>
12 #include <mutex>
13 #include <limits>
14 #include <string>
16 #include "almalloc.h"
17 #include "alfstream.h"
18 #include "alnumeric.h"
19 #include "aloptional.h"
20 #include "alspan.h"
21 #include "alstring.h"
22 #include "logging.h"
23 #include "strutils.h"
24 #include "vector.h"
27 /* Mixing thread piority level */
28 int RTPrioLevel{1};
30 /* Allow reducing the process's RTTime limit for RTKit. */
31 bool AllowRTTimeLimit{true};
34 #ifdef _WIN32
36 #include <shlobj.h>
38 const PathNamePair &GetProcBinary()
40 static al::optional<PathNamePair> procbin;
41 if(procbin) return *procbin;
43 auto fullpath = al::vector<WCHAR>(256);
44 DWORD len{GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()))};
45 while(len == fullpath.size())
47 fullpath.resize(fullpath.size() << 1);
48 len = GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()));
50 if(len == 0)
52 ERR("Failed to get process name: error %lu\n", GetLastError());
53 procbin = al::make_optional<PathNamePair>();
54 return *procbin;
57 fullpath.resize(len);
58 if(fullpath.back() != 0)
59 fullpath.push_back(0);
61 auto sep = std::find(fullpath.rbegin()+1, fullpath.rend(), '\\');
62 sep = std::find(fullpath.rbegin()+1, sep, '/');
63 if(sep != fullpath.rend())
65 *sep = 0;
66 procbin = al::make_optional<PathNamePair>(wstr_to_utf8(fullpath.data()),
67 wstr_to_utf8(&*sep + 1));
69 else
70 procbin = al::make_optional<PathNamePair>(std::string{}, wstr_to_utf8(fullpath.data()));
72 TRACE("Got binary: %s, %s\n", procbin->path.c_str(), procbin->fname.c_str());
73 return *procbin;
76 namespace {
78 void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
80 std::string pathstr{path};
81 pathstr += "\\*";
82 pathstr += ext;
83 TRACE("Searching %s\n", pathstr.c_str());
85 std::wstring wpath{utf8_to_wstr(pathstr.c_str())};
86 WIN32_FIND_DATAW fdata;
87 HANDLE hdl{FindFirstFileW(wpath.c_str(), &fdata)};
88 if(hdl == INVALID_HANDLE_VALUE) return;
90 const auto base = results->size();
92 do {
93 results->emplace_back();
94 std::string &str = results->back();
95 str = path;
96 str += '\\';
97 str += wstr_to_utf8(fdata.cFileName);
98 } while(FindNextFileW(hdl, &fdata));
99 FindClose(hdl);
101 const al::span<std::string> newlist{results->data()+base, results->size()-base};
102 std::sort(newlist.begin(), newlist.end());
103 for(const auto &name : newlist)
104 TRACE(" got %s\n", name.c_str());
107 } // namespace
109 al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
111 auto is_slash = [](int c) noexcept -> int { return (c == '\\' || c == '/'); };
113 static std::mutex search_lock;
114 std::lock_guard<std::mutex> _{search_lock};
116 /* If the path is absolute, use it directly. */
117 al::vector<std::string> results;
118 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
120 std::string path{subdir};
121 std::replace(path.begin(), path.end(), '/', '\\');
122 DirectorySearch(path.c_str(), ext, &results);
123 return results;
125 if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
127 DirectorySearch(subdir, ext, &results);
128 return results;
131 std::string path;
133 /* Search the app-local directory. */
134 if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH"))
136 path = wstr_to_utf8(localpath->c_str());
137 if(is_slash(path.back()))
138 path.pop_back();
140 else if(WCHAR *cwdbuf{_wgetcwd(nullptr, 0)})
142 path = wstr_to_utf8(cwdbuf);
143 if(is_slash(path.back()))
144 path.pop_back();
145 free(cwdbuf);
147 else
148 path = ".";
149 std::replace(path.begin(), path.end(), '/', '\\');
150 DirectorySearch(path.c_str(), ext, &results);
152 /* Search the local and global data dirs. */
153 static const int ids[2]{ CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
154 for(int id : ids)
156 WCHAR buffer[MAX_PATH];
157 if(SHGetSpecialFolderPathW(nullptr, buffer, id, FALSE) == FALSE)
158 continue;
160 path = wstr_to_utf8(buffer);
161 if(!is_slash(path.back()))
162 path += '\\';
163 path += subdir;
164 std::replace(path.begin(), path.end(), '/', '\\');
166 DirectorySearch(path.c_str(), ext, &results);
169 return results;
172 void SetRTPriority(void)
174 if(RTPrioLevel > 0)
176 if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
177 ERR("Failed to set priority level for thread\n");
181 #else
183 #include <sys/types.h>
184 #include <unistd.h>
185 #include <dirent.h>
186 #ifdef __FreeBSD__
187 #include <sys/sysctl.h>
188 #endif
189 #ifdef __HAIKU__
190 #include <FindDirectory.h>
191 #endif
192 #ifdef HAVE_PROC_PIDPATH
193 #include <libproc.h>
194 #endif
195 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
196 #include <pthread.h>
197 #include <sched.h>
198 #endif
199 #ifdef HAVE_RTKIT
200 #include <sys/time.h>
201 #include <sys/resource.h>
203 #include "dbus_wrap.h"
204 #include "rtkit.h"
205 #ifndef RLIMIT_RTTIME
206 #define RLIMIT_RTTIME 15
207 #endif
208 #endif
210 const PathNamePair &GetProcBinary()
212 static al::optional<PathNamePair> procbin;
213 if(procbin) return *procbin;
215 al::vector<char> pathname;
216 #ifdef __FreeBSD__
217 size_t pathlen;
218 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
219 if(sysctl(mib, 4, nullptr, &pathlen, nullptr, 0) == -1)
220 WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno));
221 else
223 pathname.resize(pathlen + 1);
224 sysctl(mib, 4, pathname.data(), &pathlen, nullptr, 0);
225 pathname.resize(pathlen);
227 #endif
228 #ifdef HAVE_PROC_PIDPATH
229 if(pathname.empty())
231 char procpath[PROC_PIDPATHINFO_MAXSIZE]{};
232 const pid_t pid{getpid()};
233 if(proc_pidpath(pid, procpath, sizeof(procpath)) < 1)
234 ERR("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
235 else
236 pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
238 #endif
239 #ifdef __HAIKU__
240 if(pathname.empty())
242 char procpath[PATH_MAX];
243 if(find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, procpath, sizeof(procpath)) == B_OK)
244 pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
246 #endif
247 #ifndef __SWITCH__
248 if(pathname.empty())
250 static const char SelfLinkNames[][32]{
251 "/proc/self/exe",
252 "/proc/self/file",
253 "/proc/curproc/exe",
254 "/proc/curproc/file"
257 pathname.resize(256);
259 const char *selfname{};
260 ssize_t len{};
261 for(const char *name : SelfLinkNames)
263 selfname = name;
264 len = readlink(selfname, pathname.data(), pathname.size());
265 if(len >= 0 || errno != ENOENT) break;
268 while(len > 0 && static_cast<size_t>(len) == pathname.size())
270 pathname.resize(pathname.size() << 1);
271 len = readlink(selfname, pathname.data(), pathname.size());
273 if(len <= 0)
275 WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
276 len = 0;
279 pathname.resize(static_cast<size_t>(len));
281 #endif
282 while(!pathname.empty() && pathname.back() == 0)
283 pathname.pop_back();
285 auto sep = std::find(pathname.crbegin(), pathname.crend(), '/');
286 if(sep != pathname.crend())
287 procbin = al::make_optional<PathNamePair>(std::string(pathname.cbegin(), sep.base()-1),
288 std::string(sep.base(), pathname.cend()));
289 else
290 procbin = al::make_optional<PathNamePair>(std::string{},
291 std::string(pathname.cbegin(), pathname.cend()));
293 TRACE("Got binary: \"%s\", \"%s\"\n", procbin->path.c_str(), procbin->fname.c_str());
294 return *procbin;
297 namespace {
299 void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
301 TRACE("Searching %s for *%s\n", path, ext);
302 DIR *dir{opendir(path)};
303 if(!dir) return;
305 const auto base = results->size();
306 const size_t extlen{strlen(ext)};
308 while(struct dirent *dirent{readdir(dir)})
310 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
311 continue;
313 const size_t len{strlen(dirent->d_name)};
314 if(len <= extlen) continue;
315 if(al::strcasecmp(dirent->d_name+len-extlen, ext) != 0)
316 continue;
318 results->emplace_back();
319 std::string &str = results->back();
320 str = path;
321 if(str.back() != '/')
322 str.push_back('/');
323 str += dirent->d_name;
325 closedir(dir);
327 const al::span<std::string> newlist{results->data()+base, results->size()-base};
328 std::sort(newlist.begin(), newlist.end());
329 for(const auto &name : newlist)
330 TRACE(" got %s\n", name.c_str());
333 } // namespace
335 al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
337 static std::mutex search_lock;
338 std::lock_guard<std::mutex> _{search_lock};
340 al::vector<std::string> results;
341 if(subdir[0] == '/')
343 DirectorySearch(subdir, ext, &results);
344 return results;
347 /* Search the app-local directory. */
348 if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH"))
349 DirectorySearch(localpath->c_str(), ext, &results);
350 else
352 al::vector<char> cwdbuf(256);
353 while(!getcwd(cwdbuf.data(), cwdbuf.size()))
355 if(errno != ERANGE)
357 cwdbuf.clear();
358 break;
360 cwdbuf.resize(cwdbuf.size() << 1);
362 if(cwdbuf.empty())
363 DirectorySearch(".", ext, &results);
364 else
366 DirectorySearch(cwdbuf.data(), ext, &results);
367 cwdbuf.clear();
371 // Search local data dir
372 if(auto datapath = al::getenv("XDG_DATA_HOME"))
374 std::string &path = *datapath;
375 if(path.back() != '/')
376 path += '/';
377 path += subdir;
378 DirectorySearch(path.c_str(), ext, &results);
380 else if(auto homepath = al::getenv("HOME"))
382 std::string &path = *homepath;
383 if(path.back() == '/')
384 path.pop_back();
385 path += "/.local/share/";
386 path += subdir;
387 DirectorySearch(path.c_str(), ext, &results);
390 // Search global data dirs
391 std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
393 size_t curpos{0u};
394 while(curpos < datadirs.size())
396 size_t nextpos{datadirs.find(':', curpos)};
398 std::string path{(nextpos != std::string::npos) ?
399 datadirs.substr(curpos, nextpos++ - curpos) : datadirs.substr(curpos)};
400 curpos = nextpos;
402 if(path.empty()) continue;
403 if(path.back() != '/')
404 path += '/';
405 path += subdir;
407 DirectorySearch(path.c_str(), ext, &results);
410 return results;
413 namespace {
415 bool SetRTPriorityPthread(int prio)
417 int err{ENOTSUP};
418 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
419 /* Get the min and max priority for SCHED_RR. Limit the max priority to
420 * half, for now, to ensure the thread can't take the highest priority and
421 * go rogue.
423 int rtmin{sched_get_priority_min(SCHED_RR)};
424 int rtmax{sched_get_priority_max(SCHED_RR)};
425 rtmax = (rtmax-rtmin)/2 + rtmin;
427 struct sched_param param{};
428 param.sched_priority = clampi(prio, rtmin, rtmax);
429 #ifdef SCHED_RESET_ON_FORK
430 err = pthread_setschedparam(pthread_self(), SCHED_RR|SCHED_RESET_ON_FORK, &param);
431 if(err == EINVAL)
432 #endif
433 err = pthread_setschedparam(pthread_self(), SCHED_RR, &param);
434 if(err == 0) return true;
435 #endif
437 WARN("pthread_setschedparam failed: %s (%d)\n", std::strerror(err), err);
438 return false;
441 bool SetRTPriorityRTKit(int prio)
443 #ifdef HAVE_RTKIT
444 if(!HasDBus())
446 WARN("D-Bus not available\n");
447 return false;
449 dbus::Error error;
450 dbus::ConnectionPtr conn{dbus_bus_get(DBUS_BUS_SYSTEM, &error.get())};
451 if(!conn)
453 WARN("D-Bus connection failed with %s: %s\n", error->name, error->message);
454 return false;
457 /* Don't stupidly exit if the connection dies while doing this. */
458 dbus_connection_set_exit_on_disconnect(conn.get(), false);
460 auto limit_rttime = [](DBusConnection *c) -> int
462 using ulonglong = unsigned long long;
463 long long maxrttime{rtkit_get_rttime_usec_max(c)};
464 if(maxrttime <= 0) return static_cast<int>(std::abs(maxrttime));
465 const ulonglong umaxtime{static_cast<ulonglong>(maxrttime)};
467 struct rlimit rlim{};
468 if(getrlimit(RLIMIT_RTTIME, &rlim) != 0)
469 return errno;
471 TRACE("RTTime max: %llu (hard: %llu, soft: %llu)\n", umaxtime, ulonglong{rlim.rlim_max},
472 ulonglong{rlim.rlim_cur});
473 if(rlim.rlim_max > umaxtime)
475 rlim.rlim_max = static_cast<rlim_t>(umaxtime);
476 rlim.rlim_cur = std::min(rlim.rlim_cur, rlim.rlim_max);
477 if(setrlimit(RLIMIT_RTTIME, &rlim) != 0)
478 return errno;
480 return 0;
483 int nicemin{};
484 int err{rtkit_get_min_nice_level(conn.get(), &nicemin)};
485 if(err == -ENOENT)
487 err = std::abs(err);
488 ERR("Could not query RTKit: %s (%d)\n", std::strerror(err), err);
489 return false;
491 int rtmax{rtkit_get_max_realtime_priority(conn.get())};
492 TRACE("Maximum real-time priority: %d, minimum niceness: %d\n", rtmax, nicemin);
494 if(rtmax > 0)
496 if(AllowRTTimeLimit)
498 err = limit_rttime(conn.get());
499 if(err != 0)
500 WARN("Failed to set RLIMIT_RTTIME for RTKit: %s (%d)\n",
501 std::strerror(err), err);
504 /* Limit the maximum real-time priority to half. */
505 rtmax = (rtmax+1)/2;
506 prio = clampi(prio, 1, rtmax);
508 TRACE("Making real-time with priority %d (max: %d)\n", prio, rtmax);
509 err = rtkit_make_realtime(conn.get(), 0, prio);
510 if(err == 0) return true;
512 err = std::abs(err);
513 WARN("Failed to set real-time priority: %s (%d)\n", std::strerror(err), err);
515 /* Don't try to set the niceness for non-Linux systems. Standard POSIX has
516 * niceness as a per-process attribute, while the intent here is for the
517 * audio processing thread only to get a priority boost. Currently only
518 * Linux is known to have per-thread niceness.
520 #ifdef __linux__
521 if(nicemin < 0)
523 TRACE("Making high priority with niceness %d\n", nicemin);
524 err = rtkit_make_high_priority(conn.get(), 0, nicemin);
525 if(err == 0) return true;
527 err = std::abs(err);
528 WARN("Failed to set high priority: %s (%d)\n", std::strerror(err), err);
530 #endif /* __linux__ */
532 #else
534 WARN("D-Bus not supported\n");
535 #endif
536 return false;
539 } // namespace
541 void SetRTPriority()
543 if(RTPrioLevel <= 0)
544 return;
546 if(SetRTPriorityPthread(RTPrioLevel))
547 return;
548 if(SetRTPriorityRTKit(RTPrioLevel))
549 return;
552 #endif