ChaosMode.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef mozilla_ChaosMode_h
  6. #define mozilla_ChaosMode_h
  7. #include "mozilla/Atomics.h"
  8. #include "mozilla/EnumSet.h"
  9. #include <stdint.h>
  10. #include <stdlib.h>
  11. namespace mozilla {
  12. enum ChaosFeature {
  13. None = 0x0,
  14. // Altering thread scheduling.
  15. ThreadScheduling = 0x1,
  16. // Altering network request scheduling.
  17. NetworkScheduling = 0x2,
  18. // Altering timer scheduling.
  19. TimerScheduling = 0x4,
  20. // Read and write less-than-requested amounts.
  21. IOAmounts = 0x8,
  22. // Iterate over hash tables in random order.
  23. HashTableIteration = 0x10,
  24. // Randomly refuse to use cached version of image (when allowed by spec).
  25. ImageCache = 0x20,
  26. Any = 0xffffffff,
  27. };
  28. namespace detail {
  29. extern MFBT_DATA Atomic<uint32_t> gChaosModeCounter;
  30. extern MFBT_DATA ChaosFeature gChaosFeatures;
  31. } // namespace detail
  32. /**
  33. * When "chaos mode" is activated, code that makes implicitly nondeterministic
  34. * choices is encouraged to make random and extreme choices, to test more
  35. * code paths and uncover bugs.
  36. */
  37. class ChaosMode
  38. {
  39. public:
  40. static void SetChaosFeature(ChaosFeature aChaosFeature)
  41. {
  42. detail::gChaosFeatures = aChaosFeature;
  43. }
  44. static bool isActive(ChaosFeature aFeature)
  45. {
  46. if (detail::gChaosModeCounter > 0) {
  47. return true;
  48. }
  49. return detail::gChaosFeatures & aFeature;
  50. }
  51. /**
  52. * Increase the chaos mode activation level. An equivalent number of
  53. * calls to leaveChaosMode must be made in order to restore the original
  54. * chaos mode state. If the activation level is nonzero all chaos mode
  55. * features are activated.
  56. */
  57. static void enterChaosMode()
  58. {
  59. detail::gChaosModeCounter++;
  60. }
  61. /**
  62. * Decrease the chaos mode activation level. See enterChaosMode().
  63. */
  64. static void leaveChaosMode()
  65. {
  66. MOZ_ASSERT(detail::gChaosModeCounter > 0);
  67. detail::gChaosModeCounter--;
  68. }
  69. /**
  70. * Returns a somewhat (but not uniformly) random uint32_t < aBound.
  71. * Not to be used for anything except ChaosMode, since it's not very random.
  72. */
  73. static uint32_t randomUint32LessThan(uint32_t aBound)
  74. {
  75. MOZ_ASSERT(aBound != 0);
  76. return uint32_t(rand()) % aBound;
  77. }
  78. };
  79. } /* namespace mozilla */
  80. #endif /* mozilla_ChaosMode_h */