1 /* Formatted output to strings.
2 Copyright (C) 1999, 2002, 2006-2021 Free Software Foundation, Inc.
3
4 This file is free software.
5 It is dual-licensed under "the GNU LGPLv3+ or the GNU GPLv2+".
6 You can redistribute it and/or modify it under either
7 - the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 3, or (at your
9 option) any later version, or
10 - the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option)
12 any later version, or
13 - the same dual license "the GNU LGPLv3+ or the GNU GPLv2+".
14
15 This file is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 Lesser General Public License and the GNU General Public License
19 for more details.
20
21 You should have received a copy of the GNU Lesser General Public
22 License and of the GNU General Public License along with this
23 program. If not, see <https://www.gnu.org/licenses/>. */
24
25 #ifndef SIZE_MAX
26 # define SIZE_MAX ((size_t) -1)
27 #endif
28
29 int
30 VSPRINTF (DCHAR_T *buf, const FCHAR_T *format, va_list args)
/* ![[previous]](../icons/n_left.png)
![[next]](../icons/n_right.png)
![[first]](../icons/n_first.png)
![[last]](../icons/n_last.png)
![[top]](../icons/top.png)
![[bottom]](../icons/bottom.png)
![[index]](../icons/index.png)
*/
31 {
32 /* Pass an infinite length. But note that *vasnprintf may fail if the buffer
33 argument is larger than INT_MAX (if that fits into a 'size_t' at all).
34 Also note that glibc's iconv fails with E2BIG when we pass a length that
35 is so large that buf + length wraps around, i.e.
36 (uintptr_t) (buf + length) < (uintptr_t) buf. */
37 size_t length;
38 DCHAR_T *result;
39
40 /* Set length = min (SIZE_MAX, INT_MAX, - (uintptr_t) buf - 1). */
41 length = (SIZE_MAX < INT_MAX ? SIZE_MAX : INT_MAX);
42 if (length > (~ (uintptr_t) buf) / sizeof (DCHAR_T))
43 length = (~ (uintptr_t) buf) / sizeof (DCHAR_T);
44
45 result = VASNPRINTF (buf, &length, format, args);
46 if (result == NULL)
47 return -1;
48
49 /* The infinite buffer size guarantees that the result is not malloc()ed. */
50 if (result != buf)
51 {
52 /* length is near SIZE_MAX. */
53 free (result);
54 errno = EOVERFLOW;
55 return -1;
56 }
57
58 if (length > INT_MAX)
59 {
60 errno = EOVERFLOW;
61 return -1;
62 }
63
64 /* Return the number of resulting units, excluding the trailing NUL. */
65 return length;
66 }