From 885a2a62bda297584ac5b009d4b7d0429e393c81 Mon Sep 17 00:00:00 2001 From: Ryan Lai Date: Fri, 11 Mar 2022 11:11:40 -0800 Subject: [PATCH] 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 --- onnxruntime/core/platform/windows/env.cc | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/onnxruntime/core/platform/windows/env.cc b/onnxruntime/core/platform/windows/env.cc index 52aa9cd02afd6..1a3818b758def 100644 --- a/onnxruntime/core/platform/windows/env.cc +++ b/onnxruntime/core/platform/windows/env.cc @@ -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(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();