time.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <errno.h>
  10. #include <openssl/err.h>
  11. #include "internal/time.h"
  12. OSSL_TIME ossl_time_now(void)
  13. {
  14. #if defined(_WIN32)
  15. SYSTEMTIME st;
  16. union {
  17. unsigned __int64 ul;
  18. FILETIME ft;
  19. } now;
  20. GetSystemTime(&st);
  21. SystemTimeToFileTime(&st, &now.ft);
  22. /* re-bias to 1/1/1970 */
  23. # ifdef __MINGW32__
  24. now.ul -= 116444736000000000ULL;
  25. # else
  26. now.ul -= 116444736000000000UI64;
  27. # endif
  28. return ((uint64_t)now.ul) * (OSSL_TIME_SECOND / 10000000);
  29. #else
  30. struct timeval t;
  31. if (gettimeofday(&t, NULL) < 0) {
  32. ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
  33. "calling gettimeofday()");
  34. return 0;
  35. }
  36. if (t.tv_sec <= 0)
  37. return t.tv_usec <= 0 ? 0 : t.tv_usec * (OSSL_TIME_SECOND / 1000000);
  38. return ((uint64_t)t.tv_sec * 1000000 + t.tv_usec)
  39. * (OSSL_TIME_SECOND / 1000000);
  40. #endif
  41. }