]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Utility/DataExtractor.cpp
Merge ACPICA 20180105.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Utility / DataExtractor.cpp
1 //===-- DataExtractor.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Utility/DataExtractor.h"
11
12 #include "lldb/lldb-defines.h"      // for LLDB_INVALID_ADDRESS
13 #include "lldb/lldb-enumerations.h" // for ByteOrder::eByteOrderBig
14 #include "lldb/lldb-forward.h"      // for DataBufferSP
15 #include "lldb/lldb-types.h"        // for offset_t
16
17 #include "lldb/Utility/DataBuffer.h"
18 #include "lldb/Utility/DataBufferHeap.h"
19 #include "lldb/Utility/Endian.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/Stream.h"
22 #include "lldb/Utility/StreamString.h"
23 #include "lldb/Utility/UUID.h"
24
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/MD5.h"
28 #include "llvm/Support/MathExtras.h"
29
30 #include <algorithm> // for min
31 #include <array>     // for array
32 #include <cassert>
33 #include <cstdint> // for uint8_t, uint32_t, uint64_t
34 #include <string>
35
36 #include <ctype.h>    // for isprint
37 #include <inttypes.h> // for PRIx64, PRId64
38 #include <string.h>   // for memcpy, memset, memchr
39
40 using namespace lldb;
41 using namespace lldb_private;
42
43 static inline uint16_t ReadInt16(const unsigned char *ptr, offset_t offset) {
44   uint16_t value;
45   memcpy(&value, ptr + offset, 2);
46   return value;
47 }
48
49 static inline uint32_t ReadInt32(const unsigned char *ptr,
50                                  offset_t offset = 0) {
51   uint32_t value;
52   memcpy(&value, ptr + offset, 4);
53   return value;
54 }
55
56 static inline uint64_t ReadInt64(const unsigned char *ptr,
57                                  offset_t offset = 0) {
58   uint64_t value;
59   memcpy(&value, ptr + offset, 8);
60   return value;
61 }
62
63 static inline uint16_t ReadInt16(const void *ptr) {
64   uint16_t value;
65   memcpy(&value, ptr, 2);
66   return value;
67 }
68
69 static inline uint16_t ReadSwapInt16(const unsigned char *ptr,
70                                      offset_t offset) {
71   uint16_t value;
72   memcpy(&value, ptr + offset, 2);
73   return llvm::ByteSwap_16(value);
74 }
75
76 static inline uint32_t ReadSwapInt32(const unsigned char *ptr,
77                                      offset_t offset) {
78   uint32_t value;
79   memcpy(&value, ptr + offset, 4);
80   return llvm::ByteSwap_32(value);
81 }
82
83 static inline uint64_t ReadSwapInt64(const unsigned char *ptr,
84                                      offset_t offset) {
85   uint64_t value;
86   memcpy(&value, ptr + offset, 8);
87   return llvm::ByteSwap_64(value);
88 }
89
90 static inline uint16_t ReadSwapInt16(const void *ptr) {
91   uint16_t value;
92   memcpy(&value, ptr, 2);
93   return llvm::ByteSwap_16(value);
94 }
95
96 static inline uint32_t ReadSwapInt32(const void *ptr) {
97   uint32_t value;
98   memcpy(&value, ptr, 4);
99   return llvm::ByteSwap_32(value);
100 }
101
102 static inline uint64_t ReadSwapInt64(const void *ptr) {
103   uint64_t value;
104   memcpy(&value, ptr, 8);
105   return llvm::ByteSwap_64(value);
106 }
107
108 DataExtractor::DataExtractor()
109     : m_start(nullptr), m_end(nullptr),
110       m_byte_order(endian::InlHostByteOrder()), m_addr_size(sizeof(void *)),
111       m_data_sp(), m_target_byte_size(1) {}
112
113 //----------------------------------------------------------------------
114 // This constructor allows us to use data that is owned by someone else.
115 // The data must stay around as long as this object is valid.
116 //----------------------------------------------------------------------
117 DataExtractor::DataExtractor(const void *data, offset_t length,
118                              ByteOrder endian, uint32_t addr_size,
119                              uint32_t target_byte_size /*=1*/)
120     : m_start(const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(data))),
121       m_end(const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(data)) +
122             length),
123       m_byte_order(endian), m_addr_size(addr_size), m_data_sp(),
124       m_target_byte_size(target_byte_size) {
125 #ifdef LLDB_CONFIGURATION_DEBUG
126   assert(addr_size == 4 || addr_size == 8);
127 #endif
128 }
129
130 //----------------------------------------------------------------------
131 // Make a shared pointer reference to the shared data in "data_sp" and
132 // set the endian swapping setting to "swap", and the address size to
133 // "addr_size". The shared data reference will ensure the data lives
134 // as long as any DataExtractor objects exist that have a reference to
135 // this data.
136 //----------------------------------------------------------------------
137 DataExtractor::DataExtractor(const DataBufferSP &data_sp, ByteOrder endian,
138                              uint32_t addr_size,
139                              uint32_t target_byte_size /*=1*/)
140     : m_start(nullptr), m_end(nullptr), m_byte_order(endian),
141       m_addr_size(addr_size), m_data_sp(),
142       m_target_byte_size(target_byte_size) {
143 #ifdef LLDB_CONFIGURATION_DEBUG
144   assert(addr_size == 4 || addr_size == 8);
145 #endif
146   SetData(data_sp);
147 }
148
149 //----------------------------------------------------------------------
150 // Initialize this object with a subset of the data bytes in "data".
151 // If "data" contains shared data, then a reference to this shared
152 // data will added and the shared data will stay around as long
153 // as any object contains a reference to that data. The endian
154 // swap and address size settings are copied from "data".
155 //----------------------------------------------------------------------
156 DataExtractor::DataExtractor(const DataExtractor &data, offset_t offset,
157                              offset_t length, uint32_t target_byte_size /*=1*/)
158     : m_start(nullptr), m_end(nullptr), m_byte_order(data.m_byte_order),
159       m_addr_size(data.m_addr_size), m_data_sp(),
160       m_target_byte_size(target_byte_size) {
161 #ifdef LLDB_CONFIGURATION_DEBUG
162   assert(m_addr_size == 4 || m_addr_size == 8);
163 #endif
164   if (data.ValidOffset(offset)) {
165     offset_t bytes_available = data.GetByteSize() - offset;
166     if (length > bytes_available)
167       length = bytes_available;
168     SetData(data, offset, length);
169   }
170 }
171
172 DataExtractor::DataExtractor(const DataExtractor &rhs)
173     : m_start(rhs.m_start), m_end(rhs.m_end), m_byte_order(rhs.m_byte_order),
174       m_addr_size(rhs.m_addr_size), m_data_sp(rhs.m_data_sp),
175       m_target_byte_size(rhs.m_target_byte_size) {
176 #ifdef LLDB_CONFIGURATION_DEBUG
177   assert(m_addr_size == 4 || m_addr_size == 8);
178 #endif
179 }
180
181 //----------------------------------------------------------------------
182 // Assignment operator
183 //----------------------------------------------------------------------
184 const DataExtractor &DataExtractor::operator=(const DataExtractor &rhs) {
185   if (this != &rhs) {
186     m_start = rhs.m_start;
187     m_end = rhs.m_end;
188     m_byte_order = rhs.m_byte_order;
189     m_addr_size = rhs.m_addr_size;
190     m_data_sp = rhs.m_data_sp;
191   }
192   return *this;
193 }
194
195 DataExtractor::~DataExtractor() = default;
196
197 //------------------------------------------------------------------
198 // Clears the object contents back to a default invalid state, and
199 // release any references to shared data that this object may
200 // contain.
201 //------------------------------------------------------------------
202 void DataExtractor::Clear() {
203   m_start = nullptr;
204   m_end = nullptr;
205   m_byte_order = endian::InlHostByteOrder();
206   m_addr_size = sizeof(void *);
207   m_data_sp.reset();
208 }
209
210 //------------------------------------------------------------------
211 // If this object contains shared data, this function returns the
212 // offset into that shared data. Else zero is returned.
213 //------------------------------------------------------------------
214 size_t DataExtractor::GetSharedDataOffset() const {
215   if (m_start != nullptr) {
216     const DataBuffer *data = m_data_sp.get();
217     if (data != nullptr) {
218       const uint8_t *data_bytes = data->GetBytes();
219       if (data_bytes != nullptr) {
220         assert(m_start >= data_bytes);
221         return m_start - data_bytes;
222       }
223     }
224   }
225   return 0;
226 }
227
228 //----------------------------------------------------------------------
229 // Set the data with which this object will extract from to data
230 // starting at BYTES and set the length of the data to LENGTH bytes
231 // long. The data is externally owned must be around at least as
232 // long as this object points to the data. No copy of the data is
233 // made, this object just refers to this data and can extract from
234 // it. If this object refers to any shared data upon entry, the
235 // reference to that data will be released. Is SWAP is set to true,
236 // any data extracted will be endian swapped.
237 //----------------------------------------------------------------------
238 lldb::offset_t DataExtractor::SetData(const void *bytes, offset_t length,
239                                       ByteOrder endian) {
240   m_byte_order = endian;
241   m_data_sp.reset();
242   if (bytes == nullptr || length == 0) {
243     m_start = nullptr;
244     m_end = nullptr;
245   } else {
246     m_start = const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(bytes));
247     m_end = m_start + length;
248   }
249   return GetByteSize();
250 }
251
252 //----------------------------------------------------------------------
253 // Assign the data for this object to be a subrange in "data"
254 // starting "data_offset" bytes into "data" and ending "data_length"
255 // bytes later. If "data_offset" is not a valid offset into "data",
256 // then this object will contain no bytes. If "data_offset" is
257 // within "data" yet "data_length" is too large, the length will be
258 // capped at the number of bytes remaining in "data". If "data"
259 // contains a shared pointer to other data, then a ref counted
260 // pointer to that data will be made in this object. If "data"
261 // doesn't contain a shared pointer to data, then the bytes referred
262 // to in "data" will need to exist at least as long as this object
263 // refers to those bytes. The address size and endian swap settings
264 // are copied from the current values in "data".
265 //----------------------------------------------------------------------
266 lldb::offset_t DataExtractor::SetData(const DataExtractor &data,
267                                       offset_t data_offset,
268                                       offset_t data_length) {
269   m_addr_size = data.m_addr_size;
270 #ifdef LLDB_CONFIGURATION_DEBUG
271   assert(m_addr_size == 4 || m_addr_size == 8);
272 #endif
273   // If "data" contains shared pointer to data, then we can use that
274   if (data.m_data_sp) {
275     m_byte_order = data.m_byte_order;
276     return SetData(data.m_data_sp, data.GetSharedDataOffset() + data_offset,
277                    data_length);
278   }
279
280   // We have a DataExtractor object that just has a pointer to bytes
281   if (data.ValidOffset(data_offset)) {
282     if (data_length > data.GetByteSize() - data_offset)
283       data_length = data.GetByteSize() - data_offset;
284     return SetData(data.GetDataStart() + data_offset, data_length,
285                    data.GetByteOrder());
286   }
287   return 0;
288 }
289
290 //----------------------------------------------------------------------
291 // Assign the data for this object to be a subrange of the shared
292 // data in "data_sp" starting "data_offset" bytes into "data_sp"
293 // and ending "data_length" bytes later. If "data_offset" is not
294 // a valid offset into "data_sp", then this object will contain no
295 // bytes. If "data_offset" is within "data_sp" yet "data_length" is
296 // too large, the length will be capped at the number of bytes
297 // remaining in "data_sp". A ref counted pointer to the data in
298 // "data_sp" will be made in this object IF the number of bytes this
299 // object refers to in greater than zero (if at least one byte was
300 // available starting at "data_offset") to ensure the data stays
301 // around as long as it is needed. The address size and endian swap
302 // settings will remain unchanged from their current settings.
303 //----------------------------------------------------------------------
304 lldb::offset_t DataExtractor::SetData(const DataBufferSP &data_sp,
305                                       offset_t data_offset,
306                                       offset_t data_length) {
307   m_start = m_end = nullptr;
308
309   if (data_length > 0) {
310     m_data_sp = data_sp;
311     if (data_sp) {
312       const size_t data_size = data_sp->GetByteSize();
313       if (data_offset < data_size) {
314         m_start = data_sp->GetBytes() + data_offset;
315         const size_t bytes_left = data_size - data_offset;
316         // Cap the length of we asked for too many
317         if (data_length <= bytes_left)
318           m_end = m_start + data_length; // We got all the bytes we wanted
319         else
320           m_end = m_start + bytes_left; // Not all the bytes requested were
321                                         // available in the shared data
322       }
323     }
324   }
325
326   size_t new_size = GetByteSize();
327
328   // Don't hold a shared pointer to the data buffer if we don't share
329   // any valid bytes in the shared buffer.
330   if (new_size == 0)
331     m_data_sp.reset();
332
333   return new_size;
334 }
335
336 //----------------------------------------------------------------------
337 // Extract a single unsigned char from the binary data and update
338 // the offset pointed to by "offset_ptr".
339 //
340 // RETURNS the byte that was extracted, or zero on failure.
341 //----------------------------------------------------------------------
342 uint8_t DataExtractor::GetU8(offset_t *offset_ptr) const {
343   const uint8_t *data = (const uint8_t *)GetData(offset_ptr, 1);
344   if (data)
345     return *data;
346   return 0;
347 }
348
349 //----------------------------------------------------------------------
350 // Extract "count" unsigned chars from the binary data and update the
351 // offset pointed to by "offset_ptr". The extracted data is copied into
352 // "dst".
353 //
354 // RETURNS the non-nullptr buffer pointer upon successful extraction of
355 // all the requested bytes, or nullptr when the data is not available in
356 // the buffer due to being out of bounds, or insufficient data.
357 //----------------------------------------------------------------------
358 void *DataExtractor::GetU8(offset_t *offset_ptr, void *dst,
359                            uint32_t count) const {
360   const uint8_t *data = (const uint8_t *)GetData(offset_ptr, count);
361   if (data) {
362     // Copy the data into the buffer
363     memcpy(dst, data, count);
364     // Return a non-nullptr pointer to the converted data as an indicator of
365     // success
366     return dst;
367   }
368   return nullptr;
369 }
370
371 //----------------------------------------------------------------------
372 // Extract a single uint16_t from the data and update the offset
373 // pointed to by "offset_ptr".
374 //
375 // RETURNS the uint16_t that was extracted, or zero on failure.
376 //----------------------------------------------------------------------
377 uint16_t DataExtractor::GetU16(offset_t *offset_ptr) const {
378   uint16_t val = 0;
379   const uint8_t *data = (const uint8_t *)GetData(offset_ptr, sizeof(val));
380   if (data) {
381     if (m_byte_order != endian::InlHostByteOrder())
382       val = ReadSwapInt16(data);
383     else
384       val = ReadInt16(data);
385   }
386   return val;
387 }
388
389 uint16_t DataExtractor::GetU16_unchecked(offset_t *offset_ptr) const {
390   uint16_t val;
391   if (m_byte_order == endian::InlHostByteOrder())
392     val = ReadInt16(m_start, *offset_ptr);
393   else
394     val = ReadSwapInt16(m_start, *offset_ptr);
395   *offset_ptr += sizeof(val);
396   return val;
397 }
398
399 uint32_t DataExtractor::GetU32_unchecked(offset_t *offset_ptr) const {
400   uint32_t val;
401   if (m_byte_order == endian::InlHostByteOrder())
402     val = ReadInt32(m_start, *offset_ptr);
403   else
404     val = ReadSwapInt32(m_start, *offset_ptr);
405   *offset_ptr += sizeof(val);
406   return val;
407 }
408
409 uint64_t DataExtractor::GetU64_unchecked(offset_t *offset_ptr) const {
410   uint64_t val;
411   if (m_byte_order == endian::InlHostByteOrder())
412     val = ReadInt64(m_start, *offset_ptr);
413   else
414     val = ReadSwapInt64(m_start, *offset_ptr);
415   *offset_ptr += sizeof(val);
416   return val;
417 }
418
419 //----------------------------------------------------------------------
420 // Extract "count" uint16_t values from the binary data and update
421 // the offset pointed to by "offset_ptr". The extracted data is
422 // copied into "dst".
423 //
424 // RETURNS the non-nullptr buffer pointer upon successful extraction of
425 // all the requested bytes, or nullptr when the data is not available
426 // in the buffer due to being out of bounds, or insufficient data.
427 //----------------------------------------------------------------------
428 void *DataExtractor::GetU16(offset_t *offset_ptr, void *void_dst,
429                             uint32_t count) const {
430   const size_t src_size = sizeof(uint16_t) * count;
431   const uint16_t *src = (const uint16_t *)GetData(offset_ptr, src_size);
432   if (src) {
433     if (m_byte_order != endian::InlHostByteOrder()) {
434       uint16_t *dst_pos = (uint16_t *)void_dst;
435       uint16_t *dst_end = dst_pos + count;
436       const uint16_t *src_pos = src;
437       while (dst_pos < dst_end) {
438         *dst_pos = ReadSwapInt16(src_pos);
439         ++dst_pos;
440         ++src_pos;
441       }
442     } else {
443       memcpy(void_dst, src, src_size);
444     }
445     // Return a non-nullptr pointer to the converted data as an indicator of
446     // success
447     return void_dst;
448   }
449   return nullptr;
450 }
451
452 //----------------------------------------------------------------------
453 // Extract a single uint32_t from the data and update the offset
454 // pointed to by "offset_ptr".
455 //
456 // RETURNS the uint32_t that was extracted, or zero on failure.
457 //----------------------------------------------------------------------
458 uint32_t DataExtractor::GetU32(offset_t *offset_ptr) const {
459   uint32_t val = 0;
460   const uint8_t *data = (const uint8_t *)GetData(offset_ptr, sizeof(val));
461   if (data) {
462     if (m_byte_order != endian::InlHostByteOrder()) {
463       val = ReadSwapInt32(data);
464     } else {
465       memcpy(&val, data, 4);
466     }
467   }
468   return val;
469 }
470
471 //----------------------------------------------------------------------
472 // Extract "count" uint32_t values from the binary data and update
473 // the offset pointed to by "offset_ptr". The extracted data is
474 // copied into "dst".
475 //
476 // RETURNS the non-nullptr buffer pointer upon successful extraction of
477 // all the requested bytes, or nullptr when the data is not available
478 // in the buffer due to being out of bounds, or insufficient data.
479 //----------------------------------------------------------------------
480 void *DataExtractor::GetU32(offset_t *offset_ptr, void *void_dst,
481                             uint32_t count) const {
482   const size_t src_size = sizeof(uint32_t) * count;
483   const uint32_t *src = (const uint32_t *)GetData(offset_ptr, src_size);
484   if (src) {
485     if (m_byte_order != endian::InlHostByteOrder()) {
486       uint32_t *dst_pos = (uint32_t *)void_dst;
487       uint32_t *dst_end = dst_pos + count;
488       const uint32_t *src_pos = src;
489       while (dst_pos < dst_end) {
490         *dst_pos = ReadSwapInt32(src_pos);
491         ++dst_pos;
492         ++src_pos;
493       }
494     } else {
495       memcpy(void_dst, src, src_size);
496     }
497     // Return a non-nullptr pointer to the converted data as an indicator of
498     // success
499     return void_dst;
500   }
501   return nullptr;
502 }
503
504 //----------------------------------------------------------------------
505 // Extract a single uint64_t from the data and update the offset
506 // pointed to by "offset_ptr".
507 //
508 // RETURNS the uint64_t that was extracted, or zero on failure.
509 //----------------------------------------------------------------------
510 uint64_t DataExtractor::GetU64(offset_t *offset_ptr) const {
511   uint64_t val = 0;
512   const uint8_t *data = (const uint8_t *)GetData(offset_ptr, sizeof(val));
513   if (data) {
514     if (m_byte_order != endian::InlHostByteOrder()) {
515       val = ReadSwapInt64(data);
516     } else {
517       memcpy(&val, data, 8);
518     }
519   }
520   return val;
521 }
522
523 //----------------------------------------------------------------------
524 // GetU64
525 //
526 // Get multiple consecutive 64 bit values. Return true if the entire
527 // read succeeds and increment the offset pointed to by offset_ptr, else
528 // return false and leave the offset pointed to by offset_ptr unchanged.
529 //----------------------------------------------------------------------
530 void *DataExtractor::GetU64(offset_t *offset_ptr, void *void_dst,
531                             uint32_t count) const {
532   const size_t src_size = sizeof(uint64_t) * count;
533   const uint64_t *src = (const uint64_t *)GetData(offset_ptr, src_size);
534   if (src) {
535     if (m_byte_order != endian::InlHostByteOrder()) {
536       uint64_t *dst_pos = (uint64_t *)void_dst;
537       uint64_t *dst_end = dst_pos + count;
538       const uint64_t *src_pos = src;
539       while (dst_pos < dst_end) {
540         *dst_pos = ReadSwapInt64(src_pos);
541         ++dst_pos;
542         ++src_pos;
543       }
544     } else {
545       memcpy(void_dst, src, src_size);
546     }
547     // Return a non-nullptr pointer to the converted data as an indicator of
548     // success
549     return void_dst;
550   }
551   return nullptr;
552 }
553
554 //----------------------------------------------------------------------
555 // Extract a single integer value from the data and update the offset
556 // pointed to by "offset_ptr". The size of the extracted integer
557 // is specified by the "byte_size" argument. "byte_size" should have
558 // a value between 1 and 4 since the return value is only 32 bits
559 // wide. Any "byte_size" values less than 1 or greater than 4 will
560 // result in nothing being extracted, and zero being returned.
561 //
562 // RETURNS the integer value that was extracted, or zero on failure.
563 //----------------------------------------------------------------------
564 uint32_t DataExtractor::GetMaxU32(offset_t *offset_ptr,
565                                   size_t byte_size) const {
566   switch (byte_size) {
567   case 1:
568     return GetU8(offset_ptr);
569     break;
570   case 2:
571     return GetU16(offset_ptr);
572     break;
573   case 4:
574     return GetU32(offset_ptr);
575     break;
576   default:
577     assert(false && "GetMaxU32 unhandled case!");
578     break;
579   }
580   return 0;
581 }
582
583 //----------------------------------------------------------------------
584 // Extract a single integer value from the data and update the offset
585 // pointed to by "offset_ptr". The size of the extracted integer
586 // is specified by the "byte_size" argument. "byte_size" should have
587 // a value >= 1 and <= 8 since the return value is only 64 bits
588 // wide. Any "byte_size" values less than 1 or greater than 8 will
589 // result in nothing being extracted, and zero being returned.
590 //
591 // RETURNS the integer value that was extracted, or zero on failure.
592 //----------------------------------------------------------------------
593 uint64_t DataExtractor::GetMaxU64(offset_t *offset_ptr, size_t size) const {
594   switch (size) {
595   case 1:
596     return GetU8(offset_ptr);
597     break;
598   case 2:
599     return GetU16(offset_ptr);
600     break;
601   case 4:
602     return GetU32(offset_ptr);
603     break;
604   case 8:
605     return GetU64(offset_ptr);
606     break;
607   default:
608     assert(false && "GetMax64 unhandled case!");
609     break;
610   }
611   return 0;
612 }
613
614 uint64_t DataExtractor::GetMaxU64_unchecked(offset_t *offset_ptr,
615                                             size_t size) const {
616   switch (size) {
617   case 1:
618     return GetU8_unchecked(offset_ptr);
619     break;
620   case 2:
621     return GetU16_unchecked(offset_ptr);
622     break;
623   case 4:
624     return GetU32_unchecked(offset_ptr);
625     break;
626   case 8:
627     return GetU64_unchecked(offset_ptr);
628     break;
629   default:
630     assert(false && "GetMax64 unhandled case!");
631     break;
632   }
633   return 0;
634 }
635
636 int64_t DataExtractor::GetMaxS64(offset_t *offset_ptr, size_t size) const {
637   switch (size) {
638   case 1:
639     return (int8_t)GetU8(offset_ptr);
640     break;
641   case 2:
642     return (int16_t)GetU16(offset_ptr);
643     break;
644   case 4:
645     return (int32_t)GetU32(offset_ptr);
646     break;
647   case 8:
648     return (int64_t)GetU64(offset_ptr);
649     break;
650   default:
651     assert(false && "GetMax64 unhandled case!");
652     break;
653   }
654   return 0;
655 }
656
657 uint64_t DataExtractor::GetMaxU64Bitfield(offset_t *offset_ptr, size_t size,
658                                           uint32_t bitfield_bit_size,
659                                           uint32_t bitfield_bit_offset) const {
660   uint64_t uval64 = GetMaxU64(offset_ptr, size);
661   if (bitfield_bit_size > 0) {
662     int32_t lsbcount = bitfield_bit_offset;
663     if (m_byte_order == eByteOrderBig)
664       lsbcount = size * 8 - bitfield_bit_offset - bitfield_bit_size;
665     if (lsbcount > 0)
666       uval64 >>= lsbcount;
667     uint64_t bitfield_mask = ((1ul << bitfield_bit_size) - 1);
668     if (!bitfield_mask && bitfield_bit_offset == 0 && bitfield_bit_size == 64)
669       return uval64;
670     uval64 &= bitfield_mask;
671   }
672   return uval64;
673 }
674
675 int64_t DataExtractor::GetMaxS64Bitfield(offset_t *offset_ptr, size_t size,
676                                          uint32_t bitfield_bit_size,
677                                          uint32_t bitfield_bit_offset) const {
678   int64_t sval64 = GetMaxS64(offset_ptr, size);
679   if (bitfield_bit_size > 0) {
680     int32_t lsbcount = bitfield_bit_offset;
681     if (m_byte_order == eByteOrderBig)
682       lsbcount = size * 8 - bitfield_bit_offset - bitfield_bit_size;
683     if (lsbcount > 0)
684       sval64 >>= lsbcount;
685     uint64_t bitfield_mask = (((uint64_t)1) << bitfield_bit_size) - 1;
686     sval64 &= bitfield_mask;
687     // sign extend if needed
688     if (sval64 & (((uint64_t)1) << (bitfield_bit_size - 1)))
689       sval64 |= ~bitfield_mask;
690   }
691   return sval64;
692 }
693
694 float DataExtractor::GetFloat(offset_t *offset_ptr) const {
695   typedef float float_type;
696   float_type val = 0.0;
697   const size_t src_size = sizeof(float_type);
698   const float_type *src = (const float_type *)GetData(offset_ptr, src_size);
699   if (src) {
700     if (m_byte_order != endian::InlHostByteOrder()) {
701       const uint8_t *src_data = (const uint8_t *)src;
702       uint8_t *dst_data = (uint8_t *)&val;
703       for (size_t i = 0; i < sizeof(float_type); ++i)
704         dst_data[sizeof(float_type) - 1 - i] = src_data[i];
705     } else {
706       val = *src;
707     }
708   }
709   return val;
710 }
711
712 double DataExtractor::GetDouble(offset_t *offset_ptr) const {
713   typedef double float_type;
714   float_type val = 0.0;
715   const size_t src_size = sizeof(float_type);
716   const float_type *src = (const float_type *)GetData(offset_ptr, src_size);
717   if (src) {
718     if (m_byte_order != endian::InlHostByteOrder()) {
719       const uint8_t *src_data = (const uint8_t *)src;
720       uint8_t *dst_data = (uint8_t *)&val;
721       for (size_t i = 0; i < sizeof(float_type); ++i)
722         dst_data[sizeof(float_type) - 1 - i] = src_data[i];
723     } else {
724       val = *src;
725     }
726   }
727   return val;
728 }
729
730 long double DataExtractor::GetLongDouble(offset_t *offset_ptr) const {
731   long double val = 0.0;
732 #if defined(__i386__) || defined(__amd64__) || defined(__x86_64__) ||          \
733     defined(_M_IX86) || defined(_M_IA64) || defined(_M_X64)
734   *offset_ptr += CopyByteOrderedData(*offset_ptr, 10, &val, sizeof(val),
735                                      endian::InlHostByteOrder());
736 #else
737   *offset_ptr += CopyByteOrderedData(*offset_ptr, sizeof(val), &val,
738                                      sizeof(val), endian::InlHostByteOrder());
739 #endif
740   return val;
741 }
742
743 //------------------------------------------------------------------
744 // Extract a single address from the data and update the offset
745 // pointed to by "offset_ptr". The size of the extracted address
746 // comes from the "this->m_addr_size" member variable and should be
747 // set correctly prior to extracting any address values.
748 //
749 // RETURNS the address that was extracted, or zero on failure.
750 //------------------------------------------------------------------
751 uint64_t DataExtractor::GetAddress(offset_t *offset_ptr) const {
752 #ifdef LLDB_CONFIGURATION_DEBUG
753   assert(m_addr_size == 4 || m_addr_size == 8);
754 #endif
755   return GetMaxU64(offset_ptr, m_addr_size);
756 }
757
758 uint64_t DataExtractor::GetAddress_unchecked(offset_t *offset_ptr) const {
759 #ifdef LLDB_CONFIGURATION_DEBUG
760   assert(m_addr_size == 4 || m_addr_size == 8);
761 #endif
762   return GetMaxU64_unchecked(offset_ptr, m_addr_size);
763 }
764
765 //------------------------------------------------------------------
766 // Extract a single pointer from the data and update the offset
767 // pointed to by "offset_ptr". The size of the extracted pointer
768 // comes from the "this->m_addr_size" member variable and should be
769 // set correctly prior to extracting any pointer values.
770 //
771 // RETURNS the pointer that was extracted, or zero on failure.
772 //------------------------------------------------------------------
773 uint64_t DataExtractor::GetPointer(offset_t *offset_ptr) const {
774 #ifdef LLDB_CONFIGURATION_DEBUG
775   assert(m_addr_size == 4 || m_addr_size == 8);
776 #endif
777   return GetMaxU64(offset_ptr, m_addr_size);
778 }
779
780 size_t DataExtractor::ExtractBytes(offset_t offset, offset_t length,
781                                    ByteOrder dst_byte_order, void *dst) const {
782   const uint8_t *src = PeekData(offset, length);
783   if (src) {
784     if (dst_byte_order != GetByteOrder()) {
785       // Validate that only a word- or register-sized dst is byte swapped
786       assert(length == 1 || length == 2 || length == 4 || length == 8 ||
787              length == 10 || length == 16 || length == 32);
788
789       for (uint32_t i = 0; i < length; ++i)
790         ((uint8_t *)dst)[i] = src[length - i - 1];
791     } else
792       ::memcpy(dst, src, length);
793     return length;
794   }
795   return 0;
796 }
797
798 // Extract data as it exists in target memory
799 lldb::offset_t DataExtractor::CopyData(offset_t offset, offset_t length,
800                                        void *dst) const {
801   const uint8_t *src = PeekData(offset, length);
802   if (src) {
803     ::memcpy(dst, src, length);
804     return length;
805   }
806   return 0;
807 }
808
809 // Extract data and swap if needed when doing the copy
810 lldb::offset_t
811 DataExtractor::CopyByteOrderedData(offset_t src_offset, offset_t src_len,
812                                    void *dst_void_ptr, offset_t dst_len,
813                                    ByteOrder dst_byte_order) const {
814   // Validate the source info
815   if (!ValidOffsetForDataOfSize(src_offset, src_len))
816     assert(ValidOffsetForDataOfSize(src_offset, src_len));
817   assert(src_len > 0);
818   assert(m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle);
819
820   // Validate the destination info
821   assert(dst_void_ptr != nullptr);
822   assert(dst_len > 0);
823   assert(dst_byte_order == eByteOrderBig || dst_byte_order == eByteOrderLittle);
824
825   // Validate that only a word- or register-sized dst is byte swapped
826   assert(dst_byte_order == m_byte_order || dst_len == 1 || dst_len == 2 ||
827          dst_len == 4 || dst_len == 8 || dst_len == 10 || dst_len == 16 ||
828          dst_len == 32);
829
830   // Must have valid byte orders set in this object and for destination
831   if (!(dst_byte_order == eByteOrderBig ||
832         dst_byte_order == eByteOrderLittle) ||
833       !(m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle))
834     return 0;
835
836   uint8_t *dst = (uint8_t *)dst_void_ptr;
837   const uint8_t *src = (const uint8_t *)PeekData(src_offset, src_len);
838   if (src) {
839     if (dst_len >= src_len) {
840       // We are copying the entire value from src into dst.
841       // Calculate how many, if any, zeroes we need for the most
842       // significant bytes if "dst_len" is greater than "src_len"...
843       const size_t num_zeroes = dst_len - src_len;
844       if (dst_byte_order == eByteOrderBig) {
845         // Big endian, so we lead with zeroes...
846         if (num_zeroes > 0)
847           ::memset(dst, 0, num_zeroes);
848         // Then either copy or swap the rest
849         if (m_byte_order == eByteOrderBig) {
850           ::memcpy(dst + num_zeroes, src, src_len);
851         } else {
852           for (uint32_t i = 0; i < src_len; ++i)
853             dst[i + num_zeroes] = src[src_len - 1 - i];
854         }
855       } else {
856         // Little endian destination, so we lead the value bytes
857         if (m_byte_order == eByteOrderBig) {
858           for (uint32_t i = 0; i < src_len; ++i)
859             dst[i] = src[src_len - 1 - i];
860         } else {
861           ::memcpy(dst, src, src_len);
862         }
863         // And zero the rest...
864         if (num_zeroes > 0)
865           ::memset(dst + src_len, 0, num_zeroes);
866       }
867       return src_len;
868     } else {
869       // We are only copying some of the value from src into dst..
870
871       if (dst_byte_order == eByteOrderBig) {
872         // Big endian dst
873         if (m_byte_order == eByteOrderBig) {
874           // Big endian dst, with big endian src
875           ::memcpy(dst, src + (src_len - dst_len), dst_len);
876         } else {
877           // Big endian dst, with little endian src
878           for (uint32_t i = 0; i < dst_len; ++i)
879             dst[i] = src[dst_len - 1 - i];
880         }
881       } else {
882         // Little endian dst
883         if (m_byte_order == eByteOrderBig) {
884           // Little endian dst, with big endian src
885           for (uint32_t i = 0; i < dst_len; ++i)
886             dst[i] = src[src_len - 1 - i];
887         } else {
888           // Little endian dst, with big endian src
889           ::memcpy(dst, src, dst_len);
890         }
891       }
892       return dst_len;
893     }
894   }
895   return 0;
896 }
897
898 //----------------------------------------------------------------------
899 // Extracts a variable length NULL terminated C string from
900 // the data at the offset pointed to by "offset_ptr".  The
901 // "offset_ptr" will be updated with the offset of the byte that
902 // follows the NULL terminator byte.
903 //
904 // If the offset pointed to by "offset_ptr" is out of bounds, or if
905 // "length" is non-zero and there aren't enough available
906 // bytes, nullptr will be returned and "offset_ptr" will not be
907 // updated.
908 //----------------------------------------------------------------------
909 const char *DataExtractor::GetCStr(offset_t *offset_ptr) const {
910   const char *cstr = (const char *)PeekData(*offset_ptr, 1);
911   if (cstr) {
912     const char *cstr_end = cstr;
913     const char *end = (const char *)m_end;
914     while (cstr_end < end && *cstr_end)
915       ++cstr_end;
916
917     // Now we are either at the end of the data or we point to the
918     // NULL C string terminator with cstr_end...
919     if (*cstr_end == '\0') {
920       // Advance the offset with one extra byte for the NULL terminator
921       *offset_ptr += (cstr_end - cstr + 1);
922       return cstr;
923     }
924
925     // We reached the end of the data without finding a NULL C string
926     // terminator. Fall through and return nullptr otherwise anyone that
927     // would have used the result as a C string can wander into
928     // unknown memory...
929   }
930   return nullptr;
931 }
932
933 //----------------------------------------------------------------------
934 // Extracts a NULL terminated C string from the fixed length field of
935 // length "len" at the offset pointed to by "offset_ptr".
936 // The "offset_ptr" will be updated with the offset of the byte that
937 // follows the fixed length field.
938 //
939 // If the offset pointed to by "offset_ptr" is out of bounds, or if
940 // the offset plus the length of the field is out of bounds, or if the
941 // field does not contain a NULL terminator byte, nullptr will be returned
942 // and "offset_ptr" will not be updated.
943 //----------------------------------------------------------------------
944 const char *DataExtractor::GetCStr(offset_t *offset_ptr, offset_t len) const {
945   const char *cstr = (const char *)PeekData(*offset_ptr, len);
946   if (cstr != nullptr) {
947     if (memchr(cstr, '\0', len) == nullptr) {
948       return nullptr;
949     }
950     *offset_ptr += len;
951     return cstr;
952   }
953   return nullptr;
954 }
955
956 //------------------------------------------------------------------
957 // Peeks at a string in the contained data. No verification is done
958 // to make sure the entire string lies within the bounds of this
959 // object's data, only "offset" is verified to be a valid offset.
960 //
961 // Returns a valid C string pointer if "offset" is a valid offset in
962 // this object's data, else nullptr is returned.
963 //------------------------------------------------------------------
964 const char *DataExtractor::PeekCStr(offset_t offset) const {
965   return (const char *)PeekData(offset, 1);
966 }
967
968 //----------------------------------------------------------------------
969 // Extracts an unsigned LEB128 number from this object's data
970 // starting at the offset pointed to by "offset_ptr". The offset
971 // pointed to by "offset_ptr" will be updated with the offset of the
972 // byte following the last extracted byte.
973 //
974 // Returned the extracted integer value.
975 //----------------------------------------------------------------------
976 uint64_t DataExtractor::GetULEB128(offset_t *offset_ptr) const {
977   const uint8_t *src = (const uint8_t *)PeekData(*offset_ptr, 1);
978   if (src == nullptr)
979     return 0;
980
981   const uint8_t *end = m_end;
982
983   if (src < end) {
984     uint64_t result = *src++;
985     if (result >= 0x80) {
986       result &= 0x7f;
987       int shift = 7;
988       while (src < end) {
989         uint8_t byte = *src++;
990         result |= (uint64_t)(byte & 0x7f) << shift;
991         if ((byte & 0x80) == 0)
992           break;
993         shift += 7;
994       }
995     }
996     *offset_ptr = src - m_start;
997     return result;
998   }
999
1000   return 0;
1001 }
1002
1003 //----------------------------------------------------------------------
1004 // Extracts an signed LEB128 number from this object's data
1005 // starting at the offset pointed to by "offset_ptr". The offset
1006 // pointed to by "offset_ptr" will be updated with the offset of the
1007 // byte following the last extracted byte.
1008 //
1009 // Returned the extracted integer value.
1010 //----------------------------------------------------------------------
1011 int64_t DataExtractor::GetSLEB128(offset_t *offset_ptr) const {
1012   const uint8_t *src = (const uint8_t *)PeekData(*offset_ptr, 1);
1013   if (src == nullptr)
1014     return 0;
1015
1016   const uint8_t *end = m_end;
1017
1018   if (src < end) {
1019     int64_t result = 0;
1020     int shift = 0;
1021     int size = sizeof(int64_t) * 8;
1022
1023     uint8_t byte = 0;
1024     int bytecount = 0;
1025
1026     while (src < end) {
1027       bytecount++;
1028       byte = *src++;
1029       result |= (int64_t)(byte & 0x7f) << shift;
1030       shift += 7;
1031       if ((byte & 0x80) == 0)
1032         break;
1033     }
1034
1035     // Sign bit of byte is 2nd high order bit (0x40)
1036     if (shift < size && (byte & 0x40))
1037       result |= -(1 << shift);
1038
1039     *offset_ptr += bytecount;
1040     return result;
1041   }
1042   return 0;
1043 }
1044
1045 //----------------------------------------------------------------------
1046 // Skips a ULEB128 number (signed or unsigned) from this object's
1047 // data starting at the offset pointed to by "offset_ptr". The
1048 // offset pointed to by "offset_ptr" will be updated with the offset
1049 // of the byte following the last extracted byte.
1050 //
1051 // Returns the number of bytes consumed during the extraction.
1052 //----------------------------------------------------------------------
1053 uint32_t DataExtractor::Skip_LEB128(offset_t *offset_ptr) const {
1054   uint32_t bytes_consumed = 0;
1055   const uint8_t *src = (const uint8_t *)PeekData(*offset_ptr, 1);
1056   if (src == nullptr)
1057     return 0;
1058
1059   const uint8_t *end = m_end;
1060
1061   if (src < end) {
1062     const uint8_t *src_pos = src;
1063     while ((src_pos < end) && (*src_pos++ & 0x80))
1064       ++bytes_consumed;
1065     *offset_ptr += src_pos - src;
1066   }
1067   return bytes_consumed;
1068 }
1069
1070 //----------------------------------------------------------------------
1071 // Dumps bytes from this object's data to the stream "s" starting
1072 // "start_offset" bytes into this data, and ending with the byte
1073 // before "end_offset". "base_addr" will be added to the offset
1074 // into the dumped data when showing the offset into the data in the
1075 // output information. "num_per_line" objects of type "type" will
1076 // be dumped with the option to override the format for each object
1077 // with "type_format". "type_format" is a printf style formatting
1078 // string. If "type_format" is nullptr, then an appropriate format
1079 // string will be used for the supplied "type". If the stream "s"
1080 // is nullptr, then the output will be send to Log().
1081 //----------------------------------------------------------------------
1082 lldb::offset_t DataExtractor::PutToLog(Log *log, offset_t start_offset,
1083                                        offset_t length, uint64_t base_addr,
1084                                        uint32_t num_per_line,
1085                                        DataExtractor::Type type,
1086                                        const char *format) const {
1087   if (log == nullptr)
1088     return start_offset;
1089
1090   offset_t offset;
1091   offset_t end_offset;
1092   uint32_t count;
1093   StreamString sstr;
1094   for (offset = start_offset, end_offset = offset + length, count = 0;
1095        ValidOffset(offset) && offset < end_offset; ++count) {
1096     if ((count % num_per_line) == 0) {
1097       // Print out any previous string
1098       if (sstr.GetSize() > 0) {
1099         log->PutString(sstr.GetString());
1100         sstr.Clear();
1101       }
1102       // Reset string offset and fill the current line string with address:
1103       if (base_addr != LLDB_INVALID_ADDRESS)
1104         sstr.Printf("0x%8.8" PRIx64 ":",
1105                     (uint64_t)(base_addr + (offset - start_offset)));
1106     }
1107
1108     switch (type) {
1109     case TypeUInt8:
1110       sstr.Printf(format ? format : " %2.2x", GetU8(&offset));
1111       break;
1112     case TypeChar: {
1113       char ch = GetU8(&offset);
1114       sstr.Printf(format ? format : " %c", isprint(ch) ? ch : ' ');
1115     } break;
1116     case TypeUInt16:
1117       sstr.Printf(format ? format : " %4.4x", GetU16(&offset));
1118       break;
1119     case TypeUInt32:
1120       sstr.Printf(format ? format : " %8.8x", GetU32(&offset));
1121       break;
1122     case TypeUInt64:
1123       sstr.Printf(format ? format : " %16.16" PRIx64, GetU64(&offset));
1124       break;
1125     case TypePointer:
1126       sstr.Printf(format ? format : " 0x%" PRIx64, GetAddress(&offset));
1127       break;
1128     case TypeULEB128:
1129       sstr.Printf(format ? format : " 0x%" PRIx64, GetULEB128(&offset));
1130       break;
1131     case TypeSLEB128:
1132       sstr.Printf(format ? format : " %" PRId64, GetSLEB128(&offset));
1133       break;
1134     }
1135   }
1136
1137   if (!sstr.Empty())
1138     log->PutString(sstr.GetString());
1139
1140   return offset; // Return the offset at which we ended up
1141 }
1142
1143 //----------------------------------------------------------------------
1144 // DumpUUID
1145 //
1146 // Dump out a UUID starting at 'offset' bytes into the buffer
1147 //----------------------------------------------------------------------
1148 void DataExtractor::DumpUUID(Stream *s, offset_t offset) const {
1149   if (s) {
1150     const uint8_t *uuid_data = PeekData(offset, 16);
1151     if (uuid_data) {
1152       lldb_private::UUID uuid(uuid_data, 16);
1153       uuid.Dump(s);
1154     } else {
1155       s->Printf("<not enough data for UUID at offset 0x%8.8" PRIx64 ">",
1156                 offset);
1157     }
1158   }
1159 }
1160
1161 size_t DataExtractor::Copy(DataExtractor &dest_data) const {
1162   if (m_data_sp) {
1163     // we can pass along the SP to the data
1164     dest_data.SetData(m_data_sp);
1165   } else {
1166     const uint8_t *base_ptr = m_start;
1167     size_t data_size = GetByteSize();
1168     dest_data.SetData(DataBufferSP(new DataBufferHeap(base_ptr, data_size)));
1169   }
1170   return GetByteSize();
1171 }
1172
1173 bool DataExtractor::Append(DataExtractor &rhs) {
1174   if (rhs.GetByteOrder() != GetByteOrder())
1175     return false;
1176
1177   if (rhs.GetByteSize() == 0)
1178     return true;
1179
1180   if (GetByteSize() == 0)
1181     return (rhs.Copy(*this) > 0);
1182
1183   size_t bytes = GetByteSize() + rhs.GetByteSize();
1184
1185   DataBufferHeap *buffer_heap_ptr = nullptr;
1186   DataBufferSP buffer_sp(buffer_heap_ptr = new DataBufferHeap(bytes, 0));
1187
1188   if (!buffer_sp || buffer_heap_ptr == nullptr)
1189     return false;
1190
1191   uint8_t *bytes_ptr = buffer_heap_ptr->GetBytes();
1192
1193   memcpy(bytes_ptr, GetDataStart(), GetByteSize());
1194   memcpy(bytes_ptr + GetByteSize(), rhs.GetDataStart(), rhs.GetByteSize());
1195
1196   SetData(buffer_sp);
1197
1198   return true;
1199 }
1200
1201 bool DataExtractor::Append(void *buf, offset_t length) {
1202   if (buf == nullptr)
1203     return false;
1204
1205   if (length == 0)
1206     return true;
1207
1208   size_t bytes = GetByteSize() + length;
1209
1210   DataBufferHeap *buffer_heap_ptr = nullptr;
1211   DataBufferSP buffer_sp(buffer_heap_ptr = new DataBufferHeap(bytes, 0));
1212
1213   if (!buffer_sp || buffer_heap_ptr == nullptr)
1214     return false;
1215
1216   uint8_t *bytes_ptr = buffer_heap_ptr->GetBytes();
1217
1218   if (GetByteSize() > 0)
1219     memcpy(bytes_ptr, GetDataStart(), GetByteSize());
1220
1221   memcpy(bytes_ptr + GetByteSize(), buf, length);
1222
1223   SetData(buffer_sp);
1224
1225   return true;
1226 }
1227
1228 void DataExtractor::Checksum(llvm::SmallVectorImpl<uint8_t> &dest,
1229                              uint64_t max_data) {
1230   if (max_data == 0)
1231     max_data = GetByteSize();
1232   else
1233     max_data = std::min(max_data, GetByteSize());
1234
1235   llvm::MD5 md5;
1236
1237   const llvm::ArrayRef<uint8_t> data(GetDataStart(), max_data);
1238   md5.update(data);
1239
1240   llvm::MD5::MD5Result result;
1241   md5.final(result);
1242
1243   dest.clear();
1244   dest.append(result.Bytes.begin(), result.Bytes.end());
1245 }