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