1 /* 2 * Copyright (C) 2023 Huawei Device Co., Ltd. 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 16 #include "exception_controller.h" 17 18 #include <securec.h> 19 #include "hc_mutex.h" 20 21 static volatile bool g_isInit = false; 22 static volatile bool g_isNeedThrowException = false; 23 static uint32_t g_throwExceptionIndex = UINT32_MAX; 24 static uint32_t g_callNum = 0; 25 static HcMutex *g_mutex = NULL; 26 IsNeedThrowException(void)27bool IsNeedThrowException(void) 28 { 29 if (!g_isInit) { 30 return false; 31 } 32 if (!g_isNeedThrowException) { 33 return false; 34 } 35 bool result = (g_callNum == g_throwExceptionIndex); 36 if (result) { 37 printf("throw exception.\n"); 38 } 39 return result; 40 } 41 GetCallNum(void)42uint32_t GetCallNum(void) 43 { 44 if (!g_isInit) { 45 return 0; 46 } 47 if (!g_isNeedThrowException) { 48 return 0; 49 } 50 return g_callNum; 51 } 52 AddCallNum(void)53void AddCallNum(void) 54 { 55 if (!g_isInit) { 56 return; 57 } 58 if (!g_isNeedThrowException) { 59 return; 60 } 61 g_mutex->lock(g_mutex); 62 g_callNum += 1; 63 g_mutex->unlock(g_mutex); 64 } 65 SetControllerMode(bool isNeedThrowException)66void SetControllerMode(bool isNeedThrowException) 67 { 68 if (!g_isInit) { 69 return; 70 } 71 g_isNeedThrowException = isNeedThrowException; 72 } 73 SetThrowExceptionIndex(uint32_t index)74void SetThrowExceptionIndex(uint32_t index) 75 { 76 if (!g_isInit) { 77 return; 78 } 79 if (!g_isNeedThrowException) { 80 return; 81 } 82 g_mutex->lock(g_mutex); 83 g_callNum = 0; 84 g_throwExceptionIndex = index; 85 g_mutex->unlock(g_mutex); 86 } 87 InitExceptionController(void)88void InitExceptionController(void) 89 { 90 if (g_isInit) { 91 return; 92 } 93 g_isInit = true; 94 g_isNeedThrowException = false; 95 g_throwExceptionIndex = UINT32_MAX; 96 g_callNum = 0; 97 g_mutex = (HcMutex *)malloc(sizeof(HcMutex)); 98 InitHcMutex(g_mutex); 99 } 100 DestroyExceptionController(void)101void DestroyExceptionController(void) 102 { 103 if (!g_isInit) { 104 return; 105 } 106 g_isInit = false; 107 g_mutex->lock(g_mutex); 108 g_isNeedThrowException = false; 109 g_throwExceptionIndex = UINT32_MAX; 110 g_callNum = 0; 111 g_mutex->unlock(g_mutex); 112 DestroyHcMutex(g_mutex); 113 free(g_mutex); 114 g_mutex = NULL; 115 }