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