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 unsigned Stream::GetIndentLevel() const { return m_indent_level; }
189 
190 // Set the current indentation level
191 void Stream::SetIndentLevel(unsigned indent_level) {
192   m_indent_level = indent_level;
193 }
194 
195 // Increment the current indentation level
196 void Stream::IndentMore(unsigned amount) { m_indent_level += amount; }
197 
198 // Decrement the current indentation level
199 void Stream::IndentLess(unsigned amount) {
200   if (m_indent_level >= amount)
201     m_indent_level -= amount;
202   else
203     m_indent_level = 0;
204 }
205 
206 // Get the address size in bytes
207 uint32_t Stream::GetAddressByteSize() const { return m_addr_size; }
208 
209 // Set the address size in bytes
210 void Stream::SetAddressByteSize(uint32_t addr_size) { m_addr_size = addr_size; }
211 
212 // The flags get accessor
213 Flags &Stream::GetFlags() { return m_flags; }
214 
215 // The flags const get accessor
216 const Flags &Stream::GetFlags() const { return m_flags; }
217 
218 // The byte order get accessor
219 
220 lldb::ByteOrder Stream::GetByteOrder() const { return m_byte_order; }
221 
222 size_t Stream::PrintfAsRawHex8(const char *format, ...) {
223   va_list args;
224   va_start(args, format);
225 
226   llvm::SmallString<1024> buf;
227   VASprintf(buf, format, args);
228 
229   ByteDelta delta(*this);
230   for (char C : buf)
231     _PutHex8(C, false);
232 
233   va_end(args);
234 
235   return *delta;
236 }
237 
238 size_t Stream::PutNHex8(size_t n, uint8_t uvalue) {
239   ByteDelta delta(*this);
240   for (size_t i = 0; i < n; ++i)
241     _PutHex8(uvalue, false);
242   return *delta;
243 }
244 
245 void Stream::_PutHex8(uint8_t uvalue, bool add_prefix) {
246   if (m_flags.Test(eBinary)) {
247     Write(&uvalue, 1);
248   } else {
249     if (add_prefix)
250       PutCString("0x");
251 
252     static char g_hex_to_ascii_hex_char[16] = {'0', '1', '2', '3', '4', '5',
253                                                '6', '7', '8', '9', 'a', 'b',
254                                                'c', 'd', 'e', 'f'};
255     char nibble_chars[2];
256     nibble_chars[0] = g_hex_to_ascii_hex_char[(uvalue >> 4) & 0xf];
257     nibble_chars[1] = g_hex_to_ascii_hex_char[(uvalue >> 0) & 0xf];
258     Write(nibble_chars, sizeof(nibble_chars));
259   }
260 }
261 
262 size_t Stream::PutHex8(uint8_t uvalue) {
263   ByteDelta delta(*this);
264   _PutHex8(uvalue, false);
265   return *delta;
266 }
267 
268 size_t Stream::PutHex16(uint16_t uvalue, ByteOrder byte_order) {
269   ByteDelta delta(*this);
270 
271   if (byte_order == eByteOrderInvalid)
272     byte_order = m_byte_order;
273 
274   if (byte_order == eByteOrderLittle) {
275     for (size_t byte = 0; byte < sizeof(uvalue); ++byte)
276       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
277   } else {
278     for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte)
279       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
280   }
281   return *delta;
282 }
283 
284 size_t Stream::PutHex32(uint32_t uvalue, ByteOrder byte_order) {
285   ByteDelta delta(*this);
286 
287   if (byte_order == eByteOrderInvalid)
288     byte_order = m_byte_order;
289 
290   if (byte_order == eByteOrderLittle) {
291     for (size_t byte = 0; byte < sizeof(uvalue); ++byte)
292       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
293   } else {
294     for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte)
295       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
296   }
297   return *delta;
298 }
299 
300 size_t Stream::PutHex64(uint64_t uvalue, ByteOrder byte_order) {
301   ByteDelta delta(*this);
302 
303   if (byte_order == eByteOrderInvalid)
304     byte_order = m_byte_order;
305 
306   if (byte_order == eByteOrderLittle) {
307     for (size_t byte = 0; byte < sizeof(uvalue); ++byte)
308       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
309   } else {
310     for (size_t byte = sizeof(uvalue) - 1; byte < sizeof(uvalue); --byte)
311       _PutHex8(static_cast<uint8_t>(uvalue >> (byte * 8)), false);
312   }
313   return *delta;
314 }
315 
316 size_t Stream::PutMaxHex64(uint64_t uvalue, size_t byte_size,
317                            lldb::ByteOrder byte_order) {
318   switch (byte_size) {
319   case 1:
320     return PutHex8(static_cast<uint8_t>(uvalue));
321   case 2:
322     return PutHex16(static_cast<uint16_t>(uvalue), byte_order);
323   case 4:
324     return PutHex32(static_cast<uint32_t>(uvalue), byte_order);
325   case 8:
326     return PutHex64(uvalue, byte_order);
327   }
328   return 0;
329 }
330 
331 size_t Stream::PutPointer(void *ptr) {
332   return PutRawBytes(&ptr, sizeof(ptr), endian::InlHostByteOrder(),
333                      endian::InlHostByteOrder());
334 }
335 
336 size_t Stream::PutFloat(float f, ByteOrder byte_order) {
337   if (byte_order == eByteOrderInvalid)
338     byte_order = m_byte_order;
339 
340   return PutRawBytes(&f, sizeof(f), endian::InlHostByteOrder(), byte_order);
341 }
342 
343 size_t Stream::PutDouble(double d, ByteOrder byte_order) {
344   if (byte_order == eByteOrderInvalid)
345     byte_order = m_byte_order;
346 
347   return PutRawBytes(&d, sizeof(d), endian::InlHostByteOrder(), byte_order);
348 }
349 
350 size_t Stream::PutLongDouble(long double ld, ByteOrder byte_order) {
351   if (byte_order == eByteOrderInvalid)
352     byte_order = m_byte_order;
353 
354   return PutRawBytes(&ld, sizeof(ld), endian::InlHostByteOrder(), byte_order);
355 }
356 
357 size_t Stream::PutRawBytes(const void *s, size_t src_len,
358                            ByteOrder src_byte_order, ByteOrder dst_byte_order) {
359   ByteDelta delta(*this);
360 
361   if (src_byte_order == eByteOrderInvalid)
362     src_byte_order = m_byte_order;
363 
364   if (dst_byte_order == eByteOrderInvalid)
365     dst_byte_order = m_byte_order;
366 
367   const uint8_t *src = static_cast<const uint8_t *>(s);
368   bool binary_was_set = m_flags.Test(eBinary);
369   if (!binary_was_set)
370     m_flags.Set(eBinary);
371   if (src_byte_order == dst_byte_order) {
372     for (size_t i = 0; i < src_len; ++i)
373       _PutHex8(src[i], false);
374   } else {
375     for (size_t i = src_len - 1; i < src_len; --i)
376       _PutHex8(src[i], false);
377   }
378   if (!binary_was_set)
379     m_flags.Clear(eBinary);
380 
381   return *delta;
382 }
383 
384 size_t Stream::PutBytesAsRawHex8(const void *s, size_t src_len,
385                                  ByteOrder src_byte_order,
386                                  ByteOrder dst_byte_order) {
387   ByteDelta delta(*this);
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 - 1; i < src_len; --i)
402       _PutHex8(src[i], false);
403   }
404   if (binary_is_set)
405     m_flags.Set(eBinary);
406 
407   return *delta;
408 }
409 
410 size_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