win32err.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file win32err.c
  7. * \brief Convert windows error codes to useful C strings.
  8. **/
  9. #ifdef _WIN32
  10. #include "orconfig.h"
  11. #include "lib/log/win32err.h"
  12. #include "lib/malloc/malloc.h"
  13. #include <tchar.h>
  14. #include <windows.h>
  15. /** Return a newly allocated string describing the windows system error code
  16. * <b>err</b>. Note that error codes are different from errno. Error codes
  17. * come from GetLastError() when a winapi call fails. errno is set only when
  18. * ANSI functions fail. Whee. */
  19. char *
  20. format_win32_error(DWORD err)
  21. {
  22. TCHAR *str = NULL;
  23. char *result;
  24. DWORD n;
  25. /* Somebody once decided that this interface was better than strerror(). */
  26. n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  27. FORMAT_MESSAGE_FROM_SYSTEM |
  28. FORMAT_MESSAGE_IGNORE_INSERTS,
  29. NULL, err,
  30. MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
  31. (LPVOID)&str,
  32. 0, NULL);
  33. if (str && n) {
  34. #ifdef UNICODE
  35. size_t len;
  36. if (n > 128*1024)
  37. len = (128 * 1024) * 2 + 1; /* This shouldn't be possible, but let's
  38. * make sure. */
  39. else
  40. len = n * 2 + 1;
  41. result = tor_malloc(len);
  42. wcstombs(result,str,len);
  43. result[len-1] = '\0';
  44. #else /* !(defined(UNICODE)) */
  45. result = tor_strdup(str);
  46. #endif /* defined(UNICODE) */
  47. } else {
  48. result = tor_strdup("<unformattable error>");
  49. }
  50. if (str) {
  51. LocalFree(str); /* LocalFree != free() */
  52. }
  53. return result;
  54. }
  55. #endif /* defined(_WIN32) */