Entropy.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeBasePch.h"
  6. const uint32 Entropy::kInitIterationCount = 3;
  7. void Entropy::BeginAdd()
  8. {
  9. previousValue = u.value;
  10. }
  11. void Entropy::AddCurrentTime()
  12. {
  13. LARGE_INTEGER time = {0};
  14. QueryPerformanceCounter(&time);
  15. if (time.LowPart)
  16. u.value ^= time.LowPart;
  17. }
  18. void Entropy::Add(const char byteValue)
  19. {
  20. if (byteValue)
  21. {
  22. u.array[currentIndex++] ^= byteValue;
  23. currentIndex %= sizeof(unsigned __int32);
  24. }
  25. }
  26. /* public API */
  27. void Entropy::Initialize()
  28. {
  29. for (uint32 times = 0; times < Entropy::kInitIterationCount; times++)
  30. {
  31. AddIoCounters();
  32. AddThreadCycleTime();
  33. }
  34. AddCurrentTime();
  35. }
  36. void Entropy::Add(const char *buffer, size_t size)
  37. {
  38. BeginAdd();
  39. for (size_t index = 0; index < size; index++)
  40. {
  41. Add(buffer[index]);
  42. }
  43. }
  44. void Entropy::AddIoCounters()
  45. {
  46. IO_COUNTERS ioc = {0};
  47. if (GetProcessIoCounters(GetCurrentProcess(), &ioc))
  48. {
  49. Add((char *)&ioc.ReadOperationCount, sizeof(ioc.ReadOperationCount));
  50. Add((char *)&ioc.WriteOperationCount, sizeof(ioc.WriteOperationCount));
  51. Add((char *)&ioc.OtherOperationCount, sizeof(ioc.OtherOperationCount));
  52. Add((char *)&ioc.ReadTransferCount, sizeof(ioc.ReadTransferCount));
  53. Add((char *)&ioc.WriteTransferCount, sizeof(ioc.WriteTransferCount));
  54. Add((char *)&ioc.OtherTransferCount, sizeof(ioc.OtherTransferCount));
  55. }
  56. AddCurrentTime();
  57. }
  58. void Entropy::AddThreadCycleTime()
  59. {
  60. LARGE_INTEGER threadCycleTime = {0};
  61. QueryThreadCycleTime(GetCurrentThread(), (PULONG64)&threadCycleTime);
  62. Add((char *)&threadCycleTime.LowPart, sizeof(threadCycleTime.LowPart));
  63. AddCurrentTime();
  64. }
  65. unsigned __int64 Entropy::GetRand() const
  66. {
  67. return (((unsigned __int64)previousValue) << 32) | u.value;
  68. }