xref: /freebsd-src/contrib/llvm-project/lldb/source/Utility/Stream.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===-- Stream.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 
9 #include "lldb/Utility/Stream.h"
10 
11 #include "lldb/Utility/AnsiTerminal.h"
12 #include "lldb/Utility/Endian.h"
13 #include "lldb/Utility/VASPrintf.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/LEB128.h"
17 #include "llvm/Support/Regex.h"
18 
19 #include <string>
20 
21 #include <cinttypes>
22 #include <cstddef>
23 
24 using namespace lldb;
25 using namespace lldb_private;
26 
27 Stream::Stream(uint32_t flags, uint32_t addr_size, ByteOrder byte_order,
28                bool colors)
29     : m_flags(flags), m_addr_size(addr_size), m_byte_order(byte_order),
30       m_forwarder(*this, colors) {}
31 
32 Stream::Stream(bool colors)
33     : m_flags(0), m_byte_order(endian::InlHostByteOrder()),
34       m_forwarder(*this, colors) {}
35 
36 // Destructor
37 Stream::~Stream() = default;
38 
39 ByteOrder Stream::SetByteOrder(ByteOrder byte_order) {
40   ByteOrder old_byte_order = m_byte_order;
41   m_byte_order = byte_order;
42   return old_byte_order;
43 }
44 
45 // Put an offset "uval" out to the stream using the printf format in "format".
46 void Stream::Offset(uint32_t uval, const char *format) { Printf(format, uval); }
47 
48 // Put an SLEB128 "uval" out to the stream using the printf format in "format".
49 size_t Stream::PutSLEB128(int64_t sval) {
50   if (m_flags.Test(eBinary))
51     return llvm::encodeSLEB128(sval, m_forwarder);
52   else
53     return Printf("0x%" PRIi64, sval);
54 }
55 
56 // Put an ULEB128 "uval" out to the stream using the printf format in "format".
57 size_t Stream::PutULEB128(uint64_t uval) {
58   if (m_flags.Test(eBinary))
59     return llvm::encodeULEB128(uval, m_forwarder);
60   else
61     return Printf("0x%" PRIx64, uval);
62 }
63 
64 // Print a raw NULL terminated C string to the stream.
65 size_t Stream::PutCString(llvm::StringRef str) {
66   size_t bytes_written = 0;
67   bytes_written = Write(str.data(), str.size());
68 
69   // when in binary mode, emit the NULL terminator
70   if (m_flags.Test(eBinary))
71     bytes_written += PutChar('\0');
72   return bytes_written;
73 }
74 
75 void Stream::PutCStringColorHighlighted(llvm::StringRef text,
76                                         llvm::StringRef pattern,
77                                         llvm::StringRef prefix,
78                                         llvm::StringRef suffix) {
79   // Only apply color formatting when a pattern is present and both prefix and
80   // suffix are specified. In the absence of these conditions, output the text
81   // without color formatting.
82   if (pattern.empty() || (prefix.empty() && suffix.empty())) {
83     PutCString(text);
84     return;
85   }
86 
87   llvm::Regex reg_pattern(pattern);
88   llvm::SmallVector<llvm::StringRef, 1> matches;
89   llvm::StringRef remaining = text;
90   std::string format_str = lldb_private::ansi::FormatAnsiTerminalCodes(
91       prefix.str() + "%.*s" + suffix.str());
92   while (reg_pattern.match(remaining, &matches)) {
93     llvm::StringRef match = matches[0];
94     size_t match_start_pos = match.data() - remaining.data();
95     PutCString(remaining.take_front(match_start_pos));
96     Printf(format_str.c_str(), match.size(), match.data());
97     remaining = remaining.drop_front(match_start_pos + match.size());
98   }
99   if (remaining.size())
100     PutCString(remaining);
101 }
102 
103 // Print a double quoted NULL terminated C string to the stream using the
104 // printf format in "format".
105 void Stream::QuotedCString(const char *cstr, const char *format) {
106   Printf(format, cstr);
107 }
108 
109 // Put an address "addr" out to the stream with optional prefix and suffix
110 // strings.
111 void lldb_private::DumpAddress(llvm::raw_ostream &s, uint64_t addr,
112                                uint32_t addr_size, const char *prefix,
113                                const char *suffix) {
114   if (prefix == nullptr)
115     prefix = "";
116   if (suffix == nullptr)
117     suffix = "";
118   s << prefix << llvm::format_hex(addr, 2 + 2 * addr_size) << suffix;
119 }
120 
121 // Put an address range out to the stream with optional prefix and suffix
122 // strings.
123 void lldb_private::DumpAddressRange(llvm::raw_ostream &s, uint64_t lo_addr,
124                                     uint64_t hi_addr, uint32_t addr_size,
125                                     const char *prefix, const char *suffix) {
126   if (prefix && prefix[0])
127     s << prefix;
128   DumpAddress(s, lo_addr, addr_size, "[");
129   DumpAddress(s, hi_addr, addr_size, "-", ")");
130   if (suffix && suffix[0])
131     s << suffix;
132 }
133 
134 size_t Stream::PutChar(char ch) { return Write(&ch, 1); }
135 
136 // Print some formatted output to the stream.
137 size_t Stream::Printf(const char *format, ...) {
138   va_list args;
139   va_start(args, format);
140   size_t result = PrintfVarArg(format, args);
141   va_end(args);
142   return result;
143 }
144 
145 // Print some formatted output to the stream.
146 size_t Stream::PrintfVarArg(const char *format, va_list args) {
147   llvm::SmallString<1024> buf;
148   VASprintf(buf, format, args);
149 
150   // Include the NULL termination byte for binary output
151   size_t length = buf.size();
152   if (m_flags.Test(eBinary))
153     ++length;
154   return Write(buf.c_str(), length);
155 }
156 
157 // Print and End of Line character to the stream
158 size_t Stream::EOL() { return PutChar('\n'); }
159 
160 size_t Stream::Indent(llvm::StringRef str) {
161   const size_t ind_length = PutCString(std::string(m_indent_level, ' '));
162   const size_t str_length = PutCString(str);
163   return ind_length + str_length;
164 }
165 
166 // Stream a character "ch" out to this stream.
167 Stream &Stream::operator<<(char ch) {
168   PutChar(ch);
169   return *this;
170 }
171 
172 // Stream the NULL terminated C string out to this stream.
173 Stream &Stream::operator<<(const char *s) {
174   Printf("%s", s);
175   return *this;
176 }
177 
178 Stream &Stream::operator<<(llvm::StringRef str) {
179   Write(str.data(), str.size());
180   return *this;
181 }
182 
183 // Stream the pointer value out to this stream.
184 Stream &Stream::operator<<(const void *p) {
185   Printf("0x%.*tx", static_cast<int>(sizeof(const void *)) * 2, (ptrdiff_t)p);
186   return *this;
187 }
188 
189 // Get the current indentation level
190 unsigned Stream::GetIndentLevel() const { return m_indent_level; }
191 
192 // Set the current indentation level
193 void Stream::SetIndentLevel(unsigned indent_level) {
194   m_indent_level = indent_level;
195 }
196 
197 // Increment the current indentation level
198 void Stream::IndentMore(unsigned amount) { m_indent_level += amount; }
199 
200 // Decrement the current indentation level
201 void Stream::IndentLess(unsigned amount) {
202   if (m_indent_level >= amount)
203     m_indent_level -= amount;
204   else
205     m_indent_level = 0;
206 }
207 
208 // Get the address size in bytes
209 uint32_t Stream::GetAddressByteSize() const { return m_addr_size; }
210 
211 // Set the address size in bytes
212 void Stream::SetAddressByteSize(uint32_t addr_size) { m_addr_size = addr_size; }
213 
214 // The flags get accessor
215 Flags &Stream::GetFlags() { return m_flags; }
216 
217 // The flags const get accessor
218 const Flags &Stream::GetFlags() const { return m_flags; }
219 
220 // The byte order get accessor
221 
222 lldb::ByteOrder Stream::GetByteOrder() const { return m_byte_order; }
223 
224 size_t Stream::PrintfAsRawHex8(const char *format, ...) {
225   va_list args;
226   va_start(args, format);
227 
228   llvm::SmallString<1024> buf;
229   VASprintf(buf, format, args);
230 
231   ByteDelta delta(*this);
232   for (char C : buf)
233     _PutHex8(C, false);
234 
235   va_end(args);
236 
237   return *delta;
238 }
239 
240 size_t Stream::PutNHex8(size_t n, uint8_t uvalue) {
241   ByteDelta delta(*this);
242   for (size_t i = 0; i < n; ++i)
243     _PutHex8(uvalue, false);
244   return *delta;
245 }
246 
247 void Stream::_PutHex8(uint8_t uvalue, bool add_prefix) {
248   if (m_flags.Test(eBinary)) {
249     Write(&uvalue, 1);
250   } else {
251     if (add_prefix)
252       PutCString("0x");
253 
254     static char g_hex_to_ascii_hex_char[16] = {'0', '1', '2', '3', '4', '5',
255                                                '6', '7', '8', '9', 'a', 'b',
256                                                'c', 'd', 'e', 'f'};
257     char nibble_chars[2];
258     nibble_chars[0] = g_hex_to_ascii_hex_char[(uvalue >> 4) & 0xf];
259     nibble_chars[1] = g_hex_to_ascii_hex_char[(uvalue >> 0) & 0xf];
260     Write(nibble_chars, sizeof(nibble_chars));
261   }
262 }
263 
264 size_t Stream::PutHex8(uint8_t uvalue) {
265   ByteDelta delta(*this);
266   _PutHex8(uvalue, false);
267   return *delta;
268 }
269 
270 size_t Stream::PutHex16(uint16_t uvalue, ByteOrder byte_order) {
271   ByteDelta delta(*this);
272 
273   if (byte_order == eByteOrderInvalid)
274     byte_order = m_byte_order;
275 
276   if (byte_order == eByteOrderLittle) {
277     for (size_t byte = 0; byte < sizeof(uvalue); ++byte)
278       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
279   } else {
280     for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte)
281       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
282   }
283   return *delta;
284 }
285 
286 size_t Stream::PutHex32(uint32_t uvalue, ByteOrder byte_order) {
287   ByteDelta delta(*this);
288 
289   if (byte_order == eByteOrderInvalid)
290     byte_order = m_byte_order;
291 
292   if (byte_order == eByteOrderLittle) {
293     for (size_t byte = 0; byte < sizeof(uvalue); ++byte)
294       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
295   } else {
296     for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte)
297       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
298   }
299   return *delta;
300 }
301 
302 size_t Stream::PutHex64(uint64_t uvalue, ByteOrder byte_order) {
303   ByteDelta delta(*this);
304 
305   if (byte_order == eByteOrderInvalid)
306     byte_order = m_byte_order;
307 
308   if (byte_order == eByteOrderLittle) {
309     for (size_t byte = 0; byte < sizeof(uvalue); ++byte)
310       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
311   } else {
312     for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte)
313       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
314   }
315   return *delta;
316 }
317 
318 size_t Stream::PutMaxHex64(uint64_t uvalue, size_t byte_size,
319                            lldb::ByteOrder byte_order) {
320   switch (byte_size) {
321   case 1:
322     return PutHex8(static_cast<uint8_t>(uvalue));
323   case 2:
324     return PutHex16(static_cast<uint16_t>(uvalue), byte_order);
325   case 4:
326     return PutHex32(static_cast<uint32_t>(uvalue), byte_order);
327   case 8:
328     return PutHex64(uvalue, byte_order);
329   }
330   return 0;
331 }
332 
333 size_t Stream::PutPointer(void *ptr) {
334   return PutRawBytes(&ptr, sizeof(ptr), endian::InlHostByteOrder(),
335                      endian::InlHostByteOrder());
336 }
337 
338 size_t Stream::PutFloat(float f, ByteOrder byte_order) {
339   if (byte_order == eByteOrderInvalid)
340     byte_order = m_byte_order;
341 
342   return PutRawBytes(&f, sizeof(f), endian::InlHostByteOrder(), byte_order);
343 }
344 
345 size_t Stream::PutDouble(double d, ByteOrder byte_order) {
346   if (byte_order == eByteOrderInvalid)
347     byte_order = m_byte_order;
348 
349   return PutRawBytes(&d, sizeof(d), endian::InlHostByteOrder(), byte_order);
350 }
351 
352 size_t Stream::PutLongDouble(long double ld, ByteOrder byte_order) {
353   if (byte_order == eByteOrderInvalid)
354     byte_order = m_byte_order;
355 
356   return PutRawBytes(&ld, sizeof(ld), endian::InlHostByteOrder(), byte_order);
357 }
358 
359 size_t Stream::PutRawBytes(const void *s, size_t src_len,
360                            ByteOrder src_byte_order, ByteOrder dst_byte_order) {
361   ByteDelta delta(*this);
362 
363   if (src_byte_order == eByteOrderInvalid)
364     src_byte_order = m_byte_order;
365 
366   if (dst_byte_order == eByteOrderInvalid)
367     dst_byte_order = m_byte_order;
368 
369   const uint8_t *src = static_cast<const uint8_t *>(s);
370   bool binary_was_set = m_flags.Test(eBinary);
371   if (!binary_was_set)
372     m_flags.Set(eBinary);
373   if (src_byte_order == dst_byte_order) {
374     for (size_t i = 0; i < src_len; ++i)
375       _PutHex8(src[i], false);
376   } else {
377     for (size_t i = src_len; i > 0; --i)
378       _PutHex8(src[i - 1], false);
379   }
380   if (!binary_was_set)
381     m_flags.Clear(eBinary);
382 
383   return *delta;
384 }
385 
386 size_t Stream::PutBytesAsRawHex8(const void *s, size_t src_len,
387                                  ByteOrder src_byte_order,
388                                  ByteOrder dst_byte_order) {
389   ByteDelta delta(*this);
390 
391   if (src_byte_order == eByteOrderInvalid)
392     src_byte_order = m_byte_order;
393 
394   if (dst_byte_order == eByteOrderInvalid)
395     dst_byte_order = m_byte_order;
396 
397   const uint8_t *src = static_cast<const uint8_t *>(s);
398   bool binary_is_set = m_flags.Test(eBinary);
399   m_flags.Clear(eBinary);
400   if (src_byte_order == dst_byte_order) {
401     for (size_t i = 0; i < src_len; ++i)
402       _PutHex8(src[i], false);
403   } else {
404     for (size_t i = src_len; i > 0; --i)
405       _PutHex8(src[i - 1], false);
406   }
407   if (binary_is_set)
408     m_flags.Set(eBinary);
409 
410   return *delta;
411 }
412 
413 size_t Stream::PutStringAsRawHex8(llvm::StringRef s) {
414   ByteDelta delta(*this);
415   bool binary_is_set = m_flags.Test(eBinary);
416   m_flags.Clear(eBinary);
417   for (char c : s)
418     _PutHex8(c, false);
419   if (binary_is_set)
420     m_flags.Set(eBinary);
421   return *delta;
422 }
423