return the path to the directory containing the current executable used to determine the location of auto-loaded plugin libraries
| 73 | // return the path to the directory containing the current executable |
| 74 | // used to determine the location of auto-loaded plugin libraries |
| 75 | std::string getExecutableDir() |
| 76 | { |
| 77 | #if defined(_WIN32) || defined(__CYGWIN__) |
| 78 | constexpr char kPathSep = '\\'; |
| 79 | std::string realpath = [&]() -> std::string |
| 80 | { |
| 81 | std::unique_ptr<char[]> realpath(nullptr); |
| 82 | DWORD buf_size = 128; |
| 83 | bool success = false; |
| 84 | while (!success) |
| 85 | { |
| 86 | realpath.reset(new (std::nothrow) char[buf_size]); |
| 87 | if (!realpath) |
| 88 | { |
| 89 | std::cerr << "cannot allocate memory to store executable path\n"; |
| 90 | return ""; |
| 91 | } |
| 92 | |
| 93 | DWORD written = GetModuleFileNameA(nullptr, realpath.get(), buf_size); |
| 94 | if (written < buf_size) |
| 95 | { |
| 96 | success = true; |
| 97 | } |
| 98 | else if (written == buf_size) |
| 99 | { |
| 100 | // realpath is too small, grow and retry |
| 101 | buf_size *= 2; |
| 102 | } |
| 103 | else |
| 104 | { |
| 105 | std::cerr << "failed to retrieve executable path: " << GetLastError() << "\n"; |
| 106 | return ""; |
| 107 | } |
| 108 | } |
| 109 | return realpath.get(); |
| 110 | }(); |
| 111 | #else |
| 112 | constexpr char kPathSep = '/'; |
| 113 | #if defined(__APPLE__) |
| 114 | std::unique_ptr<char[]> buf(nullptr); |
| 115 | { |
| 116 | std::uint32_t buf_size = 0; |
| 117 | _NSGetExecutablePath(nullptr, &buf_size); |
| 118 | buf.reset(new char[buf_size]); |
| 119 | if (!buf) |
| 120 | { |
| 121 | std::cerr << "cannot allocate memory to store executable path\n"; |
| 122 | return ""; |
| 123 | } |
| 124 | if (_NSGetExecutablePath(buf.get(), &buf_size)) |
| 125 | { |
| 126 | std::cerr << "unexpected error from _NSGetExecutablePath\n"; |
| 127 | } |
| 128 | } |
| 129 | const char *path = buf.get(); |
| 130 | #else |
| 131 | const char *path = "/proc/self/exe"; |
| 132 | #endif |
no test coverage detected