Bugs (fixed):
* Md shared memory file names have unexpanded variable: '${BTS_SHARED_MEMORY_PREFIX}'
1151 lines
31 KiB
C++
1151 lines
31 KiB
C++
#include "os.h"
|
|
#include "system/app_data_dir.h"
|
|
#include "system/bts_array_size.h"
|
|
#include "system/bts_debugger.h"
|
|
#include "system/facades/bts_assert.h"
|
|
#include "system/macros/unused.h"
|
|
|
|
#include <boost/algorithm/string/replace.hpp>
|
|
#include <boost/asio.hpp>
|
|
#include <boost/filesystem/operations.hpp>
|
|
#include <regex>
|
|
|
|
#ifdef _WIN32
|
|
#include <ObjBase.h>
|
|
#include <windows.h>
|
|
#ifdef GetMessage
|
|
#undef GetMessage
|
|
#endif
|
|
#include <Wbemidl.h>
|
|
#include <Winsock2.h>
|
|
#include <Ws2tcpip.h>
|
|
#include <comdef.h>
|
|
#include <direct.h>
|
|
#include <iphlpapi.h>
|
|
#else
|
|
#include <arpa/inet.h>
|
|
#include <dlfcn.h>
|
|
#include <ifaddrs.h>
|
|
#include <netdb.h>
|
|
#include <netinet/in.h>
|
|
#include <pwd.h>
|
|
#include <sys/prctl.h>
|
|
#include <sys/resource.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
#include <uuid/uuid.h>
|
|
#endif
|
|
|
|
#include <stdexcept>
|
|
|
|
#include <cstdlib>
|
|
#ifndef _WIN32
|
|
#include <dirent.h>
|
|
#endif
|
|
#include <fstream>
|
|
#include <limits>
|
|
#include <mutex>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h> // strlcpy
|
|
#include <sys/stat.h>
|
|
#include <vector>
|
|
|
|
#ifndef NO_CPP0X
|
|
#include <thread>
|
|
#endif
|
|
|
|
#include <boost/filesystem.hpp>
|
|
|
|
#ifdef _WIN32
|
|
#pragma comment(lib, "wbemuuid.lib")
|
|
#endif
|
|
|
|
namespace bts {
|
|
namespace os {
|
|
|
|
using Path = boost::filesystem::path;
|
|
|
|
unsigned int process_id() {
|
|
#ifdef _WIN32
|
|
return GetCurrentProcessId();
|
|
#else
|
|
return getpid();
|
|
#endif
|
|
}
|
|
|
|
Path process_path() {
|
|
#ifdef _WIN32
|
|
char process_name[MAX_PATH];
|
|
if (GetModuleFileName(NULL, process_name, MAX_PATH)) {
|
|
return Path(process_name);
|
|
}
|
|
#else
|
|
char process_name[PATH_MAX];
|
|
ssize_t count = readlink("/proc/self/exe", process_name, PATH_MAX);
|
|
if (count != -1) {
|
|
// Null terminate the string
|
|
process_name[count] = '\0';
|
|
return Path(process_name);
|
|
}
|
|
#endif
|
|
bts_assert_msg(false, "Failed to get process name");
|
|
}
|
|
|
|
bool is_running(unsigned int pid) {
|
|
#ifdef _WIN32
|
|
HANDLE handle = OpenProcess(SYNCHRONIZE, false, pid);
|
|
auto err = GetLastError();
|
|
// ERROR_INVALID_PARAMETER is returned when the pid is not valid
|
|
// If we're out of memory a different error code is returned but I'm having a
|
|
// hard time figuring out what it is...
|
|
if (!handle && err == ERROR_INVALID_PARAMETER)
|
|
return false;
|
|
CloseHandle(handle);
|
|
return true;
|
|
#else
|
|
return kill(pid, 0) != -1;
|
|
#endif
|
|
}
|
|
|
|
bool parse_int(const std::string &str, int *result) {
|
|
std::stringstream conv;
|
|
conv << str;
|
|
conv >> *result;
|
|
return conv.eof();
|
|
}
|
|
|
|
std::vector<std::string> parse_cmd_line(std::string const &cmd_line) {
|
|
const int ws = 0;
|
|
const int qt = 1;
|
|
const int t = 2;
|
|
|
|
std::vector<std::string> result;
|
|
size_t n = 0;
|
|
int state = ws;
|
|
while (n < cmd_line.size()) {
|
|
switch (state) {
|
|
case ws:
|
|
if (isspace(cmd_line[n]))
|
|
n++;
|
|
else if (cmd_line[n] == '"') {
|
|
n++;
|
|
result.push_back("");
|
|
state = qt;
|
|
} else {
|
|
result.push_back("");
|
|
result.back().push_back(cmd_line[n]);
|
|
n++;
|
|
state = t;
|
|
}
|
|
break;
|
|
case qt:
|
|
if (cmd_line[n] == '"') {
|
|
n++;
|
|
state = ws;
|
|
} else {
|
|
result.back().push_back(cmd_line[n]);
|
|
n++;
|
|
}
|
|
break;
|
|
case t:
|
|
if (isspace(cmd_line[n])) {
|
|
n++;
|
|
state = ws;
|
|
} else {
|
|
result.back().push_back(cmd_line[n]);
|
|
n++;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
#ifdef _WIN32
|
|
std::string ConvertWCSToMBS(const wchar_t *pstr, long wslen) {
|
|
int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);
|
|
|
|
std::string dblstr(len, '\0');
|
|
len = ::WideCharToMultiByte(
|
|
CP_ACP, 0 /* no flags */, pstr,
|
|
wslen /* not necessary NULL-terminated */, &dblstr[0], len, NULL,
|
|
NULL /* no default char */);
|
|
|
|
return dblstr;
|
|
}
|
|
|
|
std::string bstr_to_str(BSTR const &bstr) {
|
|
int wslen = ::SysStringLen(bstr);
|
|
return ConvertWCSToMBS((wchar_t *)bstr, wslen);
|
|
}
|
|
#endif
|
|
|
|
#ifdef _WIN32
|
|
struct RunningProcessesQuerier::PImpl {
|
|
PImpl() : pLoc(NULL), pSvc(NULL), where() {}
|
|
IWbemLocator *pLoc;
|
|
IWbemServices *pSvc;
|
|
std::string where;
|
|
};
|
|
|
|
RunningProcessesQuerier::RunningProcessesQuerier(
|
|
std::vector<std::string> const &exes)
|
|
: me(new PImpl()) {
|
|
|
|
for (size_t i = 0; i < exes.size(); i++) {
|
|
if (me->where.size())
|
|
me->where += " or ";
|
|
me->where += "Name='" + exes[i] + ".exe'";
|
|
}
|
|
|
|
HRESULT hres;
|
|
CoInitializeEx(0, COINIT_MULTITHREADED);
|
|
CoInitializeSecurity(
|
|
NULL,
|
|
-1, // COM authentication
|
|
NULL, // Authentication services
|
|
NULL, // Reserved
|
|
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
|
|
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
|
|
NULL, // Authentication info
|
|
EOAC_NONE, // Additional capabilities
|
|
NULL // Reserved
|
|
);
|
|
hres = CoCreateInstance(
|
|
CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator,
|
|
(LPVOID *)&me->pLoc);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
hres = me->pLoc->ConnectServer(
|
|
_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, 0, 0, 0, &me->pSvc);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
hres = CoSetProxyBlanket(
|
|
me->pSvc, // Indicates the proxy to set
|
|
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
|
|
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
|
|
NULL, // Server principal name
|
|
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
|
|
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
|
|
NULL, // client identity
|
|
EOAC_NONE // proxy capabilities
|
|
);
|
|
|
|
assert(!FAILED(hres));
|
|
}
|
|
|
|
std::vector<ProcInfo> RunningProcessesQuerier::query() {
|
|
std::vector<ProcInfo> result;
|
|
IEnumWbemClassObject *pEnumerator = NULL;
|
|
std::string query = "Select Name,ProcessId,CommandLine from Win32_Process";
|
|
if (me->where.size())
|
|
query += " Where " + me->where;
|
|
|
|
HRESULT hres = me->pSvc->ExecQuery(
|
|
bstr_t("WQL"), bstr_t(query.c_str()),
|
|
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL,
|
|
&pEnumerator);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
IWbemClassObject *pclsObj = 0;
|
|
ULONG uReturn = 0;
|
|
|
|
while (pEnumerator) {
|
|
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
|
|
if (0 == uReturn)
|
|
break;
|
|
|
|
ProcInfo i;
|
|
|
|
VARIANT vtProp;
|
|
// Get the value of the Name property
|
|
pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
|
|
i.exe = bstr_to_str(vtProp.bstrVal);
|
|
boost::replace_all(i.exe, ".exe", "");
|
|
VariantClear(&vtProp);
|
|
|
|
pclsObj->Get(L"CommandLine", 0, &vtProp, 0, 0);
|
|
i.args = parse_cmd_line(bstr_to_str(vtProp.bstrVal));
|
|
VariantClear(&vtProp);
|
|
|
|
pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);
|
|
i.pid = vtProp.intVal;
|
|
VariantClear(&vtProp);
|
|
|
|
pclsObj->Release();
|
|
result.push_back(i);
|
|
}
|
|
pEnumerator->Release();
|
|
return result;
|
|
}
|
|
|
|
RunningProcessesQuerier::~RunningProcessesQuerier() {
|
|
me->pSvc->Release();
|
|
me->pLoc->Release();
|
|
}
|
|
|
|
#else
|
|
struct RunningProcessesQuerier::PImpl {};
|
|
RunningProcessesQuerier::RunningProcessesQuerier(
|
|
std::vector<std::string> const &)
|
|
: me() {}
|
|
RunningProcessesQuerier::~RunningProcessesQuerier() {}
|
|
std::vector<ProcInfo> RunningProcessesQuerier::query() {
|
|
return os::running_processes();
|
|
}
|
|
#endif
|
|
|
|
std::vector<ProcInfo> running_processes() {
|
|
std::vector<ProcInfo> result;
|
|
#ifdef _WIN32
|
|
HRESULT hres;
|
|
CoInitializeEx(0, COINIT_MULTITHREADED);
|
|
CoInitializeSecurity(
|
|
NULL,
|
|
-1, // COM authentication
|
|
NULL, // Authentication services
|
|
NULL, // Reserved
|
|
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
|
|
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
|
|
NULL, // Authentication info
|
|
EOAC_NONE, // Additional capabilities
|
|
NULL // Reserved
|
|
);
|
|
IWbemLocator *pLoc = NULL;
|
|
|
|
hres = CoCreateInstance(
|
|
CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator,
|
|
(LPVOID *)&pLoc);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
IWbemServices *pSvc = NULL;
|
|
|
|
hres = pLoc->ConnectServer(
|
|
_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, 0, 0, 0, &pSvc);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
hres = CoSetProxyBlanket(
|
|
pSvc, // Indicates the proxy to set
|
|
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
|
|
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
|
|
NULL, // Server principal name
|
|
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
|
|
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
|
|
NULL, // client identity
|
|
EOAC_NONE // proxy capabilities
|
|
);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
IEnumWbemClassObject *pEnumerator = NULL;
|
|
hres = pSvc->ExecQuery(
|
|
bstr_t("WQL"), bstr_t("Select * from Win32_Process"),
|
|
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL,
|
|
&pEnumerator);
|
|
|
|
assert(!FAILED(hres));
|
|
|
|
IWbemClassObject *pclsObj = 0;
|
|
ULONG uReturn = 0;
|
|
|
|
while (pEnumerator) {
|
|
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
|
|
if (0 == uReturn)
|
|
break;
|
|
|
|
ProcInfo i;
|
|
|
|
VARIANT vtProp;
|
|
// Get the value of the Name property
|
|
pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
|
|
i.exe = bstr_to_str(vtProp.bstrVal);
|
|
boost::replace_all(i.exe, ".exe", "");
|
|
VariantClear(&vtProp);
|
|
|
|
pclsObj->Get(L"CommandLine", 0, &vtProp, 0, 0);
|
|
i.args = parse_cmd_line(bstr_to_str(vtProp.bstrVal));
|
|
VariantClear(&vtProp);
|
|
|
|
pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);
|
|
i.pid = vtProp.intVal;
|
|
VariantClear(&vtProp);
|
|
|
|
pclsObj->Release();
|
|
result.push_back(i);
|
|
}
|
|
|
|
pSvc->Release();
|
|
pLoc->Release();
|
|
pEnumerator->Release();
|
|
|
|
#else
|
|
boost::filesystem::directory_iterator p("/proc");
|
|
for (; p != boost::filesystem::directory_iterator(); p++) {
|
|
ProcInfo pi;
|
|
int pid;
|
|
if (parse_int(p->path().filename().string(), &pid)) {
|
|
pi.pid = pid;
|
|
std::string file_name(p->path().string() + "/cmdline");
|
|
std::ifstream fs(file_name.c_str());
|
|
std::stringstream sstr;
|
|
sstr << fs.rdbuf();
|
|
if (!fs.bad()) {
|
|
std::string cmd_line = sstr.str();
|
|
bool first_char = true;
|
|
std::string *current = 0;
|
|
for (size_t i = 0; i < cmd_line.size(); i++)
|
|
if (cmd_line[i] != 0) {
|
|
if (first_char) {
|
|
pi.args.push_back("");
|
|
current = &(pi.args.back());
|
|
}
|
|
first_char = false;
|
|
current->push_back(cmd_line[i]);
|
|
} else
|
|
first_char = true;
|
|
// shamelessly copied from get_application_path
|
|
char buffer[1024];
|
|
char temp[32];
|
|
sprintf(temp, "/proc/%d/exe", pi.pid);
|
|
int bytes = readlink(temp, buffer, sizeof(buffer));
|
|
if (bytes > 0) {
|
|
buffer[bytes] = 0;
|
|
pi.exe = boost::filesystem::path(buffer).filename().string();
|
|
}
|
|
result.push_back(pi);
|
|
}
|
|
}
|
|
}
|
|
#endif
|
|
|
|
return result;
|
|
}
|
|
|
|
char const *platform_name() {
|
|
#ifdef _WIN32
|
|
return "Windows";
|
|
#elif __linux__
|
|
return "Linux";
|
|
#else
|
|
#error This function needs to be implemented for your platform
|
|
#endif
|
|
}
|
|
|
|
std::string host_name() {
|
|
char buffer[128];
|
|
bts_assert(gethostname(buffer, BTS_ARRAYSIZE(buffer)) == 0);
|
|
return std::string(buffer);
|
|
}
|
|
|
|
std::string get_application_path(const char *module_name) {
|
|
char buffer[1024];
|
|
#ifdef _WIN32
|
|
int bytes =
|
|
GetModuleFileName(GetModuleHandle(module_name), buffer, sizeof(buffer));
|
|
#elif __linux__
|
|
UNUSED(module_name);
|
|
// I'm not completely happy with this solution but there doesn't seem to be
|
|
// anything
|
|
// more standard.
|
|
char temp[32];
|
|
sprintf(temp, "/proc/%d/exe", getpid());
|
|
int bytes = readlink(temp, buffer, sizeof(buffer));
|
|
#else
|
|
// Most unixes don't have /proc
|
|
#error This function needs to be implemented for your platform
|
|
#endif
|
|
if (bytes > 0) {
|
|
buffer[bytes] = 0;
|
|
return std::string(buffer);
|
|
} else {
|
|
throw std::runtime_error("Cannot read application directory");
|
|
}
|
|
}
|
|
|
|
std::string get_install_path() {
|
|
// The install path is the location of spark_lib (on Windows) since there may
|
|
// be an api client or other entry point (nunit?)
|
|
auto result = get_application_path("libspark");
|
|
// Trim the filename
|
|
size_t last = result.find_last_of("/\\");
|
|
result.erase(last);
|
|
return result;
|
|
}
|
|
|
|
std::string sparkd_wd() { return get_cwd(); }
|
|
|
|
std::string get_application_name() {
|
|
std::string app_path = get_application_path(nullptr);
|
|
size_t last = app_path.find_last_of("/\\");
|
|
if (last + 1 >= app_path.size())
|
|
return "";
|
|
return app_path.substr(last + 1, app_path.size() - last);
|
|
}
|
|
|
|
std::string get_cwd() {
|
|
#ifdef _WIN32
|
|
#define GET_CURRENT_DIR _getcwd
|
|
#else
|
|
#define GET_CURRENT_DIR getcwd
|
|
#endif
|
|
|
|
char current_path[1024];
|
|
if (!GET_CURRENT_DIR(current_path, sizeof(current_path))) {
|
|
throw std::runtime_error("current directory unreadable");
|
|
}
|
|
return std::string(current_path);
|
|
#undef GET_CURRENT_DIR
|
|
}
|
|
|
|
std::string &normalize_path(std::string &path) {
|
|
size_t len = path.length();
|
|
for (size_t x = 0; x < len; x++) {
|
|
if (path[x] == '/' || path[x] == '\\') {
|
|
path[x] = boost::filesystem::path::preferred_separator;
|
|
}
|
|
}
|
|
return path;
|
|
}
|
|
|
|
std::string sanitize_file_name(std::string const &file_name) {
|
|
#ifndef NO_CPP0X
|
|
const std::string forbidden = "\\/:?\"<>|";
|
|
std::string result = file_name;
|
|
std::transform(
|
|
result.begin(), result.end(), result.begin(),
|
|
[&forbidden](char c) -> char {
|
|
if (forbidden.find(c) != std::string::npos)
|
|
return '_';
|
|
else
|
|
return c;
|
|
});
|
|
return result;
|
|
#else
|
|
return file_name;
|
|
#endif
|
|
}
|
|
|
|
void gen_uuid(unsigned char out[16]) {
|
|
#ifdef _WIN32
|
|
GUID out_guid;
|
|
/*
|
|
typedef struct _GUID {
|
|
unsigned long Data1;
|
|
unsigned short Data2;
|
|
unsigned short Data3;
|
|
unsigned char Data4[ 8 ];
|
|
} GUID;
|
|
|
|
I don't think C++ guarantees the above structure is packed, so I
|
|
do the safe thing below and copy each member in turn. -pp
|
|
*/
|
|
CoCreateGuid(&out_guid);
|
|
int idx = 0;
|
|
memcpy<void>(out + idx, &out_guid.Data1, sizeof(out_guid.Data1));
|
|
idx += sizeof(out_guid.Data1);
|
|
|
|
memcpy<void>(out + idx, &out_guid.Data2, sizeof(out_guid.Data2));
|
|
idx += sizeof(out_guid.Data2);
|
|
|
|
memcpy<void>(out + idx, &out_guid.Data3, sizeof(out_guid.Data3));
|
|
idx += sizeof(out_guid.Data3);
|
|
|
|
memcpy<void>(out + idx, &out_guid.Data4, sizeof(out_guid.Data4));
|
|
idx += sizeof(out_guid.Data4);
|
|
bts_assert(idx == 16);
|
|
#else
|
|
uuid_generate(out);
|
|
#endif
|
|
}
|
|
|
|
uint64_t tick_count() {
|
|
#ifdef _WIN32
|
|
LARGE_INTEGER qpcnt;
|
|
QueryPerformanceCounter(&qpcnt);
|
|
return qpcnt.QuadPart;
|
|
#else
|
|
struct timespec ts;
|
|
clock_gettime(CLOCK_REALTIME, &ts);
|
|
return static_cast<int64_t>(1000000000UL) * static_cast<int64_t>(ts.tv_sec) +
|
|
static_cast<int64_t>(ts.tv_nsec);
|
|
#endif
|
|
}
|
|
|
|
std::vector<std::string> g_cmd_args;
|
|
bool g_cmd_args_set;
|
|
|
|
// For compat with langues that don't follow normal CRT init or use a different
|
|
// CRT
|
|
extern "C" BTS_EXPORT void provide_command_line(const char **argv, int argc) {
|
|
if (!g_cmd_args_set) {
|
|
g_cmd_args.reserve(argc);
|
|
for (int x = 0; x < argc; x++) {
|
|
g_cmd_args.push_back(argv[x]);
|
|
}
|
|
g_cmd_args_set = true;
|
|
}
|
|
}
|
|
|
|
std::vector<std::string> get_command_line() {
|
|
if (g_cmd_args_set) {
|
|
// return cached copy
|
|
return g_cmd_args;
|
|
}
|
|
#ifdef _WIN32
|
|
for (int index = 0; index < __argc; index++) {
|
|
if (__argv != nullptr) {
|
|
g_cmd_args.push_back(__argv[index]);
|
|
} else if (__wargv != nullptr) {
|
|
char temp[1024];
|
|
WideCharToMultiByte(
|
|
CP_ACP, 0, __wargv[index], -1, temp, BTS_ARRAYSIZE(temp), nullptr,
|
|
nullptr);
|
|
g_cmd_args.push_back(temp);
|
|
} else {
|
|
bts_assert(__argv != nullptr || __wargv != nullptr);
|
|
}
|
|
}
|
|
g_cmd_args_set = true;
|
|
return g_cmd_args;
|
|
#elif __linux__
|
|
std::vector<std::string> args;
|
|
std::ifstream in("/proc/self/cmdline", std::ios::in);
|
|
if (!in.fail()) {
|
|
std::string current;
|
|
do {
|
|
char ch = in.get();
|
|
if (ch == '\0') {
|
|
args.push_back(current);
|
|
current.clear();
|
|
} else {
|
|
current += ch;
|
|
}
|
|
} while (!in.eof());
|
|
}
|
|
return args;
|
|
#else
|
|
#error This function needs to be implemented for your platform
|
|
#endif
|
|
}
|
|
|
|
void enable_core_dumps() {
|
|
#ifndef _WIN32
|
|
struct rlimit core_limits;
|
|
core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
|
|
setrlimit(RLIMIT_CORE, &core_limits);
|
|
#endif
|
|
}
|
|
|
|
int get_random_port() {
|
|
srand(os::tick_count());
|
|
return rand() % 10000 + 20000;
|
|
}
|
|
|
|
int num_cores() {
|
|
#ifdef _WIN32
|
|
SYSTEM_INFO sysinfo;
|
|
GetSystemInfo(&sysinfo);
|
|
return sysinfo.dwNumberOfProcessors;
|
|
#else
|
|
return sysconf(_SC_NPROCESSORS_ONLN);
|
|
#endif
|
|
}
|
|
|
|
std::string expand_env(std::string name, bool assert_vars_exist) {
|
|
static const std::regex env_re{R"--(\$\{([^}]+)\})--"};
|
|
std::smatch match;
|
|
while (std::regex_search(name, match, env_re)) {
|
|
const auto from = match[0];
|
|
const auto var_name = match[1].str();
|
|
const auto var = std::getenv(var_name.c_str());
|
|
if (!var) {
|
|
bts_assert_msgf(
|
|
!assert_vars_exist, "Environment variable '{}' is undefined",
|
|
std::string{name});
|
|
name.replace(from.first, from.second, "");
|
|
continue;
|
|
}
|
|
name.replace(from.first, from.second, var);
|
|
}
|
|
return name;
|
|
}
|
|
|
|
std::optional<std::string> try_expand_env(const std::string &name) {
|
|
std::string result;
|
|
if (try_expand_env(name, result)) {
|
|
return result;
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
|
|
bool try_expand_env(const std::string &name, std::string &result) {
|
|
result = name;
|
|
static const std::regex env_re{R"--(\$\{([^}]+)\})--"};
|
|
std::smatch match;
|
|
while (std::regex_search(result, match, env_re)) {
|
|
const auto from = match[0];
|
|
const auto var_name = match[1].str();
|
|
const auto var = std::getenv(var_name.c_str());
|
|
if (!var) {
|
|
return false;
|
|
}
|
|
result.replace(from.first, from.second, var);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
Path app_data_path() {
|
|
// Since the app data path is expanded from environment variables, we only
|
|
// compute it once and save the result in a static singleton. This way, even
|
|
// if someone accidentally changes the environment variable during runtime,
|
|
// the application won't suddenly start using a new data dir
|
|
static std::optional<Path> app_data_path_;
|
|
if (app_data_path_) {
|
|
return *app_data_path_;
|
|
}
|
|
static std::mutex cache_lock;
|
|
static std::map<std::string, std::string> active_interfaces;
|
|
std::lock_guard<std::mutex> l(cache_lock);
|
|
if (app_data_path_) {
|
|
return *app_data_path_;
|
|
}
|
|
std::string base_path;
|
|
bts_assert(try_expand_env(APP_DATA_DIR, base_path));
|
|
app_data_path_ = Path{base_path} / "bts" / process_path().filename();
|
|
app_data_path_ = app_data_path_->make_preferred();
|
|
return *app_data_path_;
|
|
}
|
|
|
|
/**
|
|
* @details If @p relative_path doesn't exist and @p mkdirs is true, the
|
|
* missing directories will be created. If the non-existent path ends with a
|
|
* directory separator ('/' or '\'), the full path will be created. Otherwise,
|
|
* the path to the parent directory will be created.
|
|
*/
|
|
boost::filesystem::path app_data_path(
|
|
const boost::filesystem::path &relative_path, bool mkdirs) {
|
|
auto path = app_data_path() / relative_path;
|
|
path.make_preferred();
|
|
bts_assert(!path.empty());
|
|
if (mkdirs && !boost::filesystem::exists(path)) {
|
|
bool is_dir =
|
|
path.string().back() == boost::filesystem::path::preferred_separator;
|
|
if (is_dir) {
|
|
boost::filesystem::create_directories(path);
|
|
} else {
|
|
boost::filesystem::create_directories(path.parent_path());
|
|
}
|
|
}
|
|
return path;
|
|
}
|
|
|
|
std::string username() {
|
|
#ifdef _WIN32
|
|
char buffer[1024];
|
|
DWORD buffer_size = BTS_ARRAYSIZE(buffer);
|
|
if (GetUserNameA((LPSTR)&buffer, &buffer_size)) {
|
|
return buffer;
|
|
}
|
|
#else
|
|
uid_t uid = geteuid();
|
|
struct passwd *pw = getpwuid(uid);
|
|
if (pw) {
|
|
return pw->pw_name;
|
|
}
|
|
#endif
|
|
return "";
|
|
}
|
|
|
|
std::string find_newest_file(
|
|
const std::string &directory,
|
|
std::function<bool(const std::string &)> include_file) {
|
|
include_file(directory);
|
|
#ifndef _WIN32
|
|
struct stat directory_stat;
|
|
if (stat(directory.c_str(), &directory_stat) != 0) {
|
|
return "";
|
|
}
|
|
DIR *dir = opendir(directory.c_str());
|
|
struct dirent *entry;
|
|
struct stat file_stat;
|
|
std::string newest_file_name = "";
|
|
time_t newest_file_time = 0;
|
|
while ((entry = readdir(dir)) != NULL) {
|
|
std::string file_name = entry->d_name;
|
|
if (!include_file(file_name))
|
|
continue;
|
|
std::string file_path = directory + "/" + file_name;
|
|
if (stat(file_path.c_str(), &file_stat) == 0) {
|
|
time_t file_time = file_stat.st_mtime;
|
|
if (file_time > newest_file_time) {
|
|
newest_file_time = file_time;
|
|
newest_file_name = file_name;
|
|
}
|
|
}
|
|
}
|
|
closedir(dir);
|
|
return newest_file_name;
|
|
#else
|
|
bts_assert_msg(false, "Not supported on windows");
|
|
return "";
|
|
#endif
|
|
}
|
|
|
|
char *strncpy(char *dest, const char *src, size_t count) {
|
|
#ifdef _WIN32
|
|
::strncpy_s(dest, count, src, count);
|
|
#else
|
|
// could use strlcpy but that isn't supported on orc
|
|
::strncpy(dest, src, count);
|
|
dest[count - 1] = '\0';
|
|
#endif
|
|
return dest;
|
|
}
|
|
|
|
void setenv(const char *name, const char *value) {
|
|
#ifdef _WIN32
|
|
SetEnvironmentVariable(name, value);
|
|
#else
|
|
::setenv(name, value, true);
|
|
#endif
|
|
}
|
|
|
|
#ifdef _WIN32
|
|
|
|
// Link with Iphlpapi.lib
|
|
#pragma comment(lib, "IPHLPAPI.lib")
|
|
|
|
#define WORKING_BUFFER_SIZE 15000
|
|
#define MAX_TRIES 3
|
|
|
|
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
|
|
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
|
|
|
|
// inline std::wstring convert( const std::string& as )
|
|
// {
|
|
// wchar_t* buf = new wchar_t[as.size() * 2 + 2];
|
|
// swprintf( buf, L"%S", as.c_str() );
|
|
// std::wstring rval = buf;
|
|
// delete[] buf;
|
|
// return rval;
|
|
// }
|
|
|
|
std::map<std::string, std::string> get_windows_ips() {
|
|
std::map<std::string, std::string> result;
|
|
|
|
char address_buffer[256];
|
|
bool success = false;
|
|
|
|
DWORD dwSize = 0;
|
|
DWORD dwRetVal = 0;
|
|
|
|
unsigned int i = 0;
|
|
ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
|
|
GAA_FLAG_SKIP_DNS_SERVER;
|
|
ULONG family = AF_UNSPEC;
|
|
LPVOID lpMsgBuf = NULL;
|
|
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
|
|
ULONG outBufLen = 0;
|
|
ULONG Iterations = 0;
|
|
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
|
|
PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
|
|
|
|
family = AF_INET;
|
|
outBufLen = WORKING_BUFFER_SIZE;
|
|
|
|
do {
|
|
pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
|
|
if (pAddresses == NULL) {
|
|
bts_assert(false);
|
|
}
|
|
|
|
dwRetVal =
|
|
GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
|
|
|
|
if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
|
|
FREE(pAddresses);
|
|
pAddresses = NULL;
|
|
} else {
|
|
break;
|
|
}
|
|
|
|
Iterations++;
|
|
|
|
} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));
|
|
|
|
if (dwRetVal == NO_ERROR) {
|
|
pCurrAddresses = pAddresses;
|
|
while (pCurrAddresses) {
|
|
if ((pCurrAddresses->OperStatus == IfOperStatusUp) &&
|
|
(pCurrAddresses->FirstUnicastAddress)) {
|
|
DWORD length = 256;
|
|
WSAAddressToStringA(
|
|
pCurrAddresses->FirstUnicastAddress->Address.lpSockaddr,
|
|
pCurrAddresses->FirstUnicastAddress->Address.iSockaddrLength,
|
|
NULL, address_buffer, &length);
|
|
|
|
char friendly_name_buffer[256];
|
|
wcstombs(friendly_name_buffer, pCurrAddresses->FriendlyName, 256);
|
|
result[std::string(friendly_name_buffer)] =
|
|
std::string(address_buffer);
|
|
}
|
|
pCurrAddresses = pCurrAddresses->Next;
|
|
}
|
|
}
|
|
|
|
if (pAddresses)
|
|
FREE(pAddresses);
|
|
|
|
return result;
|
|
}
|
|
|
|
#endif
|
|
|
|
BTS_EXPORT std::string default_host_ip() { return host_ip(""); }
|
|
|
|
BTS_EXPORT std::map<std::string, std::string> host_ips() {
|
|
static std::mutex cache_lock;
|
|
static std::map<std::string, std::string> active_interfaces;
|
|
static bool first_time = true;
|
|
|
|
std::lock_guard<std::mutex> l(cache_lock);
|
|
if (!first_time)
|
|
return active_interfaces;
|
|
else
|
|
first_time = false;
|
|
|
|
#ifdef _WIN32
|
|
active_interfaces = get_windows_ips();
|
|
#else
|
|
std::string result;
|
|
struct ifaddrs *ifAddrStruct = NULL;
|
|
struct ifaddrs *ifa = NULL;
|
|
void *tmpAddrPtr = NULL;
|
|
getifaddrs(&ifAddrStruct);
|
|
|
|
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
|
|
if (ifa->ifa_addr != NULL &&
|
|
ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
|
|
// is a valid IP4 Address
|
|
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
|
|
char addressBuffer[INET_ADDRSTRLEN];
|
|
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
|
|
|
|
if (ifa->ifa_flags & IFF_UP) {
|
|
std::string interface(ifa->ifa_name);
|
|
std::string address(addressBuffer);
|
|
|
|
// LOG (Info,gen) << "Interface: "
|
|
// << interface << " is active and has ip "
|
|
// << address;
|
|
active_interfaces[interface] = address;
|
|
}
|
|
}
|
|
}
|
|
if (ifAddrStruct != NULL)
|
|
freeifaddrs(ifAddrStruct);
|
|
#endif
|
|
return active_interfaces;
|
|
}
|
|
|
|
void remove_loopback(std::map<std::string, std::string> &interfaces) {
|
|
std::map<std::string, std::string>::iterator i;
|
|
for (i = interfaces.begin(); i != interfaces.end(); i++)
|
|
if (i->second == "127.0.0.1") {
|
|
interfaces.erase(i->first);
|
|
return;
|
|
}
|
|
}
|
|
|
|
BTS_EXPORT std::string host_ip(std::string const &src_interface_name) {
|
|
static std::mutex cache_lock;
|
|
static std::map<std::string, std::string> interface_ips;
|
|
std::lock_guard<std::mutex> l(cache_lock);
|
|
|
|
std::map<std::string, std::string>::const_iterator it =
|
|
interface_ips.find(src_interface_name);
|
|
if (it != interface_ips.end())
|
|
return it->second;
|
|
|
|
auto interface_name = src_interface_name;
|
|
|
|
std::string default_interface;
|
|
std::string default_ip;
|
|
std::map<std::string, std::string> ips = host_ips();
|
|
std::vector<std::string> interface_order;
|
|
|
|
#ifdef _WIN32
|
|
interface_order.push_back("Local Area Connection 1");
|
|
#else
|
|
interface_order.push_back("eth0");
|
|
interface_order.push_back("br0");
|
|
interface_order.push_back("wlan0");
|
|
#endif
|
|
|
|
if (interface_name.size()) {
|
|
default_interface = interface_name;
|
|
default_ip = ips[interface_name];
|
|
} else {
|
|
if (ips.empty()) {
|
|
default_interface = "";
|
|
default_ip = "";
|
|
} else if (ips.size() == 1) {
|
|
default_interface = ips.begin()->first;
|
|
default_ip = ips.begin()->second;
|
|
} else {
|
|
remove_loopback(ips);
|
|
if (ips.size() == 1) {
|
|
default_interface = ips.begin()->first;
|
|
default_ip = ips.begin()->second;
|
|
} else {
|
|
for (std::string &in : interface_order)
|
|
if (ips[in].size()) {
|
|
default_interface = in;
|
|
default_ip = ips[in];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (default_ip.empty()) {
|
|
|
|
if (src_interface_name.empty()) {
|
|
std::ostringstream msg;
|
|
std::pair<std::string, std::string> p;
|
|
for (auto p : ips)
|
|
msg << p.first << " ";
|
|
// LOG (Fatal,gen) << "Cannot pick default interface. Too many options:
|
|
// "
|
|
// << msg.str ();
|
|
}
|
|
// else
|
|
// LOG (Fatal,gen) << "Could not find interface '" << interface_name;
|
|
bts_assert(false);
|
|
}
|
|
// else
|
|
// LOG (Info,gen) << "Selecting default interface: " << default_interface
|
|
// << " ip is " << default_ip;
|
|
|
|
interface_ips[src_interface_name] = default_ip;
|
|
return default_ip;
|
|
}
|
|
|
|
BTS_EXPORT void set_thread_name(std::string const &n) {
|
|
set_thread_name(n.c_str());
|
|
}
|
|
|
|
BTS_EXPORT void set_thread_name(const char *name) {
|
|
#ifdef _WIN32
|
|
if (!IsDebuggerPresent())
|
|
return;
|
|
|
|
const DWORD MS_VC_EXCEPTION = 0x406D1388;
|
|
#pragma pack(push, 8)
|
|
struct tagTHREADNAME_INFO {
|
|
DWORD dwType; // Must be 0x1000.
|
|
LPCSTR szName; // Pointer to name (in user addr space).
|
|
DWORD dwThreadID; // Thread ID (-1=caller thread).
|
|
DWORD dwFlags; // Reserved for future use, must be zero.
|
|
} info;
|
|
#pragma pack(pop)
|
|
|
|
info.dwType = 0x1000;
|
|
info.szName = name;
|
|
info.dwThreadID = -1;
|
|
info.dwFlags = 0;
|
|
|
|
#ifdef _MSC_VER
|
|
__try {
|
|
#endif
|
|
RaiseException(
|
|
MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR),
|
|
(ULONG_PTR *)&info);
|
|
#ifdef _MSC_VER
|
|
} __except (EXCEPTION_EXECUTE_HANDLER) {
|
|
}
|
|
#endif
|
|
#else
|
|
prctl(PR_SET_NAME, name, 0, 0, 0);
|
|
#endif
|
|
}
|
|
|
|
BTS_EXPORT void get_thread_name(std::string *out) {
|
|
#ifdef _WIN32
|
|
*out = "unknown";
|
|
#else
|
|
out->resize(16);
|
|
pthread_getname_np(pthread_self(), &((*out)[0]), 16);
|
|
auto sz = strlen(out->data());
|
|
out->resize(sz);
|
|
#endif
|
|
}
|
|
|
|
BTS_EXPORT std::string get_thread_name() {
|
|
std::string thread_name;
|
|
get_thread_name(&thread_name);
|
|
return thread_name;
|
|
}
|
|
|
|
BTS_EXPORT float fnan() { return std::numeric_limits<float>::quiet_NaN(); }
|
|
|
|
BTS_EXPORT bool is_finite(double d) {
|
|
#ifdef _WIN32
|
|
return (::_finite(d) != 0);
|
|
#else
|
|
return (::finite(d) != 0);
|
|
#endif
|
|
}
|
|
|
|
int cache_size_l3_bytes() {
|
|
// note: index1,2 are the L1 and L2 caches
|
|
std::fstream stream(
|
|
"/sys/devices/system/cpu/cpu0/cache/index3/size", std::ios_base::in);
|
|
if (stream) {
|
|
int sz;
|
|
stream >> sz;
|
|
return sz * 1024;
|
|
} else {
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
//
|
|
// Interop functions
|
|
//
|
|
namespace interop {
|
|
|
|
extern "C" BTS_EXPORT unsigned int setup_process_job_object() {
|
|
#ifdef _WIN32
|
|
if (IsDebuggerPresent())
|
|
return 0;
|
|
HANDLE hjob = CreateJobObject(nullptr, nullptr);
|
|
if (hjob == nullptr)
|
|
return 100; // Failed to create JOB object.
|
|
|
|
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = {0};
|
|
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
|
|
|
BOOL success = SetInformationJobObject(
|
|
hjob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
|
|
DWORD error = GetLastError();
|
|
if (!success)
|
|
return error;
|
|
success = AssignProcessToJobObject(hjob, GetCurrentProcess());
|
|
error = GetLastError();
|
|
if (!success)
|
|
return error;
|
|
#endif
|
|
return 0;
|
|
}
|
|
|
|
} // namespace interop
|
|
} // namespace os
|
|
} // namespace bts
|