1 //===-- string_utils.cpp ----------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "string_utils.h"
17 static int appendChar(char **Buffer, const char *BufferEnd, char C) {
18 if (*Buffer < BufferEnd) {
25 // Appends number in a given Base to buffer. If its length is less than
26 // |MinNumberLength|, it is padded with leading zeroes or spaces, depending
27 // on the value of |PadWithZero|.
28 static int appendNumber(char **Buffer, const char *BufferEnd, u64 AbsoluteValue,
29 u8 Base, u8 MinNumberLength, bool PadWithZero,
30 bool Negative, bool Upper) {
31 constexpr uptr MaxLen = 30;
32 RAW_CHECK(Base == 10 || Base == 16);
33 RAW_CHECK(Base == 10 || !Negative);
34 RAW_CHECK(AbsoluteValue || !Negative);
35 RAW_CHECK(MinNumberLength < MaxLen);
37 if (Negative && MinNumberLength)
39 if (Negative && PadWithZero)
40 Res += appendChar(Buffer, BufferEnd, '-');
41 uptr NumBuffer[MaxLen];
44 RAW_CHECK_MSG(static_cast<uptr>(Pos) < MaxLen,
45 "appendNumber buffer overflow");
46 NumBuffer[Pos++] = static_cast<uptr>(AbsoluteValue % Base);
47 AbsoluteValue /= Base;
48 } while (AbsoluteValue > 0);
49 if (Pos < MinNumberLength) {
50 memset(&NumBuffer[Pos], 0,
51 sizeof(NumBuffer[0]) * static_cast<uptr>(MinNumberLength - Pos));
52 Pos = MinNumberLength;
56 for (; Pos >= 0 && NumBuffer[Pos] == 0; Pos--) {
57 char c = (PadWithZero || Pos == 0) ? '0' : ' ';
58 Res += appendChar(Buffer, BufferEnd, c);
60 if (Negative && !PadWithZero)
61 Res += appendChar(Buffer, BufferEnd, '-');
62 for (; Pos >= 0; Pos--) {
63 char Digit = static_cast<char>(NumBuffer[Pos]);
64 Digit = static_cast<char>((Digit < 10) ? '0' + Digit
65 : (Upper ? 'A' : 'a') + Digit - 10);
66 Res += appendChar(Buffer, BufferEnd, Digit);
71 static int appendUnsigned(char **Buffer, const char *BufferEnd, u64 Num,
72 u8 Base, u8 MinNumberLength, bool PadWithZero,
74 return appendNumber(Buffer, BufferEnd, Num, Base, MinNumberLength,
75 PadWithZero, /*Negative=*/false, Upper);
78 static int appendSignedDecimal(char **Buffer, const char *BufferEnd, s64 Num,
79 u8 MinNumberLength, bool PadWithZero) {
80 const bool Negative = (Num < 0);
81 return appendNumber(Buffer, BufferEnd,
82 static_cast<u64>(Negative ? -Num : Num), 10,
83 MinNumberLength, PadWithZero, Negative,
87 // Use the fact that explicitly requesting 0 Width (%0s) results in UB and
88 // interpret Width == 0 as "no Width requested":
89 // Width == 0 - no Width requested
90 // Width < 0 - left-justify S within and pad it to -Width chars, if necessary
91 // Width > 0 - right-justify S, not implemented yet
92 static int appendString(char **Buffer, const char *BufferEnd, int Width,
93 int MaxChars, const char *S) {
98 if (MaxChars >= 0 && Res >= MaxChars)
100 Res += appendChar(Buffer, BufferEnd, *S);
102 // Only the left justified strings are supported.
104 Res += appendChar(Buffer, BufferEnd, ' ');
108 static int appendPointer(char **Buffer, const char *BufferEnd, u64 ptr_value) {
110 Res += appendString(Buffer, BufferEnd, 0, -1, "0x");
111 Res += appendUnsigned(Buffer, BufferEnd, ptr_value, 16,
112 SCUDO_POINTER_FORMAT_LENGTH, /*PadWithZero=*/true,
117 int formatString(char *Buffer, uptr BufferLength, const char *Format,
119 static const char *PrintfFormatsHelp =
120 "Supported formatString formats: %([0-9]*)?(z|ll)?{d,u,x,X}; %p; "
121 "%[-]([0-9]*)?(\\.\\*)?s; %c\n";
123 RAW_CHECK(BufferLength > 0);
124 const char *BufferEnd = &Buffer[BufferLength - 1];
125 const char *Cur = Format;
127 for (; *Cur; Cur++) {
129 Res += appendChar(&Buffer, BufferEnd, *Cur);
133 const bool LeftJustified = *Cur == '-';
136 bool HaveWidth = (*Cur >= '0' && *Cur <= '9');
137 const bool PadWithZero = (*Cur == '0');
140 while (*Cur >= '0' && *Cur <= '9')
141 Width = static_cast<u8>(Width * 10 + *Cur++ - '0');
143 const bool HavePrecision = (Cur[0] == '.' && Cur[1] == '*');
147 Precision = va_arg(Args, int);
149 const bool HaveZ = (*Cur == 'z');
151 const bool HaveLL = !HaveZ && (Cur[0] == 'l' && Cur[1] == 'l');
155 const bool HaveLength = HaveZ || HaveLL;
156 const bool HaveFlags = HaveWidth || HaveLength;
157 // At the moment only %s supports precision and left-justification.
158 CHECK(!((Precision >= 0 || LeftJustified) && *Cur != 's'));
161 DVal = HaveLL ? va_arg(Args, s64)
162 : HaveZ ? va_arg(Args, sptr) : va_arg(Args, int);
163 Res += appendSignedDecimal(&Buffer, BufferEnd, DVal, Width, PadWithZero);
169 UVal = HaveLL ? va_arg(Args, u64)
170 : HaveZ ? va_arg(Args, uptr) : va_arg(Args, unsigned);
171 const bool Upper = (*Cur == 'X');
172 Res += appendUnsigned(&Buffer, BufferEnd, UVal, (*Cur == 'u') ? 10 : 16,
173 Width, PadWithZero, Upper);
177 RAW_CHECK_MSG(!HaveFlags, PrintfFormatsHelp);
178 Res += appendPointer(&Buffer, BufferEnd, va_arg(Args, uptr));
182 RAW_CHECK_MSG(!HaveLength, PrintfFormatsHelp);
183 // Only left-justified Width is supported.
184 CHECK(!HaveWidth || LeftJustified);
185 Res += appendString(&Buffer, BufferEnd, LeftJustified ? -Width : Width,
186 Precision, va_arg(Args, char *));
190 RAW_CHECK_MSG(!HaveFlags, PrintfFormatsHelp);
192 appendChar(&Buffer, BufferEnd, static_cast<char>(va_arg(Args, int)));
196 RAW_CHECK_MSG(!HaveFlags, PrintfFormatsHelp);
197 Res += appendChar(&Buffer, BufferEnd, '%');
201 RAW_CHECK_MSG(false, PrintfFormatsHelp);
205 RAW_CHECK(Buffer <= BufferEnd);
206 appendChar(&Buffer, BufferEnd + 1, '\0');
210 void ScopedString::append(const char *Format, va_list Args) {
211 DCHECK_LT(Length, String.size());
213 va_copy(ArgsCopy, Args);
214 // formatString doesn't currently support a null buffer or zero buffer length,
215 // so in order to get the resulting formatted string length, we use a one-char
218 const uptr AdditionalLength =
219 static_cast<uptr>(formatString(C, sizeof(C), Format, Args)) + 1;
220 String.resize(Length + AdditionalLength);
221 formatString(String.data() + Length, AdditionalLength, Format, ArgsCopy);
222 Length = strlen(String.data());
223 CHECK_LT(Length, String.size());
227 void ScopedString::append(const char *Format, ...) {
229 va_start(Args, Format);
230 append(Format, Args);
235 void Printf(const char *Format, ...) {
237 va_start(Args, Format);
238 ScopedString Msg(1024);
239 Msg.append(Format, Args);
240 outputRaw(Msg.data());