1 /**
2 * Copyright 2021-2023 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #ifndef MINDSPORE_CORE_UTILS_MS_UTILS_SECURE_H_
17 #define MINDSPORE_CORE_UTILS_MS_UTILS_SECURE_H_
18
19 #include "securec/include/securec.h"
20 #include "utils/log_adapter.h"
21
22 namespace mindspore {
23 namespace common {
24 // Used to copy huge memory. It is necessary to apply for a large memory length and use the memcpy_s security function
25 // together to ensure the security of data copying.
huge_memcpy(uint8_t * destAddr,size_t destMaxLen,const uint8_t * srcAddr,size_t srcLen)26 static inline errno_t huge_memcpy(uint8_t *destAddr, size_t destMaxLen, const uint8_t *srcAddr, size_t srcLen) {
27 while (destMaxLen > SECUREC_MEM_MAX_LEN && srcLen > SECUREC_MEM_MAX_LEN) {
28 errno_t ret = memcpy_s(destAddr, SECUREC_MEM_MAX_LEN, srcAddr, SECUREC_MEM_MAX_LEN);
29 if (ret != EOK) {
30 return ret;
31 }
32 destAddr += SECUREC_MEM_MAX_LEN;
33 srcAddr += SECUREC_MEM_MAX_LEN;
34 destMaxLen -= SECUREC_MEM_MAX_LEN;
35 srcLen -= SECUREC_MEM_MAX_LEN;
36 }
37 return memcpy_s(destAddr, destMaxLen, srcAddr, srcLen);
38 }
39
40 // Used to initialize huge memory. It is necessary to apply for a large memory length and use the memset_s security
41 // function together to ensure the security of data initialization.
huge_memset(uint8_t * destAddr,size_t destMaxLen,int value,size_t count)42 static inline errno_t huge_memset(uint8_t *destAddr, size_t destMaxLen, int value, size_t count) {
43 while (destMaxLen > SECUREC_MEM_MAX_LEN && count > SECUREC_MEM_MAX_LEN) {
44 errno_t ret = memset_s(destAddr, SECUREC_MEM_MAX_LEN, value, SECUREC_MEM_MAX_LEN);
45 if (ret != EOK) {
46 return ret;
47 }
48 destAddr += SECUREC_MEM_MAX_LEN;
49 destMaxLen -= SECUREC_MEM_MAX_LEN;
50 count -= SECUREC_MEM_MAX_LEN;
51 }
52 return memset_s(destAddr, destMaxLen, value, count);
53 }
54 } // namespace common
55 } // namespace mindspore
56
57 #endif // MINDSPORE_CORE_UTILS_MS_UTILS_SECURE_H_
58