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