win_util.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (C) 2023 Amazon Inc. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "win_util.h"
  6. __wasi_timestamp_t
  7. convert_filetime_to_wasi_timestamp(LPFILETIME filetime)
  8. {
  9. // From 1601-01-01 to 1970-01-01 there are 134774 days.
  10. static const uint64_t NT_to_UNIX_epoch =
  11. 134774ull * 86400ull * 1000ull * 1000ull * 1000ull;
  12. ULARGE_INTEGER temp = { .HighPart = filetime->dwHighDateTime,
  13. .LowPart = filetime->dwLowDateTime };
  14. // WASI timestamps are measured in nanoseconds whereas FILETIME structs are
  15. // represented in terms 100-nanosecond intervals.
  16. return (temp.QuadPart * 100ull) - NT_to_UNIX_epoch;
  17. }
  18. __wasi_errno_t
  19. convert_windows_error_code(DWORD windows_error_code)
  20. {
  21. switch (windows_error_code) {
  22. case ERROR_INVALID_PARAMETER:
  23. case ERROR_INVALID_HANDLE:
  24. case ERROR_NEGATIVE_SEEK:
  25. return __WASI_EINVAL;
  26. case ERROR_SHARING_VIOLATION:
  27. case ERROR_PIPE_BUSY:
  28. return __WASI_EBUSY;
  29. case ERROR_ACCESS_DENIED:
  30. return __WASI_EACCES;
  31. case ERROR_ALREADY_EXISTS:
  32. case ERROR_FILE_EXISTS:
  33. return __WASI_EEXIST;
  34. case ERROR_NO_MORE_FILES:
  35. case ERROR_FILE_NOT_FOUND:
  36. case ERROR_INVALID_NAME:
  37. return __WASI_ENOENT;
  38. case ERROR_PRIVILEGE_NOT_HELD:
  39. return __WASI_EPERM;
  40. case ERROR_NOT_ENOUGH_MEMORY:
  41. return __WASI_ENOMEM;
  42. case ERROR_NOACCESS:
  43. return __WASI_EFAULT;
  44. case ERROR_DIR_NOT_EMPTY:
  45. return __WASI_ENOTEMPTY;
  46. case ERROR_DIRECTORY:
  47. return __WASI_ENOTDIR;
  48. case ERROR_IO_PENDING:
  49. case ERROR_INSUFFICIENT_BUFFER:
  50. case ERROR_INVALID_FLAGS:
  51. case ERROR_NO_UNICODE_TRANSLATION:
  52. default:
  53. return __WASI_EINVAL;
  54. }
  55. }
  56. #ifdef UWP_DEFAULT_VPRINTF
  57. int
  58. uwp_print_to_debugger(const char *format, va_list ap)
  59. {
  60. // Provide a stack buffer which should be large enough for any realistic
  61. // string so we avoid making an allocation on every printf call.
  62. char stack_buf[2048];
  63. char *buf = stack_buf;
  64. int ret = vsnprintf(stack_buf, sizeof(stack_buf), format, ap);
  65. if (ret >= sizeof(stack_buf)) {
  66. // Allocate an extra byte for the null terminator.
  67. char *heap_buf = BH_MALLOC(ret + 1);
  68. buf = heap_buf;
  69. if (heap_buf == NULL) {
  70. errno = ENOMEM;
  71. return -1;
  72. }
  73. ret = vsnprintf(heap_buf, ret + 1, format, ap);
  74. }
  75. if (ret >= 0)
  76. OutputDebugStringA(buf);
  77. if (buf != stack_buf)
  78. BH_FREE(buf);
  79. return ret;
  80. }
  81. #endif