LLDB mainline
StringPrinter.cpp
Go to the documentation of this file.
1//===-- StringPrinter.cpp -------------------------------------------------===//
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
10
11#include "lldb/Core/Debugger.h"
13#include "lldb/Target/Process.h"
14#include "lldb/Target/Target.h"
15#include "lldb/Utility/Status.h"
17
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/Support/ConvertUTF.h"
20
21#include <cctype>
22#include <locale>
23#include <memory>
24
25using namespace lldb;
26using namespace lldb_private;
27using namespace lldb_private::formatters;
30
31/// DecodedCharBuffer stores the decoded contents of a single character. It
32/// avoids managing memory on the heap by copying decoded bytes into an in-line
33/// buffer.
35public:
36 DecodedCharBuffer(std::nullptr_t) {}
37
38 DecodedCharBuffer(const uint8_t *bytes, size_t size) : m_size(size) {
39 if (size > MaxLength)
40 llvm_unreachable("unsupported length");
41 memcpy(m_data, bytes, size);
42 }
43
44 DecodedCharBuffer(const char *bytes, size_t size)
45 : DecodedCharBuffer(reinterpret_cast<const uint8_t *>(bytes), size) {}
46
47 const uint8_t *GetBytes() const { return m_data; }
48
49 size_t GetSize() const { return m_size; }
50
51private:
52 static constexpr unsigned MaxLength = 16;
53
54 size_t m_size = 0;
55 uint8_t m_data[MaxLength] = {0};
56};
57
59 std::function<DecodedCharBuffer(uint8_t *, uint8_t *, uint8_t *&)>;
60
61// we define this for all values of type but only implement it for those we
62// care about that's good because we get linker errors for any unsupported type
63template <StringElementType type>
65GetPrintableImpl(uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next,
66 StringPrinter::EscapeStyle escape_style);
67
68// Mimic isprint() for Unicode codepoints.
69static bool isprint32(char32_t codepoint) {
70 if (codepoint <= 0x1F || codepoint == 0x7F) // C0
71 {
72 return false;
73 }
74 if (codepoint >= 0x80 && codepoint <= 0x9F) // C1
75 {
76 return false;
77 }
78 if (codepoint == 0x2028 || codepoint == 0x2029) // line/paragraph separators
79 {
80 return false;
81 }
82 if (codepoint == 0x200E || codepoint == 0x200F ||
83 (codepoint >= 0x202A &&
84 codepoint <= 0x202E)) // bidirectional text control
85 {
86 return false;
87 }
88 if (codepoint >= 0xFFF9 &&
89 codepoint <= 0xFFFF) // interlinears and generally specials
90 {
91 return false;
92 }
93 return true;
94}
95
97 StringPrinter::EscapeStyle escape_style) {
98 const bool is_swift_escape_style =
100 switch (c) {
101 case 0:
102 return {"\\0", 2};
103 case '\a':
104 return {"\\a", 2};
105 case '\b':
106 if (is_swift_escape_style)
107 return nullptr;
108 return {"\\b", 2};
109 case '\f':
110 if (is_swift_escape_style)
111 return nullptr;
112 return {"\\f", 2};
113 case '\n':
114 return {"\\n", 2};
115 case '\r':
116 return {"\\r", 2};
117 case '\t':
118 return {"\\t", 2};
119 case '\v':
120 if (is_swift_escape_style)
121 return nullptr;
122 return {"\\v", 2};
123 case '\"':
124 return {"\\\"", 2};
125 case '\'':
126 if (is_swift_escape_style)
127 return {"\\'", 2};
128 return nullptr;
129 case '\\':
130 return {"\\\\", 2};
131 }
132 return nullptr;
133}
134
135template <>
137 uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next,
138 StringPrinter::EscapeStyle escape_style) {
139 // The ASCII helper always advances 1 byte at a time.
140 next = buffer + 1;
141
142 DecodedCharBuffer retval = attemptASCIIEscape(*buffer, escape_style);
143 if (retval.GetSize())
144 return retval;
145
146 // Use llvm's locale-independent isPrint(char), instead of the libc
147 // implementation which may give different results on different platforms.
148 if (llvm::isPrint(*buffer))
149 return {buffer, 1};
150
151 unsigned escaped_len;
152 constexpr unsigned max_buffer_size = 7;
153 uint8_t data[max_buffer_size];
154 switch (escape_style) {
156 // Prints 4 characters, then a \0 terminator.
157 escaped_len = snprintf((char *)data, max_buffer_size, "\\x%02x", *buffer);
158 break;
160 // Prints up to 6 characters, then a \0 terminator.
161 escaped_len = snprintf((char *)data, max_buffer_size, "\\u{%x}", *buffer);
162 break;
163 }
164 lldbassert(escaped_len > 0 && "unknown string escape style");
165 return {data, escaped_len};
166}
167
168template <>
170 uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next,
171 StringPrinter::EscapeStyle escape_style) {
172 // If the utf8 encoded length is invalid (i.e., not in the closed interval
173 // [1;4]), or if there aren't enough bytes to print, or if the subsequence
174 // isn't valid utf8, fall back to printing an ASCII-escaped subsequence.
175 if (!llvm::isLegalUTF8Sequence(buffer, buffer_end))
176 return GetPrintableImpl<StringElementType::ASCII>(buffer, buffer_end, next,
177 escape_style);
178
179 // Convert the valid utf8 sequence to a utf32 codepoint. This cannot fail.
180 llvm::UTF32 codepoint = 0;
181 const llvm::UTF8 *buffer_for_conversion = buffer;
182 llvm::ConversionResult result = llvm::convertUTF8Sequence(
183 &buffer_for_conversion, buffer_end, &codepoint, llvm::strictConversion);
184 assert(result == llvm::conversionOK &&
185 "Failed to convert legal utf8 sequence");
187
188 // The UTF8 helper always advances by the utf8 encoded length.
189 const unsigned utf8_encoded_len = buffer_for_conversion - buffer;
190 next = buffer + utf8_encoded_len;
191
192 DecodedCharBuffer retval = attemptASCIIEscape(codepoint, escape_style);
193 if (retval.GetSize())
194 return retval;
195 if (isprint32(codepoint))
196 return {buffer, utf8_encoded_len};
197
198 unsigned escaped_len;
199 constexpr unsigned max_buffer_size = 13;
200 uint8_t data[max_buffer_size];
201 switch (escape_style) {
203 // Prints 10 characters, then a \0 terminator.
204 escaped_len = snprintf((char *)data, max_buffer_size, "\\U%08x", codepoint);
205 break;
207 // Prints up to 12 characters, then a \0 terminator.
208 escaped_len = snprintf((char *)data, max_buffer_size, "\\u{%x}", codepoint);
209 break;
210 }
211 lldbassert(escaped_len > 0 && "unknown string escape style");
212 return {data, escaped_len};
213}
214
215// Given a sequence of bytes, this function returns: a sequence of bytes to
216// actually print out + a length the following unscanned position of the buffer
217// is in next
219 uint8_t *buffer_end, uint8_t *&next,
220 StringPrinter::EscapeStyle escape_style) {
221 if (!buffer || buffer >= buffer_end)
222 return {nullptr};
223
224 switch (type) {
225 case StringElementType::ASCII:
226 return GetPrintableImpl<StringElementType::ASCII>(buffer, buffer_end, next,
227 escape_style);
228 case StringElementType::UTF8:
229 return GetPrintableImpl<StringElementType::UTF8>(buffer, buffer_end, next,
230 escape_style);
231 default:
232 return {nullptr};
233 }
234}
235
236static EscapingHelper
238 StringPrinter::EscapeStyle escape_style) {
239 switch (elem_type) {
240 case GetPrintableElementType::UTF8:
241 case GetPrintableElementType::ASCII:
242 return [escape_style, elem_type](uint8_t *buffer, uint8_t *buffer_end,
243 uint8_t *&next) -> DecodedCharBuffer {
244 return GetPrintable(elem_type == GetPrintableElementType::UTF8
245 ? StringElementType::UTF8
246 : StringElementType::ASCII,
247 buffer, buffer_end, next, escape_style);
248 };
249 }
250 llvm_unreachable("bad element type");
251}
252
253/// Read a string encoded in accordance with \tparam SourceDataType from a
254/// host-side LLDB buffer, then pretty-print it to a stream using \p style.
255template <typename SourceDataType>
258 llvm::ConversionResult (*ConvertFunction)(const SourceDataType **,
259 const SourceDataType *,
260 llvm::UTF8 **, llvm::UTF8 *,
261 llvm::ConversionFlags),
263 assert(dump_options.GetStream() && "need a Stream to print the string to");
264 Stream &stream(*dump_options.GetStream());
265 if (dump_options.GetPrefixToken() != nullptr)
266 stream.Printf("%s", dump_options.GetPrefixToken());
267 if (dump_options.GetQuote() != 0)
268 stream.Printf("%c", dump_options.GetQuote());
269 auto data(dump_options.GetData());
270 auto source_size(dump_options.GetSourceSize());
271 if (data.GetByteSize() && data.GetDataStart() && data.GetDataEnd()) {
272 const int bufferSPSize = data.GetByteSize();
273 if (dump_options.GetSourceSize() == 0) {
274 const int origin_encoding = 8 * sizeof(SourceDataType);
275 source_size = bufferSPSize / (origin_encoding / 4);
276 }
277
278 const SourceDataType *data_ptr =
279 (const SourceDataType *)data.GetDataStart();
280 const SourceDataType *data_end_ptr = data_ptr + source_size;
281
282 switch (dump_options.GetZeroTermination()) {
284 break;
285
287 while (data_ptr < data_end_ptr) {
288 if (!*data_ptr) {
289 data_end_ptr = data_ptr;
290 break;
291 }
292 data_ptr++;
293 }
294
295 data_ptr = (const SourceDataType *)data.GetDataStart();
296 } break;
297
299 while (data_end_ptr != data_ptr) {
300 if (*(data_end_ptr - 1))
301 break;
302 data_end_ptr--;
303 }
304 } break;
305 }
306 const bool zero_is_terminator =
307 dump_options.GetZeroTermination() ==
309
310 lldb::WritableDataBufferSP utf8_data_buffer_sp;
311 llvm::UTF8 *utf8_data_ptr = nullptr;
312 llvm::UTF8 *utf8_data_end_ptr = nullptr;
313
314 if (ConvertFunction) {
315 utf8_data_buffer_sp =
316 std::make_shared<DataBufferHeap>(4 * bufferSPSize, 0);
317 utf8_data_ptr = (llvm::UTF8 *)utf8_data_buffer_sp->GetBytes();
318 utf8_data_end_ptr = utf8_data_ptr + utf8_data_buffer_sp->GetByteSize();
319 ConvertFunction(&data_ptr, data_end_ptr, &utf8_data_ptr,
320 utf8_data_end_ptr, llvm::lenientConversion);
321 if (!zero_is_terminator)
322 utf8_data_end_ptr = utf8_data_ptr;
323 // needed because the ConvertFunction will change the value of the
324 // data_ptr.
325 utf8_data_ptr =
326 (llvm::UTF8 *)utf8_data_buffer_sp->GetBytes();
327 } else {
328 // just copy the pointers - the cast is necessary to make the compiler
329 // happy but this should only happen if we are reading UTF8 data
330 utf8_data_ptr = const_cast<llvm::UTF8 *>(
331 reinterpret_cast<const llvm::UTF8 *>(data_ptr));
332 utf8_data_end_ptr = const_cast<llvm::UTF8 *>(
333 reinterpret_cast<const llvm::UTF8 *>(data_end_ptr));
334 }
335
336 const bool escape_non_printables = dump_options.GetEscapeNonPrintables();
337 EscapingHelper escaping_callback;
338 if (escape_non_printables)
339 escaping_callback =
340 GetDefaultEscapingHelper(style, dump_options.GetEscapeStyle());
341
342 // since we tend to accept partial data (and even partially malformed data)
343 // we might end up with no NULL terminator before the end_ptr hence we need
344 // to take a slower route and ensure we stay within boundaries
345 for (; utf8_data_ptr < utf8_data_end_ptr;) {
346 if (zero_is_terminator && !*utf8_data_ptr)
347 break;
348
349 if (escape_non_printables) {
350 uint8_t *next_data = nullptr;
351 auto printable =
352 escaping_callback(utf8_data_ptr, utf8_data_end_ptr, next_data);
353 auto printable_bytes = printable.GetBytes();
354 auto printable_size = printable.GetSize();
355
356 // We failed to figure out how to print this string.
357 if (!printable_bytes || !next_data)
358 return false;
359
360 for (unsigned c = 0; c < printable_size; c++)
361 stream.Printf("%c", *(printable_bytes + c));
362 utf8_data_ptr = (uint8_t *)next_data;
363 } else {
364 stream.Printf("%c", *utf8_data_ptr);
365 utf8_data_ptr++;
366 }
367 }
368 }
369 if (dump_options.GetQuote() != 0)
370 stream.Printf("%c", dump_options.GetQuote());
371 if (dump_options.GetSuffixToken() != nullptr)
372 stream.Printf("%s", dump_options.GetSuffixToken());
373 if (dump_options.GetIsTruncated())
374 stream.Printf("...");
375 return true;
376}
377
384
391
404
405namespace lldb_private {
406
407namespace formatters {
408
409template <typename SourceDataType>
411 StringElementType elem_type,
413 llvm::ConversionResult (*ConvertFunction)(const SourceDataType **,
414 const SourceDataType *,
415 llvm::UTF8 **, llvm::UTF8 *,
416 llvm::ConversionFlags)) {
417 assert(options.GetStream() && "need a Stream to print the string to");
418 if (!options.GetStream())
419 return false;
420
421 if (options.GetLocation() == Address(0) || options.GetLocation() == Address())
422 return false;
423
424 lldb::TargetSP target_sp = options.GetTargetSP();
425 if (!target_sp)
426 return false;
427
428 constexpr int type_width = sizeof(SourceDataType);
429 constexpr int origin_encoding = 8 * type_width;
430 if (origin_encoding != 8 && origin_encoding != 16 && origin_encoding != 32)
431 return false;
432 // If not UTF8 or ASCII, conversion to UTF8 is necessary.
433 if (origin_encoding != 8 && !ConvertFunction)
434 return false;
435
436 bool needs_zero_terminator = options.GetZeroTermination() ==
438
439 bool is_truncated = false;
440 const auto max_size = target_sp->GetMaximumSizeOfStringSummary();
441
442 uint32_t sourceSize;
443 if (elem_type == StringElementType::ASCII && !options.GetSourceSize()) {
444 // FIXME: The NSString formatter sets HasSourceSize(true) when the size is
445 // actually unknown, as well as SetZeroTermination(Ignore). IIUC the
446 // C++ formatter also sets SetZeroTermination(Ignore) when it doesn't
447 // mean to. I don't see how this makes sense: we should fix the formatters.
448 //
449 // Until then, the behavior that's expected for ASCII strings with unknown
450 // lengths is to read up to the max size and then null-terminate. Do that.
451 sourceSize = max_size;
452 needs_zero_terminator = true;
453 } else if (options.HasSourceSize()) {
454 sourceSize = options.GetSourceSize();
455 if (!options.GetIgnoreMaxLength()) {
456 if (sourceSize > max_size) {
457 sourceSize = max_size;
458 is_truncated = true;
459 }
460 }
461 } else {
462 sourceSize = max_size;
463 needs_zero_terminator = true;
464 }
465
466 const int bufferSPSize = sourceSize * type_width;
467 lldb::WritableDataBufferSP buffer_sp(new DataBufferHeap(bufferSPSize, 0));
468
469 // Check if we got bytes. We never get any bytes if we have an empty
470 // string, but we still continue so that we end up actually printing
471 // an empty string ("").
472 if (sourceSize != 0 && !buffer_sp->GetBytes())
473 return false;
474
476 char *buffer = reinterpret_cast<char *>(buffer_sp->GetBytes());
477
478 if (elem_type == StringElementType::ASCII)
479 target_sp->ReadCStringFromMemory(options.GetLocation(), buffer,
480 bufferSPSize, error);
481 else if (needs_zero_terminator)
482 target_sp->ReadStringFromMemory(options.GetLocation(), buffer,
483 bufferSPSize, error, type_width);
484 else
485 target_sp->ReadMemory(options.GetLocation(), buffer, bufferSPSize, error);
486 if (error.Fail()) {
487 options.GetStream()->Printf("unable to read data");
488 return true;
489 }
490
492 dump_options.SetData(
493 DataExtractor(buffer_sp, target_sp->GetArchitecture().GetByteOrder(),
494 target_sp->GetArchitecture().GetAddressByteSize()));
495 dump_options.SetSourceSize(sourceSize);
496 dump_options.SetIsTruncated(is_truncated);
497 if (needs_zero_terminator) {
498 dump_options.SetZeroTermination(
500 }
501
502 GetPrintableElementType print_style = (elem_type == StringElementType::ASCII)
503 ? GetPrintableElementType::ASCII
504 : GetPrintableElementType::UTF8;
505 return DumpEncodedBufferToStream(print_style, ConvertFunction, dump_options);
506}
507
508template <>
510 const ReadStringAndDumpToStreamOptions &options) {
511 return ReadEncodedBufferAndDumpToStream<llvm::UTF8>(StringElementType::UTF8,
512 options, nullptr);
513}
514
515template <>
517 const ReadStringAndDumpToStreamOptions &options) {
519 StringElementType::UTF16, options, llvm::ConvertUTF16toUTF8);
520}
521
522template <>
524 const ReadStringAndDumpToStreamOptions &options) {
526 StringElementType::UTF32, options, llvm::ConvertUTF32toUTF8);
527}
528
529template <>
531 const ReadStringAndDumpToStreamOptions &options) {
532 return ReadEncodedBufferAndDumpToStream<char>(StringElementType::ASCII,
533 options, nullptr);
534}
535
536template <>
538 const ReadBufferAndDumpToStreamOptions &options) {
539 return DumpEncodedBufferToStream<llvm::UTF8>(GetPrintableElementType::UTF8,
540 nullptr, options);
541}
542
543template <>
545 const ReadBufferAndDumpToStreamOptions &options) {
546 return DumpEncodedBufferToStream(GetPrintableElementType::UTF8,
547 llvm::ConvertUTF16toUTF8, options);
548}
549
550template <>
552 const ReadBufferAndDumpToStreamOptions &options) {
553 return DumpEncodedBufferToStream(GetPrintableElementType::UTF8,
554 llvm::ConvertUTF32toUTF8, options);
555}
556
557template <>
559 const ReadBufferAndDumpToStreamOptions &options) {
560 // Treat ASCII the same as UTF8.
561 //
562 // FIXME: This is probably not the right thing to do (well, it's debatable).
563 // If an ASCII-encoded string happens to contain a sequence of invalid bytes
564 // that forms a valid UTF8 character, we'll print out that character. This is
565 // good if you're playing fast and loose with encodings (probably good for
566 // std::string users), but maybe not so good if you care about your string
567 // formatter respecting the semantics of your selected string encoding. In
568 // the latter case you'd want to see the character byte sequence ('\x..'), not
569 // the UTF8 character itself.
571}
572
573} // namespace formatters
574
575} // namespace lldb_private
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
DecodedCharBuffer GetPrintableImpl< StringElementType::ASCII >(uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next, StringPrinter::EscapeStyle escape_style)
std::function< DecodedCharBuffer(uint8_t *, uint8_t *, uint8_t *&)> EscapingHelper
static DecodedCharBuffer GetPrintableImpl(uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next, StringPrinter::EscapeStyle escape_style)
DecodedCharBuffer attemptASCIIEscape(llvm::UTF32 c, StringPrinter::EscapeStyle escape_style)
StringPrinter::GetPrintableElementType GetPrintableElementType
static bool DumpEncodedBufferToStream(GetPrintableElementType style, llvm::ConversionResult(*ConvertFunction)(const SourceDataType **, const SourceDataType *, llvm::UTF8 **, llvm::UTF8 *, llvm::ConversionFlags), const StringPrinter::ReadBufferAndDumpToStreamOptions &dump_options)
Read a string encoded in accordance with.
DecodedCharBuffer GetPrintableImpl< StringElementType::UTF8 >(uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next, StringPrinter::EscapeStyle escape_style)
static bool isprint32(char32_t codepoint)
static DecodedCharBuffer GetPrintable(StringElementType type, uint8_t *buffer, uint8_t *buffer_end, uint8_t *&next, StringPrinter::EscapeStyle escape_style)
StringPrinter::StringElementType StringElementType
static EscapingHelper GetDefaultEscapingHelper(GetPrintableElementType elem_type, StringPrinter::EscapeStyle escape_style)
DecodedCharBuffer stores the decoded contents of a single character.
size_t GetSize() const
DecodedCharBuffer(const uint8_t *bytes, size_t size)
DecodedCharBuffer(const char *bytes, size_t size)
static constexpr unsigned MaxLength
const uint8_t * GetBytes() const
DecodedCharBuffer(std::nullptr_t)
uint8_t m_data[MaxLength]
A section + offset based address class.
Definition Address.h:62
A subclass of DataBuffer that stores a data buffer on the heap.
An data extractor class.
An error handling class.
Definition Status.h:118
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
lldb::TargetSP GetTargetSP() const
static bool ReadBufferAndDumpToStream(const ReadBufferAndDumpToStreamOptions &options)
@ TrimTrailingZeros
Print embedded zeros, but ignore zeros at the end of the buffer.
@ ZeroTerminate
Stop printing at the first zero terminator.
@ Ignore
Don't look for a terminator - print the whole buffer.
static bool ReadStringAndDumpToStream(const ReadStringAndDumpToStreamOptions &options)
#define UNUSED_IF_ASSERT_DISABLED(x)
static bool ReadEncodedBufferAndDumpToStream(StringElementType elem_type, const StringPrinter::ReadStringAndDumpToStreamOptions &options, llvm::ConversionResult(*ConvertFunction)(const SourceDataType **, const SourceDataType *, llvm::UTF8 **, llvm::UTF8 *, llvm::ConversionFlags))
bool StringPrinter::ReadBufferAndDumpToStream< StringElementType::UTF8 >(const ReadBufferAndDumpToStreamOptions &options)
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
std::shared_ptr< lldb_private::Target > TargetSP