Skip to content

Commit

Permalink
avoid using LocalFree on FormatMessageW buffer (microsoft#10796)
Browse files Browse the repository at this point in the history
* remove local free

* Remove local free from onnxruntime

* don't allocate

* Change to use constexpr to satisfy  CPU build warning
  • Loading branch information
Ryan Lai authored and lavanyax committed Mar 29, 2022
1 parent 180d74c commit 885a2a6
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions onnxruntime/core/platform/windows/env.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand Down

0 comments on commit 885a2a6

Please # to comment.