Make some structs nested
[openal-soft.git] / core / helpers.cpp
blobe4a94fe5ca15cd708d9d76e184ac63156b824eac
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>
15 #include <tuple>
17 #include "almalloc.h"
18 #include "alfstream.h"
19 #include "alnumeric.h"
20 #include "aloptional.h"
21 #include "alspan.h"
22 #include "alstring.h"
23 #include "logging.h"
24 #include "strutils.h"
25 #include "vector.h"
28 /* Mixing thread piority level */
29 int RTPrioLevel{1};
31 /* Allow reducing the process's RTTime limit for RTKit. */
32 bool AllowRTTimeLimit{true};
35 #ifdef _WIN32
37 #include <shlobj.h>
39 const PathNamePair &GetProcBinary()
41 static al::optional<PathNamePair> procbin;
42 if(procbin) return *procbin;
44 auto fullpath = al::vector<WCHAR>(256);
45 DWORD len{GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()))};
46 while(len == fullpath.size())
48 fullpath.resize(fullpath.size() << 1);
49 len = GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()));
51 if(len == 0)
53 ERR("Failed to get process name: error %lu\n", GetLastError());
54 procbin = al::make_optional<PathNamePair>();
55 return *procbin;
58 fullpath.resize(len);
59 if(fullpath.back() != 0)
60 fullpath.push_back(0);
62 auto sep = std::find(fullpath.rbegin()+1, fullpath.rend(), '\\');
63 sep = std::find(fullpath.rbegin()+1, sep, '/');
64 if(sep != fullpath.rend())
66 *sep = 0;
67 procbin = al::make_optional<PathNamePair>(wstr_to_utf8(fullpath.data()),
68 wstr_to_utf8(&*sep + 1));
70 else
71 procbin = al::make_optional<PathNamePair>(std::string{}, wstr_to_utf8(fullpath.data()));
73 TRACE("Got binary: %s, %s\n", procbin->path.c_str(), procbin->fname.c_str());
74 return *procbin;
77 namespace {
79 void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
81 std::string pathstr{path};
82 pathstr += "\\*";
83 pathstr += ext;
84 TRACE("Searching %s\n", pathstr.c_str());
86 std::wstring wpath{utf8_to_wstr(pathstr.c_str())};
87 WIN32_FIND_DATAW fdata;
88 HANDLE hdl{FindFirstFileW(wpath.c_str(), &fdata)};
89 if(hdl == INVALID_HANDLE_VALUE) return;
91 const auto base = results->size();
93 do {
94 results->emplace_back();
95 std::string &str = results->back();
96 str = path;
97 str += '\\';
98 str += wstr_to_utf8(fdata.cFileName);
99 } while(FindNextFileW(hdl, &fdata));
100 FindClose(hdl);
102 const al::span<std::string> newlist{results->data()+base, results->size()-base};
103 std::sort(newlist.begin(), newlist.end());
104 for(const auto &name : newlist)
105 TRACE(" got %s\n", name.c_str());
108 } // namespace
110 al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
112 auto is_slash = [](int c) noexcept -> int { return (c == '\\' || c == '/'); };
114 static std::mutex search_lock;
115 std::lock_guard<std::mutex> _{search_lock};
117 /* If the path is absolute, use it directly. */
118 al::vector<std::string> results;
119 if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
121 std::string path{subdir};
122 std::replace(path.begin(), path.end(), '/', '\\');
123 DirectorySearch(path.c_str(), ext, &results);
124 return results;
126 if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
128 DirectorySearch(subdir, ext, &results);
129 return results;
132 std::string path;
134 /* Search the app-local directory. */
135 if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH"))
137 path = wstr_to_utf8(localpath->c_str());
138 if(is_slash(path.back()))
139 path.pop_back();
141 else if(WCHAR *cwdbuf{_wgetcwd(nullptr, 0)})
143 path = wstr_to_utf8(cwdbuf);
144 if(is_slash(path.back()))
145 path.pop_back();
146 free(cwdbuf);
148 else
149 path = ".";
150 std::replace(path.begin(), path.end(), '/', '\\');
151 DirectorySearch(path.c_str(), ext, &results);
153 /* Search the local and global data dirs. */
154 static const int ids[2]{ CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
155 for(int id : ids)
157 WCHAR buffer[MAX_PATH];
158 if(SHGetSpecialFolderPathW(nullptr, buffer, id, FALSE) == FALSE)
159 continue;
161 path = wstr_to_utf8(buffer);
162 if(!is_slash(path.back()))
163 path += '\\';
164 path += subdir;
165 std::replace(path.begin(), path.end(), '/', '\\');
167 DirectorySearch(path.c_str(), ext, &results);
170 return results;
173 void SetRTPriority(void)
175 if(RTPrioLevel > 0)
177 if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
178 ERR("Failed to set priority level for thread\n");
182 #else
184 #include <sys/types.h>
185 #include <unistd.h>
186 #include <dirent.h>
187 #ifdef __FreeBSD__
188 #include <sys/sysctl.h>
189 #endif
190 #ifdef __HAIKU__
191 #include <FindDirectory.h>
192 #endif
193 #ifdef HAVE_PROC_PIDPATH
194 #include <libproc.h>
195 #endif
196 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
197 #include <pthread.h>
198 #include <sched.h>
199 #endif
200 #ifdef HAVE_RTKIT
201 #include <sys/time.h>
202 #include <sys/resource.h>
204 #include "dbus_wrap.h"
205 #include "rtkit.h"
206 #ifndef RLIMIT_RTTIME
207 #define RLIMIT_RTTIME 15
208 #endif
209 #endif
211 const PathNamePair &GetProcBinary()
213 static al::optional<PathNamePair> procbin;
214 if(procbin) return *procbin;
216 al::vector<char> pathname;
217 #ifdef __FreeBSD__
218 size_t pathlen;
219 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
220 if(sysctl(mib, 4, nullptr, &pathlen, nullptr, 0) == -1)
221 WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno));
222 else
224 pathname.resize(pathlen + 1);
225 sysctl(mib, 4, pathname.data(), &pathlen, nullptr, 0);
226 pathname.resize(pathlen);
228 #endif
229 #ifdef HAVE_PROC_PIDPATH
230 if(pathname.empty())
232 char procpath[PROC_PIDPATHINFO_MAXSIZE]{};
233 const pid_t pid{getpid()};
234 if(proc_pidpath(pid, procpath, sizeof(procpath)) < 1)
235 ERR("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
236 else
237 pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
239 #endif
240 #ifdef __HAIKU__
241 if(pathname.empty())
243 char procpath[PATH_MAX];
244 if(find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, procpath, sizeof(procpath)) == B_OK)
245 pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
247 #endif
248 #ifndef __SWITCH__
249 if(pathname.empty())
251 static const char SelfLinkNames[][32]{
252 "/proc/self/exe",
253 "/proc/self/file",
254 "/proc/curproc/exe",
255 "/proc/curproc/file"
258 pathname.resize(256);
260 const char *selfname{};
261 ssize_t len{};
262 for(const char *name : SelfLinkNames)
264 selfname = name;
265 len = readlink(selfname, pathname.data(), pathname.size());
266 if(len >= 0 || errno != ENOENT) break;
269 while(len > 0 && static_cast<size_t>(len) == pathname.size())
271 pathname.resize(pathname.size() << 1);
272 len = readlink(selfname, pathname.data(), pathname.size());
274 if(len <= 0)
276 WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
277 len = 0;
280 pathname.resize(static_cast<size_t>(len));
282 #endif
283 while(!pathname.empty() && pathname.back() == 0)
284 pathname.pop_back();
286 auto sep = std::find(pathname.crbegin(), pathname.crend(), '/');
287 if(sep != pathname.crend())
288 procbin = al::make_optional<PathNamePair>(std::string(pathname.cbegin(), sep.base()-1),
289 std::string(sep.base(), pathname.cend()));
290 else
291 procbin = al::make_optional<PathNamePair>(std::string{},
292 std::string(pathname.cbegin(), pathname.cend()));
294 TRACE("Got binary: \"%s\", \"%s\"\n", procbin->path.c_str(), procbin->fname.c_str());
295 return *procbin;
298 namespace {
300 void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
302 TRACE("Searching %s for *%s\n", path, ext);
303 DIR *dir{opendir(path)};
304 if(!dir) return;
306 const auto base = results->size();
307 const size_t extlen{strlen(ext)};
309 while(struct dirent *dirent{readdir(dir)})
311 if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
312 continue;
314 const size_t len{strlen(dirent->d_name)};
315 if(len <= extlen) continue;
316 if(al::strcasecmp(dirent->d_name+len-extlen, ext) != 0)
317 continue;
319 results->emplace_back();
320 std::string &str = results->back();
321 str = path;
322 if(str.back() != '/')
323 str.push_back('/');
324 str += dirent->d_name;
326 closedir(dir);
328 const al::span<std::string> newlist{results->data()+base, results->size()-base};
329 std::sort(newlist.begin(), newlist.end());
330 for(const auto &name : newlist)
331 TRACE(" got %s\n", name.c_str());
334 } // namespace
336 al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
338 static std::mutex search_lock;
339 std::lock_guard<std::mutex> _{search_lock};
341 al::vector<std::string> results;
342 if(subdir[0] == '/')
344 DirectorySearch(subdir, ext, &results);
345 return results;
348 /* Search the app-local directory. */
349 if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH"))
350 DirectorySearch(localpath->c_str(), ext, &results);
351 else
353 al::vector<char> cwdbuf(256);
354 while(!getcwd(cwdbuf.data(), cwdbuf.size()))
356 if(errno != ERANGE)
358 cwdbuf.clear();
359 break;
361 cwdbuf.resize(cwdbuf.size() << 1);
363 if(cwdbuf.empty())
364 DirectorySearch(".", ext, &results);
365 else
367 DirectorySearch(cwdbuf.data(), ext, &results);
368 cwdbuf.clear();
372 // Search local data dir
373 if(auto datapath = al::getenv("XDG_DATA_HOME"))
375 std::string &path = *datapath;
376 if(path.back() != '/')
377 path += '/';
378 path += subdir;
379 DirectorySearch(path.c_str(), ext, &results);
381 else if(auto homepath = al::getenv("HOME"))
383 std::string &path = *homepath;
384 if(path.back() == '/')
385 path.pop_back();
386 path += "/.local/share/";
387 path += subdir;
388 DirectorySearch(path.c_str(), ext, &results);
391 // Search global data dirs
392 std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
394 size_t curpos{0u};
395 while(curpos < datadirs.size())
397 size_t nextpos{datadirs.find(':', curpos)};
399 std::string path{(nextpos != std::string::npos) ?
400 datadirs.substr(curpos, nextpos++ - curpos) : datadirs.substr(curpos)};
401 curpos = nextpos;
403 if(path.empty()) continue;
404 if(path.back() != '/')
405 path += '/';
406 path += subdir;
408 DirectorySearch(path.c_str(), ext, &results);
411 return results;
414 namespace {
416 bool SetRTPriorityPthread(int prio)
418 int err{ENOTSUP};
419 #if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
420 /* Get the min and max priority for SCHED_RR. Limit the max priority to
421 * half, for now, to ensure the thread can't take the highest priority and
422 * go rogue.
424 int rtmin{sched_get_priority_min(SCHED_RR)};
425 int rtmax{sched_get_priority_max(SCHED_RR)};
426 rtmax = (rtmax-rtmin)/2 + rtmin;
428 struct sched_param param{};
429 param.sched_priority = clampi(prio, rtmin, rtmax);
430 #ifdef SCHED_RESET_ON_FORK
431 err = pthread_setschedparam(pthread_self(), SCHED_RR|SCHED_RESET_ON_FORK, &param);
432 if(err == EINVAL)
433 #endif
434 err = pthread_setschedparam(pthread_self(), SCHED_RR, &param);
435 if(err == 0) return true;
437 #else
439 std::ignore = prio;
440 #endif
441 WARN("pthread_setschedparam failed: %s (%d)\n", std::strerror(err), err);
442 return false;
445 bool SetRTPriorityRTKit(int prio)
447 #ifdef HAVE_RTKIT
448 if(!HasDBus())
450 WARN("D-Bus not available\n");
451 return false;
453 dbus::Error error;
454 dbus::ConnectionPtr conn{dbus_bus_get(DBUS_BUS_SYSTEM, &error.get())};
455 if(!conn)
457 WARN("D-Bus connection failed with %s: %s\n", error->name, error->message);
458 return false;
461 /* Don't stupidly exit if the connection dies while doing this. */
462 dbus_connection_set_exit_on_disconnect(conn.get(), false);
464 auto limit_rttime = [](DBusConnection *c) -> int
466 using ulonglong = unsigned long long;
467 long long maxrttime{rtkit_get_rttime_usec_max(c)};
468 if(maxrttime <= 0) return static_cast<int>(std::abs(maxrttime));
469 const ulonglong umaxtime{static_cast<ulonglong>(maxrttime)};
471 struct rlimit rlim{};
472 if(getrlimit(RLIMIT_RTTIME, &rlim) != 0)
473 return errno;
475 TRACE("RTTime max: %llu (hard: %llu, soft: %llu)\n", umaxtime, ulonglong{rlim.rlim_max},
476 ulonglong{rlim.rlim_cur});
477 if(rlim.rlim_max > umaxtime)
479 rlim.rlim_max = static_cast<rlim_t>(umaxtime);
480 rlim.rlim_cur = std::min(rlim.rlim_cur, rlim.rlim_max);
481 if(setrlimit(RLIMIT_RTTIME, &rlim) != 0)
482 return errno;
484 return 0;
487 int nicemin{};
488 int err{rtkit_get_min_nice_level(conn.get(), &nicemin)};
489 if(err == -ENOENT)
491 err = std::abs(err);
492 ERR("Could not query RTKit: %s (%d)\n", std::strerror(err), err);
493 return false;
495 int rtmax{rtkit_get_max_realtime_priority(conn.get())};
496 TRACE("Maximum real-time priority: %d, minimum niceness: %d\n", rtmax, nicemin);
498 if(rtmax > 0)
500 if(AllowRTTimeLimit)
502 err = limit_rttime(conn.get());
503 if(err != 0)
504 WARN("Failed to set RLIMIT_RTTIME for RTKit: %s (%d)\n",
505 std::strerror(err), err);
508 /* Limit the maximum real-time priority to half. */
509 rtmax = (rtmax+1)/2;
510 prio = clampi(prio, 1, rtmax);
512 TRACE("Making real-time with priority %d (max: %d)\n", prio, rtmax);
513 err = rtkit_make_realtime(conn.get(), 0, prio);
514 if(err == 0) return true;
516 err = std::abs(err);
517 WARN("Failed to set real-time priority: %s (%d)\n", std::strerror(err), err);
519 /* Don't try to set the niceness for non-Linux systems. Standard POSIX has
520 * niceness as a per-process attribute, while the intent here is for the
521 * audio processing thread only to get a priority boost. Currently only
522 * Linux is known to have per-thread niceness.
524 #ifdef __linux__
525 if(nicemin < 0)
527 TRACE("Making high priority with niceness %d\n", nicemin);
528 err = rtkit_make_high_priority(conn.get(), 0, nicemin);
529 if(err == 0) return true;
531 err = std::abs(err);
532 WARN("Failed to set high priority: %s (%d)\n", std::strerror(err), err);
534 #endif /* __linux__ */
536 #else
538 std::ignore = prio;
539 WARN("D-Bus not supported\n");
540 #endif
541 return false;
544 } // namespace
546 void SetRTPriority()
548 if(RTPrioLevel <= 0)
549 return;
551 if(SetRTPriorityPthread(RTPrioLevel))
552 return;
553 if(SetRTPriorityRTKit(RTPrioLevel))
554 return;
557 #endif