error.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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(ANDROID) || \
  29. (defined(__GLIBC__) && (_GNU_SOURCE || (_POSIX_C_SOURCE < 200112L && _XOPEN_SOURCE < 600)))
  30. // Thread safe (GNU-specific)
  31. const char* str = strerror_r(e, err_str, sizeof(err_str));
  32. return std::string(str);
  33. #else
  34. // Thread safe (XSI-compliant)
  35. int second_err = strerror_r(e, err_str, sizeof(err_str));
  36. if (second_err != 0) {
  37. return "(strerror_r failed to format error)";
  38. }
  39. return std::string(err_str);
  40. #endif // GLIBC etc.
  41. #endif // _WIN32
  42. }
  43. std::string GetLastErrorMsg() {
  44. #ifdef _WIN32
  45. return NativeErrorToString(GetLastError());
  46. #else
  47. return NativeErrorToString(errno);
  48. #endif
  49. }
  50. } // namespace Common