returns the filename of the given process or the current one
| 950 | // returns the filename of the given process or the current one |
| 951 | // |
| 952 | std::filesystem::path processPath(HANDLE process = INVALID_HANDLE_VALUE) |
| 953 | { |
| 954 | // double the buffer size 10 times |
| 955 | const int MaxTries = 10; |
| 956 | |
| 957 | DWORD bufferSize = MAX_PATH; |
| 958 | |
| 959 | for (int tries = 0; tries < MaxTries; ++tries) { |
| 960 | auto buffer = std::make_unique<wchar_t[]>(bufferSize + 1); |
| 961 | std::fill(buffer.get(), buffer.get() + bufferSize + 1, 0); |
| 962 | |
| 963 | DWORD writtenSize = 0; |
| 964 | |
| 965 | if (process == INVALID_HANDLE_VALUE) { |
| 966 | // query this process |
| 967 | writtenSize = GetModuleFileNameW(0, buffer.get(), bufferSize); |
| 968 | } else { |
| 969 | // query another process |
| 970 | writtenSize = GetModuleBaseNameW(process, 0, buffer.get(), bufferSize); |
| 971 | } |
| 972 | |
| 973 | if (writtenSize == 0) { |
| 974 | // hard failure |
| 975 | const auto e = GetLastError(); |
| 976 | std::wcerr << formatSystemMessage(e) << L"\n"; |
| 977 | break; |
| 978 | } else if (writtenSize >= bufferSize) { |
| 979 | // buffer is too small, try again |
| 980 | bufferSize *= 2; |
| 981 | } else { |
| 982 | // if GetModuleFileName() works, `writtenSize` does not include the null |
| 983 | // terminator |
| 984 | const std::wstring s(buffer.get(), writtenSize); |
| 985 | const std::filesystem::path path(s); |
| 986 | |
| 987 | return path; |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | // something failed or the path is way too long to make sense |
| 992 | |
| 993 | std::wstring what; |
| 994 | if (process == INVALID_HANDLE_VALUE) { |
| 995 | what = L"the current process"; |
| 996 | } else { |
| 997 | what = L"pid " + std::to_wstring(reinterpret_cast<std::uintptr_t>(process)); |
| 998 | } |
| 999 | |
| 1000 | std::wcerr << L"failed to get filename for " << what << L"\n"; |
| 1001 | return {}; |
| 1002 | } |
| 1003 | |
| 1004 | std::wstring processFilename(HANDLE process = INVALID_HANDLE_VALUE) |
| 1005 | { |
no test coverage detected