time.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2022-2023 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. OSSL_TIME r;
  15. #if defined(_WIN32) && !defined(OPENSSL_SYS_UEFI)
  16. SYSTEMTIME st;
  17. union {
  18. unsigned __int64 ul;
  19. FILETIME ft;
  20. } now;
  21. GetSystemTime(&st);
  22. SystemTimeToFileTime(&st, &now.ft);
  23. /* re-bias to 1/1/1970 */
  24. # ifdef __MINGW32__
  25. now.ul -= 116444736000000000ULL;
  26. # else
  27. now.ul -= 116444736000000000UI64;
  28. # endif
  29. r.t = ((uint64_t)now.ul) * (OSSL_TIME_SECOND / 10000000);
  30. #else /* defined(_WIN32) */
  31. struct timeval t;
  32. if (gettimeofday(&t, NULL) < 0) {
  33. ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
  34. "calling gettimeofday()");
  35. return ossl_time_zero();
  36. }
  37. if (t.tv_sec <= 0)
  38. r.t = t.tv_usec <= 0 ? 0 : t.tv_usec * OSSL_TIME_US;
  39. else
  40. r.t = ((uint64_t)t.tv_sec * 1000000 + t.tv_usec) * OSSL_TIME_US;
  41. #endif /* defined(_WIN32) */
  42. return r;
  43. }