• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Dawn Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef DAWNNATIVE_ERRORINJECTOR_H_
16 #define DAWNNATIVE_ERRORINJECTOR_H_
17 
18 #include <stdint.h>
19 #include <type_traits>
20 
21 namespace dawn_native {
22 
23     template <typename ErrorType>
24     struct InjectedErrorResult {
25         ErrorType error;
26         bool injected;
27     };
28 
29     bool ErrorInjectorEnabled();
30 
31     bool ShouldInjectError();
32 
33     template <typename ErrorType>
MaybeInjectError(ErrorType errorType)34     InjectedErrorResult<ErrorType> MaybeInjectError(ErrorType errorType) {
35         return InjectedErrorResult<ErrorType>{errorType, ShouldInjectError()};
36     }
37 
38     template <typename ErrorType, typename... ErrorTypes>
MaybeInjectError(ErrorType errorType,ErrorTypes...errorTypes)39     InjectedErrorResult<ErrorType> MaybeInjectError(ErrorType errorType, ErrorTypes... errorTypes) {
40         if (ShouldInjectError()) {
41             return InjectedErrorResult<ErrorType>{errorType, true};
42         }
43         return MaybeInjectError(errorTypes...);
44     }
45 
46 }  // namespace dawn_native
47 
48 #if defined(DAWN_ENABLE_ERROR_INJECTION)
49 
50 #    define INJECT_ERROR_OR_RUN(stmt, ...)                                                   \
51         [&]() {                                                                              \
52             if (DAWN_UNLIKELY(::dawn_native::ErrorInjectorEnabled())) {                      \
53                 /* Only used for testing and fuzzing, so it's okay if this is deoptimized */ \
54                 auto injectedError = ::dawn_native::MaybeInjectError(__VA_ARGS__);           \
55                 if (injectedError.injected) {                                                \
56                     return injectedError.error;                                              \
57                 }                                                                            \
58             }                                                                                \
59             return (stmt);                                                                   \
60         }()
61 
62 #else
63 
64 #    define INJECT_ERROR_OR_RUN(stmt, ...) stmt
65 
66 #endif
67 
68 #endif  // DAWNNATIVE_ERRORINJECTOR_H_
69