win32err.c 1.6 KB

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