1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <cstdarg> // va_start, va_end
10#include <cstddef> // size_t
11#include <cstdlib> // malloc
12#include <cstdio>  // vsprintf, vsnprintf
13#include <cstring> // strcpy, wcsncpy
14#include <cwchar>  // mbstate_t
15
16
17// Like sprintf, but when return value >= 0 it returns
18// a pointer to a malloc'd string in *sptr.
19// If return >= 0, use free to delete *sptr.
20int __libcpp_vasprintf( char **sptr, const char *__restrict format, va_list ap )
21{
22    *sptr = NULL;
23    // Query the count required.
24    va_list ap_copy;
25    va_copy(ap_copy, ap);
26    _LIBCPP_DIAGNOSTIC_PUSH
27    _LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Wformat-nonliteral")
28    int count = vsnprintf( NULL, 0, format, ap_copy );
29    _LIBCPP_DIAGNOSTIC_POP
30    va_end(ap_copy);
31    if (count < 0)
32        return count;
33    size_t buffer_size = static_cast<size_t>(count) + 1;
34    char* p = static_cast<char*>(malloc(buffer_size));
35    if ( ! p )
36        return -1;
37    // If we haven't used exactly what was required, something is wrong.
38    // Maybe bug in vsnprintf. Report the error and return.
39    _LIBCPP_DIAGNOSTIC_PUSH
40    _LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Wformat-nonliteral")
41    if (vsnprintf(p, buffer_size, format, ap) != count) {
42    _LIBCPP_DIAGNOSTIC_POP
43        free(p);
44        return -1;
45    }
46    // All good. This is returning memory to the caller not freeing it.
47    *sptr = p;
48    return count;
49}
50
51// Returns >= 0: the number of wide characters found in the
52// multi byte sequence src (of src_size_bytes), that fit in the buffer dst
53// (of max_dest_chars elements size). The count returned excludes the
54// null terminator. When dst is NULL, no characters are copied
55// and no "out" parameters are updated.
56// Returns (size_t) -1: an incomplete sequence encountered.
57// Leaves *src pointing the next character to convert or NULL
58// if a null character was converted from *src.
59size_t mbsnrtowcs( wchar_t *__restrict dst, const char **__restrict src,
60                   size_t src_size_bytes, size_t max_dest_chars, mbstate_t *__restrict ps )
61{
62    const size_t terminated_sequence = static_cast<size_t>(0);
63    //const size_t invalid_sequence = static_cast<size_t>(-1);
64    const size_t incomplete_sequence = static_cast< size_t>(-2);
65
66    size_t dest_converted = 0;
67    size_t source_converted = 0;
68    size_t source_remaining = src_size_bytes;
69    size_t result = 0;
70    bool have_result = false;
71
72    // If dst is null then max_dest_chars should be ignored according to the
73    // standard.  Setting max_dest_chars to a large value has this effect.
74    if (!dst)
75        max_dest_chars = static_cast<size_t>(-1);
76
77    while ( source_remaining ) {
78        if ( dst && dest_converted >= max_dest_chars )
79            break;
80        // Converts one multi byte character.
81        // if result > 0, it's the size in bytes of that character.
82        // othewise if result is zero it indicates the null character has been found.
83        // otherwise it's an error and errno may be set.
84        size_t char_size = mbrtowc( dst ? dst + dest_converted : NULL, *src + source_converted, source_remaining, ps );
85        // Don't do anything to change errno from here on.
86        if ( char_size > 0 ) {
87            source_remaining -= char_size;
88            source_converted += char_size;
89            ++dest_converted;
90            continue;
91        }
92        result = char_size;
93        have_result = true;
94        break;
95    }
96    if ( dst ) {
97        if ( have_result && result == terminated_sequence )
98            *src = NULL;
99        else
100            *src += source_converted;
101    }
102    if ( have_result && result != terminated_sequence && result != incomplete_sequence )
103        return static_cast<size_t>(-1);
104
105    return dest_converted;
106}
107
108// Converts max_source_chars from the wide character buffer pointer to by *src,
109// into the multi byte character sequence buffer stored at dst which must be
110// dst_size_bytes bytes in size.
111// Returns >= 0: the number of bytes in the sequence
112// converted from *src, excluding the null terminator.
113// Returns size_t(-1) if an error occurs, also sets errno.
114// If dst is NULL dst_size_bytes is ignored and no bytes are copied to dst
115// and no "out" parameters are updated.
116size_t wcsnrtombs( char *__restrict dst, const wchar_t **__restrict src,
117                   size_t max_source_chars, size_t dst_size_bytes, mbstate_t *__restrict ps )
118{
119    //const size_t invalid_sequence = static_cast<size_t>(-1);
120
121    size_t source_converted = 0;
122    size_t dest_converted = 0;
123    size_t dest_remaining = dst_size_bytes;
124    size_t char_size = 0;
125    const errno_t no_error = ( errno_t) 0;
126    errno_t result = ( errno_t ) 0;
127    bool have_result = false;
128    bool terminator_found = false;
129
130    // If dst is null then dst_size_bytes should be ignored according to the
131    // standard.  Setting dest_remaining to a large value has this effect.
132    if (!dst)
133        dest_remaining = static_cast<size_t>(-1);
134
135    while ( source_converted != max_source_chars ) {
136        if ( ! dest_remaining )
137            break;
138        wchar_t c = (*src)[source_converted];
139        if ( dst )
140            result = wcrtomb_s( &char_size, dst + dest_converted, dest_remaining, c, ps);
141        else
142            result = wcrtomb_s( &char_size, NULL, 0, c, ps);
143        // If result is zero there is no error and char_size contains the
144        // size of the multi-byte-sequence converted.
145        // Otherwise result indicates an errno type error.
146        if ( result == no_error ) {
147            if ( c == L'\0' ) {
148                terminator_found = true;
149                break;
150            }
151            ++source_converted;
152            if ( dst )
153                dest_remaining -= char_size;
154            dest_converted += char_size;
155            continue;
156        }
157        have_result = true;
158        break;
159    }
160    if ( dst ) {
161        if ( terminator_found )
162            *src = NULL;
163        else
164            *src = *src + source_converted;
165    }
166    if ( have_result && result != no_error ) {
167        errno = result;
168        return static_cast<size_t>(-1);
169    }
170
171    return dest_converted;
172}
173