avoid using LocalFree on FormatMessageW buffer (#10796)

* remove local free

* Remove local free from onnxruntime

* don't allocate

* Change to use constexpr to satisfy  CPU build warning
This commit is contained in:
Ryan Lai 2022-03-11 11:11:40 -08:00 committed by GitHub
parent 64556888a1
commit 2e7592ddf8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -544,22 +544,21 @@ class WindowsEnv : public Env {
#endif
if (!*handle) {
const auto error_code = GetLastError();
LPVOID lpMsgBuf;
static constexpr DWORD bufferLength = 64 * 1024;
std::wstring s(bufferLength, '\0');
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpMsgBuf,
(LPWSTR)s.data(),
0, NULL);
std::wostringstream oss;
oss << L"LoadLibrary failed with error " << error_code << L" \"" << (LPWSTR)lpMsgBuf << L"\" when trying to load \"" << wlibrary_filename << L"\"";
oss << L"LoadLibrary failed with error " << error_code << L" \"" << s.c_str() << L"\" when trying to load \"" << wlibrary_filename << L"\"";
std::wstring errmsg = oss.str();
// TODO: trim the ending '\r' and/or '\n'
common::Status status(common::ONNXRUNTIME, common::FAIL, ToUTF8String(errmsg));
LocalFree(lpMsgBuf);
return status;
}
return Status::OK();
@ -577,22 +576,21 @@ class WindowsEnv : public Env {
*symbol = ::GetProcAddress(reinterpret_cast<HMODULE>(handle), symbol_name.c_str());
if (!*symbol) {
const auto error_code = GetLastError();
LPVOID lpMsgBuf;
static constexpr DWORD bufferLength = 64 * 1024;
std::wstring s(bufferLength, '\0');
FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpMsgBuf,
(LPWSTR)s.data(),
0, NULL);
std::wostringstream oss;
oss << L"Failed to find symbol " << ToWideString(symbol_name) << L" in library, error code: " << error_code << L" \"" << (LPWSTR)lpMsgBuf << L"\"";
oss << L"Failed to find symbol " << ToWideString(symbol_name) << L" in library, error code: " << error_code << L" \"" << s.c_str() << L"\"";
std::wstring errmsg = oss.str();
// TODO: trim the ending '\r' and/or '\n'
common::Status status(common::ONNXRUNTIME, common::FAIL, ToUTF8String(errmsg));
LocalFree(lpMsgBuf);
return status;
}
return Status::OK();