error.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // SPDX-FileCopyrightText: 2013 Dolphin Emulator Project
  2. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. #include <cstddef>
  5. #ifdef _WIN32
  6. #include <windows.h>
  7. #else
  8. #include <cerrno>
  9. #include <cstring>
  10. #endif
  11. #include "common/error.h"
  12. namespace Common {
  13. std::string NativeErrorToString(int e) {
  14. #ifdef _WIN32
  15. LPSTR err_str;
  16. DWORD res = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER |
  17. FORMAT_MESSAGE_IGNORE_INSERTS,
  18. nullptr, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  19. reinterpret_cast<LPSTR>(&err_str), 1, nullptr);
  20. if (!res) {
  21. return "(FormatMessageA failed to format error)";
  22. }
  23. std::string ret(err_str);
  24. LocalFree(err_str);
  25. return ret;
  26. #else
  27. char err_str[255];
  28. #if defined(__GLIBC__) && (_GNU_SOURCE || (_POSIX_C_SOURCE < 200112L && _XOPEN_SOURCE < 600))
  29. // Thread safe (GNU-specific)
  30. const char* str = strerror_r(e, err_str, sizeof(err_str));
  31. return std::string(str);
  32. #else
  33. // Thread safe (XSI-compliant)
  34. int second_err = strerror_r(e, err_str, sizeof(err_str));
  35. if (second_err != 0) {
  36. return "(strerror_r failed to format error)";
  37. }
  38. return std::string(err_str);
  39. #endif // GLIBC etc.
  40. #endif // _WIN32
  41. }
  42. std::string GetLastErrorMsg() {
  43. #ifdef _WIN32
  44. return NativeErrorToString(GetLastError());
  45. #else
  46. return NativeErrorToString(errno);
  47. #endif
  48. }
  49. } // namespace Common