• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 "vsnprintf_s_p.h"
17 
18 #include <stdlib.h>
19 #include <string.h>
20 #include <stdio.h>
21 
22 /* Do not malloc in vsnprintf, thus the log api can be called inside signal handler*/
23 #define HILOG_PROHIBIT_ALLOCATION
24 
25 /* Define the max length of the string */
26 #ifndef SECUREC_STRING_MAX_LEN
27 #define SECUREC_STRING_MAX_LEN 0x7fffffffUL
28 #endif
29 
30 #if SECUREC_STRING_MAX_LEN > 0x7fffffffUL
31 #error "max string is 2G"
32 #endif
33 
34 #if defined(_DEBUG) || defined(DEBUG)
35     #if defined(SECUREC_ERROR_HANDLER_BY_ASSERT)
36         #define SECUREC_ERROR_INVALID_PARAMTER(msg) assert( msg "invalid argument" == NULL)
37         #define SECUREC_ERROR_INVALID_RANGE(msg)    assert( msg "invalid dest buffer size" == NULL)
38     #elif defined(SECUREC_ERROR_HANDLER_BY_PRINTF)
39         #if SECUREC_IN_KERNEL
40             #define SECUREC_ERROR_INVALID_PARAMTER(msg) printk( "%s invalid argument\n",msg)
41             #define SECUREC_ERROR_INVALID_RANGE(msg)    printk( "%s invalid dest buffer size\n", msg)
42         #else
43             #define SECUREC_ERROR_INVALID_PARAMTER(msg) printf( "%s invalid argument\n",msg)
44             #define SECUREC_ERROR_INVALID_RANGE(msg)    printf( "%s invalid dest buffer size\n", msg)
45         #endif
46     #elif defined(SECUREC_ERROR_HANDLER_BY_FILE_LOG)
47         #define SECUREC_ERROR_INVALID_PARAMTER(msg) LogSecureCRuntimeError(msg " EINVAL\n")
48         #define SECUREC_ERROR_INVALID_RANGE(msg)    LogSecureCRuntimeError(msg " ERANGE\n")
49     #else
50         #define SECUREC_ERROR_INVALID_PARAMTER(msg) ((void)0)
51         #define SECUREC_ERROR_INVALID_RANGE(msg)    ((void)0)
52     #endif
53 
54 #else
55     #define SECUREC_ERROR_INVALID_PARAMTER(msg) ((void)0)
56     #define SECUREC_ERROR_INVALID_RANGE(msg)    ((void)0)
57     #define SECUREC_ERROR_BUFFER_OVERLAP(msg)   ((void)0)
58 #endif
59 
60 #define SECUREC_PRINTF_TRUNCATE (-2)
61 typedef struct {
62     int count;
63     char *cur;
64 } SecPrintfStream;
65 
66 #ifdef SECUREC_STACK_SIZE_LESS_THAN_1K
67 /* SECUREC_BUFFER_SIZE Can not be less than 23 ,
68  *the length of the octal representation of 64-bit integers with zero lead
69  */
70 #define SECUREC_BUFFER_SIZE    256
71 #else
72 #define SECUREC_BUFFER_SIZE    512
73 #endif
74 #define SECUREC_MAX_PRECISION  SECUREC_BUFFER_SIZE
75 /* max. # bytes in multibyte char  ,see MB_LEN_MAX */
76 #define SECUREC_MB_LEN 16
77 
78 #if (defined(_MSC_VER)) && (_MSC_VER >= 1400)
79 #define SECUREC_MASK_MSVC_CRT_WARNING __pragma(warning(push)) \
80     __pragma(warning(disable:4996 4127))
81 #define SECUREC_END_MASK_MSVC_CRT_WARNING  __pragma(warning(pop))
82 #else
83 #define SECUREC_MASK_MSVC_CRT_WARNING
84 #define SECUREC_END_MASK_MSVC_CRT_WARNING
85 #endif
86 
87 #define SECUREC_WHILE_ZERO SECUREC_MASK_MSVC_CRT_WARNING while (0) SECUREC_END_MASK_MSVC_CRT_WARNING
88 
89 /* flag definitions */
90 /* Using macros instead of enumerations is because some of the enumerated types under the compiler are 16bit. */
91 #define SECUREC_FLAG_SIGN           0x00001U
92 #define SECUREC_FLAG_SIGN_SPACE     0x00002U
93 #define SECUREC_FLAG_LEFT           0x00004U
94 #define SECUREC_FLAG_LEADZERO       0x00008U
95 #define SECUREC_FLAG_LONG           0x00010U
96 #define SECUREC_FLAG_SHORT          0x00020U
97 #define SECUREC_FLAG_SIGNED         0x00040U
98 #define SECUREC_FLAG_ALTERNATE      0x00080U
99 #define SECUREC_FLAG_NEGATIVE       0x00100U
100 #define SECUREC_FLAG_FORCE_OCTAL    0x00200U
101 #define SECUREC_FLAG_LONG_DOUBLE    0x00400U
102 #define SECUREC_FLAG_WIDECHAR       0x00800U
103 #define SECUREC_FLAG_LONGLONG       0x01000U
104 #define SECUREC_FLAG_CHAR           0x02000U
105 #define SECUREC_FLAG_POINTER        0x04000U
106 #define SECUREC_FLAG_I64            0x08000U
107 #define SECUREC_FLAG_PTRDIFF        0x10000U
108 #define SECUREC_FLAG_SIZE           0x20000U
109 #ifdef  SECUREC_COMPATIBLE_LINUX_FORMAT
110 #define SECUREC_FLAG_INTMAX         0x40000U
111 #endif
112 
113 /* put a char to output */
114 #define SECUREC_PUTC(_c,_stream)    ((--(_stream)->count >= 0) ? ((*(_stream)->cur++ = (char)(_c)) & 0xff) : EOF)
115 /* to clear e835 */
116 #define SECUREC_PUTC_ZERO(_stream)    ((--(_stream)->count >= 0) ? ((*(_stream)->cur++ = (char)('\0'))) : EOF)
117 
118 /* state definitions */
119 typedef enum {
120     STAT_NORMAL,
121     STAT_PERCENT,
122     STAT_FLAG,
123     STAT_WIDTH,
124     STAT_DOT,
125     STAT_PRECIS,
126     STAT_SIZE,
127     STAT_TYPE,
128     STAT_INVALID
129 } SecFmtState;
130 
131 #ifndef HILOG_PROHIBIT_ALLOCATION
132 #ifndef SECUREC_MALLOC
133 #define SECUREC_MALLOC(x) __libc_malloc((size_t)(x))
134 #endif
135 
136 #ifndef SECUREC_FREE
137 #define SECUREC_FREE(x)   __libc_free((void *)(x))
138 #endif
139 
140 #else
141 #define SECUREC_MALLOC(x) (NULL)
142 #define SECUREC_FREE(x) {}
143 #endif
144 
145 #if (defined(_WIN32) || defined(_WIN64) || defined(_MSC_VER)) || defined(__ARMCC_VERSION)
146 typedef __int64 SecInt64;
147 typedef unsigned __int64 SecUnsignedInt64;
148 #if defined(__ARMCC_VERSION)
149 typedef int SecInt32;
150 typedef unsigned int SecUnsignedInt32;
151 #else
152 typedef __int32 SecInt32;
153 typedef unsigned __int32 SecUnsignedInt32;
154 #endif
155 #else
156 typedef int SecInt32;
157 typedef unsigned int SecUnsignedInt32;
158 typedef long long SecInt64;
159 typedef unsigned long long SecUnsignedInt64;
160 #endif
161 
SecWriteString(const char * string,int len,SecPrintfStream * f,int * pnumwritten)162 static inline void SecWriteString(const char *string, int len, SecPrintfStream *f, int *pnumwritten)
163 {
164     const char *str = string;
165     int count = len;
166     while (count-- > 0) {
167         if (SECUREC_PUTC(*str, f) == EOF) {
168             *pnumwritten = -1;
169             break;
170         } else {
171             ++(*pnumwritten);
172             ++str;
173         }
174     }
175 }
176 
SecWriteMultiChar(char ch,int num,SecPrintfStream * f,int * pnumwritten)177 static inline void SecWriteMultiChar(char ch, int num, SecPrintfStream *f, int *pnumwritten)
178 {
179     int count = num;
180     while (count-- > 0) {
181         if (SECUREC_PUTC(ch, f) == EOF) {
182             *pnumwritten = -1;
183             break;
184         } else {
185             ++(*pnumwritten);
186         }
187     }
188 }
189 
190 static inline int SecVsnprintfPImpl(char *string, size_t count, int priv, const char *format, va_list arglist);
191 
192 /*******************************************************************************
193  * <FUNCTION DESCRIPTION>
194  *    The vsnprintf_s function is equivalent to the vsnprintf function
195  *     except for the parameter destMax/count and the explicit runtime-constraints violation
196  *    The vsnprintf_s function takes a pointer to an argument list, then formats
197  *    and writes up to count characters of the given data to the memory pointed
198  *    to by strDest and appends a terminating null.
199  *
200  * <INPUT PARAMETERS>
201  *    strDest                  Storage location for the output.
202  *    destMax                The size of the strDest for output.
203  *    count                    Maximum number of character to write(not including
204  *                                the terminating NULL)
205  *    priv_on               whether print <private> for not-public args
206  *    format                   Format-control string.
207  *    arglist                     pointer to list of arguments.
208  *
209  * <OUTPUT PARAMETERS>
210  *    strDest                is updated
211  *
212  * <RETURN VALUE>
213  *    return  the number of characters written, not including the terminating null
214  *    return -1 if an  error occurs.
215  *    return -1 if count < destMax and the output string  has been truncated
216  *
217  * If there is a runtime-constraint violation, strDest[0] will be set to the '\0' when strDest and destMax valid
218  *******************************************************************************
219  */
220  HILOG_LOCAL_API
vsnprintfp_s(char * strDest,size_t destMax,size_t count,int priv,const char * format,va_list arglist)221 int vsnprintfp_s(char *strDest, size_t destMax, size_t count, int priv,  const char *format, va_list arglist)
222 {
223     int retVal;
224 
225     if (format == NULL || strDest == NULL || destMax == 0 || destMax > SECUREC_STRING_MAX_LEN ||
226         (count > (SECUREC_STRING_MAX_LEN - 1) && count != (size_t)-1)) {
227         if (strDest != NULL && destMax > 0) {
228             strDest[0] = '\0';
229         }
230         SECUREC_ERROR_INVALID_PARAMTER("vsnprintfp_s");
231         return -1;
232     }
233 
234     if (destMax > count) {
235         retVal = SecVsnprintfPImpl(strDest, count + 1, priv, format, arglist);
236         if (retVal == SECUREC_PRINTF_TRUNCATE) {  /* lsd add to keep dest buffer not destroyed 2014.2.18 */
237             /* the string has been truncated, return  -1 */
238             return -1;          /* to skip error handler,  return strlen(strDest) or -1 */
239         }
240     } else {                    /* destMax <= count */
241         retVal = SecVsnprintfPImpl(strDest, destMax, priv, format, arglist);
242 #ifdef SECUREC_COMPATIBLE_WIN_FORMAT
243         if (retVal == SECUREC_PRINTF_TRUNCATE && count == (size_t)-1) {
244             return -1;
245         }
246 #endif
247     }
248 
249     if (retVal < 0) {
250         strDest[0] = '\0';      /* empty the dest strDest */
251 
252         if (retVal == SECUREC_PRINTF_TRUNCATE) {
253             /* Buffer too small */
254             SECUREC_ERROR_INVALID_RANGE("vsnprintfp_s");
255         }
256 
257         SECUREC_ERROR_INVALID_PARAMTER("vsnprintfp_s");
258         return -1;
259     }
260 
261     return retVal;
262 }
263 
264 #ifdef SECUREC_FOR_WCHAR
265 #undef SECUREC_FOR_WCHAR
266 #endif
267 
268 typedef char SecChar;
269 #define SECUREC_CHAR(x) x
270 
271 #define SECUREC_WRITE_MULTI_CHAR  SecWriteMultiChar
272 #define SECUREC_WRITE_STRING      SecWriteString
273 #include "output_p.inl"
274 
SecVsnprintfPImpl(char * string,size_t count,int priv,const char * format,va_list arglist)275 static inline int SecVsnprintfPImpl(char *string, size_t count, int priv, const char *format, va_list arglist)
276 {
277     SecPrintfStream str;
278     int retVal;
279 
280     str.count = (int)count;     /* this count include \0 character */
281     str.cur = string;
282 
283     retVal = SecOutputPS(&str, priv, format, arglist);
284     if ((retVal >= 0) && (SECUREC_PUTC_ZERO(&str) != EOF)) {
285         return (retVal);
286     } else if (str.count < 0) {
287         /* the buffer was too small; we return truncation */
288         string[count - 1] = 0;
289         return SECUREC_PRINTF_TRUNCATE;
290     }
291 
292     return -1;
293 }
294