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