• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * This file is part of the openHiTLS project.
3  *
4  * openHiTLS is licensed under the Mulan PSL v2.
5  * You can use this software according to the terms and conditions of the Mulan PSL v2.
6  * You may obtain a copy of Mulan PSL v2 at:
7  *
8  *     http://license.coscl.org.cn/MulanPSL2
9  *
10  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11  * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12  * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13  * See the Mulan PSL v2 for more details.
14  */
15 #include "hitls_build.h"
16 #ifdef HITLS_BSL_BUFFER
17 #include "securec.h"
18 #include "bsl_sal.h"
19 #include "bsl_buffer.h"
20 
BSL_BufMemNew(void)21 BSL_BufMem *BSL_BufMemNew(void)
22 {
23     BSL_BufMem *ret = NULL;
24 
25     ret = (BSL_BufMem *)BSL_SAL_Malloc(sizeof(BSL_BufMem));
26     if (ret == NULL) {
27         return NULL;
28     }
29 
30     ret->length = 0;
31     ret->max = 0;
32     ret->data = NULL;
33 
34     return ret;
35 }
36 
BSL_BufMemFree(BSL_BufMem * a)37 void BSL_BufMemFree(BSL_BufMem *a)
38 {
39     if (a == NULL) {
40         return;
41     }
42 
43     if (a->data != NULL) {
44         BSL_SAL_FREE(a->data);
45     }
46 
47     BSL_SAL_FREE(a);
48 }
49 
BSL_BufMemGrowClean(BSL_BufMem * str,size_t len)50 size_t BSL_BufMemGrowClean(BSL_BufMem *str, size_t len)
51 {
52     char *ret = NULL;
53     if (str->length >= len) {
54         if (memset_s(&(str->data[len]), str->max - len, 0, str->length - len) != EOK) {
55             return 0;
56         }
57         str->length = len;
58         return len;
59     }
60     if (str->max >= len) {
61         if (memset_s(&(str->data[str->length]), str->max - str->length, 0, len - str->length) != EOK) {
62             return 0;
63         }
64         str->length = len;
65         return len;
66     }
67     const size_t n = ((len + 3) / 3) * 4; // actual growth size
68     if (n < len || n > UINT32_MAX) { // does not meet growth requirements or overflows
69         return 0;
70     }
71     ret = BSL_SAL_Malloc((uint32_t)n);
72     if (ret == NULL) {
73         return 0;
74     }
75     if (str->data != NULL && memcpy_s(ret, n, str->data, str->max) != EOK) {
76         BSL_SAL_FREE(ret);
77         return 0;
78     }
79     if (memset_s(&ret[str->length], n - str->length, 0, len - str->length) != EOK) {
80         BSL_SAL_FREE(ret);
81         return 0;
82     }
83     BSL_SAL_CleanseData(str->data, (uint32_t)str->max);
84     BSL_SAL_FREE(str->data);
85     str->data = ret;
86     str->max = n;
87     str->length = len;
88     return len;
89 }
90 
91 #endif