DataExtractor.cpp revision 263363
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 <assert.h>
11#include <stddef.h>
12
13#include <bitset>
14#include <limits>
15#include <sstream>
16#include <string>
17
18#include "clang/AST/ASTContext.h"
19
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/Support/MathExtras.h"
25
26
27#include "lldb/Core/DataBufferHeap.h"
28#include "lldb/Core/DataExtractor.h"
29#include "lldb/Core/DataBuffer.h"
30#include "lldb/Core/Disassembler.h"
31#include "lldb/Core/Log.h"
32#include "lldb/Core/Stream.h"
33#include "lldb/Core/StreamString.h"
34#include "lldb/Core/UUID.h"
35#include "lldb/Core/dwarf.h"
36#include "lldb/Host/Endian.h"
37#include "lldb/Symbol/ClangASTContext.h"
38#include "lldb/Target/ExecutionContext.h"
39#include "lldb/Target/ExecutionContextScope.h"
40#include "lldb/Target/Target.h"
41
42using namespace lldb;
43using namespace lldb_private;
44
45static inline uint16_t
46ReadInt16(const unsigned char* ptr, offset_t offset)
47{
48    return *(uint16_t *)(ptr + offset);
49}
50static inline uint32_t
51ReadInt32 (const unsigned char* ptr, offset_t offset)
52{
53    return *(uint32_t *)(ptr + offset);
54}
55
56static inline uint64_t
57ReadInt64(const unsigned char* ptr, offset_t offset)
58{
59    return *(uint64_t *)(ptr + offset);
60}
61
62static inline uint16_t
63ReadInt16(const void* ptr)
64{
65    return *(uint16_t *)(ptr);
66}
67static inline uint32_t
68ReadInt32 (const void* ptr)
69{
70    return *(uint32_t *)(ptr);
71}
72
73static inline uint64_t
74ReadInt64(const void* ptr)
75{
76    return *(uint64_t *)(ptr);
77}
78
79static inline uint16_t
80ReadSwapInt16(const unsigned char* ptr, offset_t offset)
81{
82    return llvm::ByteSwap_16(*(uint16_t *)(ptr + offset));
83}
84
85static inline uint32_t
86ReadSwapInt32 (const unsigned char* ptr, offset_t offset)
87{
88    return llvm::ByteSwap_32(*(uint32_t *)(ptr + offset));
89}
90static inline uint64_t
91ReadSwapInt64(const unsigned char* ptr, offset_t offset)
92{
93  return llvm::ByteSwap_64(*(uint64_t *)(ptr + offset));
94}
95
96static inline uint16_t
97ReadSwapInt16(const void* ptr)
98{
99    return llvm::ByteSwap_16(*(uint16_t *)(ptr));
100}
101
102static inline uint32_t
103ReadSwapInt32 (const void* ptr)
104{
105    return llvm::ByteSwap_32(*(uint32_t *)(ptr));
106}
107static inline uint64_t
108ReadSwapInt64(const void* ptr)
109{
110    return llvm::ByteSwap_64(*(uint64_t *)(ptr));
111}
112
113#define NON_PRINTABLE_CHAR '.'
114//----------------------------------------------------------------------
115// Default constructor.
116//----------------------------------------------------------------------
117DataExtractor::DataExtractor () :
118    m_start     (NULL),
119    m_end       (NULL),
120    m_byte_order(lldb::endian::InlHostByteOrder()),
121    m_addr_size (4),
122    m_data_sp   ()
123{
124}
125
126//----------------------------------------------------------------------
127// This constructor allows us to use data that is owned by someone else.
128// The data must stay around as long as this object is valid.
129//----------------------------------------------------------------------
130DataExtractor::DataExtractor (const void* data, offset_t length, ByteOrder endian, uint32_t addr_size) :
131    m_start     ((uint8_t*)data),
132    m_end       ((uint8_t*)data + length),
133    m_byte_order(endian),
134    m_addr_size (addr_size),
135    m_data_sp   ()
136{
137}
138
139//----------------------------------------------------------------------
140// Make a shared pointer reference to the shared data in "data_sp" and
141// set the endian swapping setting to "swap", and the address size to
142// "addr_size". The shared data reference will ensure the data lives
143// as long as any DataExtractor objects exist that have a reference to
144// this data.
145//----------------------------------------------------------------------
146DataExtractor::DataExtractor (const DataBufferSP& data_sp, ByteOrder endian, uint32_t addr_size) :
147    m_start     (NULL),
148    m_end       (NULL),
149    m_byte_order(endian),
150    m_addr_size (addr_size),
151    m_data_sp   ()
152{
153    SetData (data_sp);
154}
155
156//----------------------------------------------------------------------
157// Initialize this object with a subset of the data bytes in "data".
158// If "data" contains shared data, then a reference to this shared
159// data will added and the shared data will stay around as long
160// as any object contains a reference to that data. The endian
161// swap and address size settings are copied from "data".
162//----------------------------------------------------------------------
163DataExtractor::DataExtractor (const DataExtractor& data, offset_t offset, offset_t length) :
164    m_start(NULL),
165    m_end(NULL),
166    m_byte_order(data.m_byte_order),
167    m_addr_size(data.m_addr_size),
168    m_data_sp()
169{
170    if (data.ValidOffset(offset))
171    {
172        offset_t bytes_available = data.GetByteSize() - offset;
173        if (length > bytes_available)
174            length = bytes_available;
175        SetData(data, offset, length);
176    }
177}
178
179DataExtractor::DataExtractor (const DataExtractor& rhs) :
180    m_start (rhs.m_start),
181    m_end (rhs.m_end),
182    m_byte_order (rhs.m_byte_order),
183    m_addr_size (rhs.m_addr_size),
184    m_data_sp (rhs.m_data_sp)
185{
186}
187
188//----------------------------------------------------------------------
189// Assignment operator
190//----------------------------------------------------------------------
191const DataExtractor&
192DataExtractor::operator= (const DataExtractor& rhs)
193{
194    if (this != &rhs)
195    {
196        m_start = rhs.m_start;
197        m_end = rhs.m_end;
198        m_byte_order = rhs.m_byte_order;
199        m_addr_size = rhs.m_addr_size;
200        m_data_sp = rhs.m_data_sp;
201    }
202    return *this;
203}
204
205//----------------------------------------------------------------------
206// Destructor
207//----------------------------------------------------------------------
208DataExtractor::~DataExtractor ()
209{
210}
211
212//------------------------------------------------------------------
213// Clears the object contents back to a default invalid state, and
214// release any references to shared data that this object may
215// contain.
216//------------------------------------------------------------------
217void
218DataExtractor::Clear ()
219{
220    m_start = NULL;
221    m_end = NULL;
222    m_byte_order = lldb::endian::InlHostByteOrder();
223    m_addr_size = 4;
224    m_data_sp.reset();
225}
226
227//------------------------------------------------------------------
228// If this object contains shared data, this function returns the
229// offset into that shared data. Else zero is returned.
230//------------------------------------------------------------------
231size_t
232DataExtractor::GetSharedDataOffset () const
233{
234    if (m_start != NULL)
235    {
236        const DataBuffer * data = m_data_sp.get();
237        if (data != NULL)
238        {
239            const uint8_t * data_bytes = data->GetBytes();
240            if (data_bytes != NULL)
241            {
242                assert(m_start >= data_bytes);
243                return m_start - data_bytes;
244            }
245        }
246    }
247    return 0;
248}
249
250//----------------------------------------------------------------------
251// Set the data with which this object will extract from to data
252// starting at BYTES and set the length of the data to LENGTH bytes
253// long. The data is externally owned must be around at least as
254// long as this object points to the data. No copy of the data is
255// made, this object just refers to this data and can extract from
256// it. If this object refers to any shared data upon entry, the
257// reference to that data will be released. Is SWAP is set to true,
258// any data extracted will be endian swapped.
259//----------------------------------------------------------------------
260lldb::offset_t
261DataExtractor::SetData (const void *bytes, offset_t length, ByteOrder endian)
262{
263    m_byte_order = endian;
264    m_data_sp.reset();
265    if (bytes == NULL || length == 0)
266    {
267        m_start = NULL;
268        m_end = NULL;
269    }
270    else
271    {
272        m_start = (uint8_t *)bytes;
273        m_end = m_start + length;
274    }
275    return GetByteSize();
276}
277
278//----------------------------------------------------------------------
279// Assign the data for this object to be a subrange in "data"
280// starting "data_offset" bytes into "data" and ending "data_length"
281// bytes later. If "data_offset" is not a valid offset into "data",
282// then this object will contain no bytes. If "data_offset" is
283// within "data" yet "data_length" is too large, the length will be
284// capped at the number of bytes remaining in "data". If "data"
285// contains a shared pointer to other data, then a ref counted
286// pointer to that data will be made in this object. If "data"
287// doesn't contain a shared pointer to data, then the bytes referred
288// to in "data" will need to exist at least as long as this object
289// refers to those bytes. The address size and endian swap settings
290// are copied from the current values in "data".
291//----------------------------------------------------------------------
292lldb::offset_t
293DataExtractor::SetData (const DataExtractor& data, offset_t data_offset, offset_t data_length)
294{
295    m_addr_size = data.m_addr_size;
296    // If "data" contains shared pointer to data, then we can use that
297    if (data.m_data_sp.get())
298    {
299        m_byte_order = data.m_byte_order;
300        return SetData(data.m_data_sp, data.GetSharedDataOffset() + data_offset, data_length);
301    }
302
303    // We have a DataExtractor object that just has a pointer to bytes
304    if (data.ValidOffset(data_offset))
305    {
306        if (data_length > data.GetByteSize() - data_offset)
307            data_length = data.GetByteSize() - data_offset;
308        return SetData (data.GetDataStart() + data_offset, data_length, data.GetByteOrder());
309    }
310    return 0;
311}
312
313//----------------------------------------------------------------------
314// Assign the data for this object to be a subrange of the shared
315// data in "data_sp" starting "data_offset" bytes into "data_sp"
316// and ending "data_length" bytes later. If "data_offset" is not
317// a valid offset into "data_sp", then this object will contain no
318// bytes. If "data_offset" is within "data_sp" yet "data_length" is
319// too large, the length will be capped at the number of bytes
320// remaining in "data_sp". A ref counted pointer to the data in
321// "data_sp" will be made in this object IF the number of bytes this
322// object refers to in greater than zero (if at least one byte was
323// available starting at "data_offset") to ensure the data stays
324// around as long as it is needed. The address size and endian swap
325// settings will remain unchanged from their current settings.
326//----------------------------------------------------------------------
327lldb::offset_t
328DataExtractor::SetData (const DataBufferSP& data_sp, offset_t data_offset, offset_t data_length)
329{
330    m_start = m_end = NULL;
331
332    if (data_length > 0)
333    {
334        m_data_sp = data_sp;
335        if (data_sp.get())
336        {
337            const size_t data_size = data_sp->GetByteSize();
338            if (data_offset < data_size)
339            {
340                m_start = data_sp->GetBytes() + data_offset;
341                const size_t bytes_left = data_size - data_offset;
342                // Cap the length of we asked for too many
343                if (data_length <= bytes_left)
344                    m_end = m_start + data_length;  // We got all the bytes we wanted
345                else
346                    m_end = m_start + bytes_left;   // Not all the bytes requested were available in the shared data
347            }
348        }
349    }
350
351    size_t new_size = GetByteSize();
352
353    // Don't hold a shared pointer to the data buffer if we don't share
354    // any valid bytes in the shared buffer.
355    if (new_size == 0)
356        m_data_sp.reset();
357
358    return new_size;
359}
360
361//----------------------------------------------------------------------
362// Extract a single unsigned char from the binary data and update
363// the offset pointed to by "offset_ptr".
364//
365// RETURNS the byte that was extracted, or zero on failure.
366//----------------------------------------------------------------------
367uint8_t
368DataExtractor::GetU8 (offset_t *offset_ptr) const
369{
370    const uint8_t *data = (const uint8_t *)GetData (offset_ptr, 1);
371    if (data)
372        return *data;
373    return 0;
374}
375
376//----------------------------------------------------------------------
377// Extract "count" unsigned chars from the binary data and update the
378// offset pointed to by "offset_ptr". The extracted data is copied into
379// "dst".
380//
381// RETURNS the non-NULL buffer pointer upon successful extraction of
382// all the requested bytes, or NULL when the data is not available in
383// the buffer due to being out of bounds, or unsufficient data.
384//----------------------------------------------------------------------
385void *
386DataExtractor::GetU8 (offset_t *offset_ptr, void *dst, uint32_t count) const
387{
388    const uint8_t *data = (const uint8_t *)GetData (offset_ptr, count);
389    if (data)
390    {
391        // Copy the data into the buffer
392        memcpy (dst, data, count);
393        // Return a non-NULL pointer to the converted data as an indicator of success
394        return dst;
395    }
396    return NULL;
397}
398
399//----------------------------------------------------------------------
400// Extract a single uint16_t from the data and update the offset
401// pointed to by "offset_ptr".
402//
403// RETURNS the uint16_t that was extracted, or zero on failure.
404//----------------------------------------------------------------------
405uint16_t
406DataExtractor::GetU16 (offset_t *offset_ptr) const
407{
408    uint16_t val = 0;
409    const uint8_t *data = (const uint8_t *)GetData (offset_ptr, sizeof(val));
410    if (data)
411    {
412        if (m_byte_order != lldb::endian::InlHostByteOrder())
413            val = ReadSwapInt16(data);
414        else
415            val = ReadInt16 (data);
416    }
417    return val;
418}
419
420uint16_t
421DataExtractor::GetU16_unchecked (offset_t *offset_ptr) const
422{
423    uint16_t val;
424    if (m_byte_order == lldb::endian::InlHostByteOrder())
425        val = ReadInt16 (m_start, *offset_ptr);
426    else
427        val = ReadSwapInt16(m_start, *offset_ptr);
428    *offset_ptr += sizeof(val);
429    return val;
430}
431
432uint32_t
433DataExtractor::GetU32_unchecked (offset_t *offset_ptr) const
434{
435    uint32_t val;
436    if (m_byte_order == lldb::endian::InlHostByteOrder())
437        val = ReadInt32 (m_start, *offset_ptr);
438    else
439        val =  ReadSwapInt32 (m_start, *offset_ptr);
440    *offset_ptr += sizeof(val);
441    return val;
442}
443
444uint64_t
445DataExtractor::GetU64_unchecked (offset_t *offset_ptr) const
446{
447    uint64_t val;
448    if (m_byte_order == lldb::endian::InlHostByteOrder())
449        val = ReadInt64 (m_start, *offset_ptr);
450    else
451        val = ReadSwapInt64 (m_start, *offset_ptr);
452    *offset_ptr += sizeof(val);
453    return val;
454}
455
456
457//----------------------------------------------------------------------
458// Extract "count" uint16_t values from the binary data and update
459// the offset pointed to by "offset_ptr". The extracted data is
460// copied into "dst".
461//
462// RETURNS the non-NULL buffer pointer upon successful extraction of
463// all the requested bytes, or NULL when the data is not available
464// in the buffer due to being out of bounds, or unsufficient data.
465//----------------------------------------------------------------------
466void *
467DataExtractor::GetU16 (offset_t *offset_ptr, void *void_dst, uint32_t count) const
468{
469    const size_t src_size = sizeof(uint16_t) * count;
470    const uint16_t *src = (const uint16_t *)GetData (offset_ptr, src_size);
471    if (src)
472    {
473        if (m_byte_order != lldb::endian::InlHostByteOrder())
474        {
475            uint16_t *dst_pos = (uint16_t *)void_dst;
476            uint16_t *dst_end = dst_pos + count;
477            const uint16_t *src_pos = src;
478            while (dst_pos < dst_end)
479            {
480                *dst_pos = ReadSwapInt16 (src_pos);
481                ++dst_pos;
482                ++src_pos;
483            }
484        }
485        else
486        {
487            memcpy (void_dst, src, src_size);
488        }
489        // Return a non-NULL pointer to the converted data as an indicator of success
490        return void_dst;
491    }
492    return NULL;
493}
494
495//----------------------------------------------------------------------
496// Extract a single uint32_t from the data and update the offset
497// pointed to by "offset_ptr".
498//
499// RETURNS the uint32_t that was extracted, or zero on failure.
500//----------------------------------------------------------------------
501uint32_t
502DataExtractor::GetU32 (offset_t *offset_ptr) const
503{
504    uint32_t val = 0;
505    const uint32_t *data = (const uint32_t *)GetData (offset_ptr, sizeof(val));
506    if (data)
507    {
508        if (m_byte_order != lldb::endian::InlHostByteOrder())
509            val = ReadSwapInt32 (data);
510        else
511            val = *data;
512    }
513    return val;
514}
515
516//----------------------------------------------------------------------
517// Extract "count" uint32_t values from the binary data and update
518// the offset pointed to by "offset_ptr". The extracted data is
519// copied into "dst".
520//
521// RETURNS the non-NULL buffer pointer upon successful extraction of
522// all the requested bytes, or NULL when the data is not available
523// in the buffer due to being out of bounds, or unsufficient data.
524//----------------------------------------------------------------------
525void *
526DataExtractor::GetU32 (offset_t *offset_ptr, void *void_dst, uint32_t count) const
527{
528    const size_t src_size = sizeof(uint32_t) * count;
529    const uint32_t *src = (const uint32_t *)GetData (offset_ptr, src_size);
530    if (src)
531    {
532        if (m_byte_order != lldb::endian::InlHostByteOrder())
533        {
534            uint32_t *dst_pos = (uint32_t *)void_dst;
535            uint32_t *dst_end = dst_pos + count;
536            const uint32_t *src_pos = src;
537            while (dst_pos < dst_end)
538            {
539                *dst_pos = ReadSwapInt32 (src_pos);
540                ++dst_pos;
541                ++src_pos;
542            }
543        }
544        else
545        {
546            memcpy (void_dst, src, src_size);
547        }
548        // Return a non-NULL pointer to the converted data as an indicator of success
549        return void_dst;
550    }
551    return NULL;
552}
553
554//----------------------------------------------------------------------
555// Extract a single uint64_t from the data and update the offset
556// pointed to by "offset_ptr".
557//
558// RETURNS the uint64_t that was extracted, or zero on failure.
559//----------------------------------------------------------------------
560uint64_t
561DataExtractor::GetU64 (offset_t *offset_ptr) const
562{
563    uint64_t val = 0;
564    const uint64_t *data = (const uint64_t *)GetData (offset_ptr, sizeof(val));
565    if (data)
566    {
567        if (m_byte_order != lldb::endian::InlHostByteOrder())
568            val = ReadSwapInt64 (data);
569        else
570            val = *data;
571    }
572    return val;
573}
574
575//----------------------------------------------------------------------
576// GetU64
577//
578// Get multiple consecutive 64 bit values. Return true if the entire
579// read succeeds and increment the offset pointed to by offset_ptr, else
580// return false and leave the offset pointed to by offset_ptr unchanged.
581//----------------------------------------------------------------------
582void *
583DataExtractor::GetU64 (offset_t *offset_ptr, void *void_dst, uint32_t count) const
584{
585    const size_t src_size = sizeof(uint64_t) * count;
586    const uint64_t *src = (const uint64_t *)GetData (offset_ptr, src_size);
587    if (src)
588    {
589        if (m_byte_order != lldb::endian::InlHostByteOrder())
590        {
591            uint64_t *dst_pos = (uint64_t *)void_dst;
592            uint64_t *dst_end = dst_pos + count;
593            const uint64_t *src_pos = src;
594            while (dst_pos < dst_end)
595            {
596                *dst_pos = ReadSwapInt64 (src_pos);
597                ++dst_pos;
598                ++src_pos;
599            }
600        }
601        else
602        {
603            memcpy (void_dst, src, src_size);
604        }
605        // Return a non-NULL pointer to the converted data as an indicator of success
606        return void_dst;
607    }
608    return NULL;
609}
610
611//----------------------------------------------------------------------
612// Extract a single integer value from the data and update the offset
613// pointed to by "offset_ptr". The size of the extracted integer
614// is specified by the "byte_size" argument. "byte_size" should have
615// a value between 1 and 4 since the return value is only 32 bits
616// wide. Any "byte_size" values less than 1 or greater than 4 will
617// result in nothing being extracted, and zero being returned.
618//
619// RETURNS the integer value that was extracted, or zero on failure.
620//----------------------------------------------------------------------
621uint32_t
622DataExtractor::GetMaxU32 (offset_t *offset_ptr, size_t byte_size) const
623{
624    switch (byte_size)
625    {
626    case 1: return GetU8 (offset_ptr); break;
627    case 2: return GetU16(offset_ptr); break;
628    case 4: return GetU32(offset_ptr); break;
629    default:
630        assert("GetMaxU32 unhandled case!" == NULL);
631        break;
632    }
633    return 0;
634}
635
636//----------------------------------------------------------------------
637// Extract a single integer value from the data and update the offset
638// pointed to by "offset_ptr". The size of the extracted integer
639// is specified by the "byte_size" argument. "byte_size" should have
640// a value >= 1 and <= 8 since the return value is only 64 bits
641// wide. Any "byte_size" values less than 1 or greater than 8 will
642// result in nothing being extracted, and zero being returned.
643//
644// RETURNS the integer value that was extracted, or zero on failure.
645//----------------------------------------------------------------------
646uint64_t
647DataExtractor::GetMaxU64 (offset_t *offset_ptr, size_t size) const
648{
649    switch (size)
650    {
651    case 1: return GetU8 (offset_ptr); break;
652    case 2: return GetU16(offset_ptr); break;
653    case 4: return GetU32(offset_ptr); break;
654    case 8: return GetU64(offset_ptr); break;
655    default:
656        assert("GetMax64 unhandled case!" == NULL);
657        break;
658    }
659    return 0;
660}
661
662uint64_t
663DataExtractor::GetMaxU64_unchecked (offset_t *offset_ptr, size_t size) const
664{
665    switch (size)
666    {
667        case 1: return GetU8_unchecked  (offset_ptr); break;
668        case 2: return GetU16_unchecked (offset_ptr); break;
669        case 4: return GetU32_unchecked (offset_ptr); break;
670        case 8: return GetU64_unchecked (offset_ptr); break;
671        default:
672            assert("GetMax64 unhandled case!" == NULL);
673            break;
674    }
675    return 0;
676}
677
678int64_t
679DataExtractor::GetMaxS64 (offset_t *offset_ptr, size_t size) const
680{
681    switch (size)
682    {
683    case 1: return (int8_t)GetU8 (offset_ptr); break;
684    case 2: return (int16_t)GetU16(offset_ptr); break;
685    case 4: return (int32_t)GetU32(offset_ptr); break;
686    case 8: return (int64_t)GetU64(offset_ptr); break;
687    default:
688        assert("GetMax64 unhandled case!" == NULL);
689        break;
690    }
691    return 0;
692}
693
694uint64_t
695DataExtractor::GetMaxU64Bitfield (offset_t *offset_ptr, size_t size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset) const
696{
697    uint64_t uval64 = GetMaxU64 (offset_ptr, size);
698    if (bitfield_bit_size > 0)
699    {
700        if (bitfield_bit_offset > 0)
701            uval64 >>= bitfield_bit_offset;
702        uint64_t bitfield_mask = ((1ul << bitfield_bit_size) - 1);
703        if (!bitfield_mask && bitfield_bit_offset == 0 && bitfield_bit_size == 64)
704            return uval64;
705        uval64 &= bitfield_mask;
706    }
707    return uval64;
708}
709
710int64_t
711DataExtractor::GetMaxS64Bitfield (offset_t *offset_ptr, size_t size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset) const
712{
713    int64_t sval64 = GetMaxS64 (offset_ptr, size);
714    if (bitfield_bit_size > 0)
715    {
716        if (bitfield_bit_offset > 0)
717            sval64 >>= bitfield_bit_offset;
718        uint64_t bitfield_mask = (((uint64_t)1) << bitfield_bit_size) - 1;
719        sval64 &= bitfield_mask;
720        // sign extend if needed
721        if (sval64 & (((uint64_t)1) << (bitfield_bit_size - 1)))
722            sval64 |= ~bitfield_mask;
723    }
724    return sval64;
725}
726
727
728float
729DataExtractor::GetFloat (offset_t *offset_ptr) const
730{
731    typedef float float_type;
732    float_type val = 0.0;
733    const size_t src_size = sizeof(float_type);
734    const float_type *src = (const float_type *)GetData (offset_ptr, src_size);
735    if (src)
736    {
737        if (m_byte_order != lldb::endian::InlHostByteOrder())
738        {
739            const uint8_t *src_data = (const uint8_t *)src;
740            uint8_t *dst_data = (uint8_t *)&val;
741            for (size_t i=0; i<sizeof(float_type); ++i)
742                dst_data[sizeof(float_type) - 1 - i] = src_data[i];
743        }
744        else
745        {
746            val = *src;
747        }
748    }
749    return val;
750}
751
752double
753DataExtractor::GetDouble (offset_t *offset_ptr) const
754{
755    typedef double float_type;
756    float_type val = 0.0;
757    const size_t src_size = sizeof(float_type);
758    const float_type *src = (const float_type *)GetData (offset_ptr, src_size);
759    if (src)
760    {
761        if (m_byte_order != lldb::endian::InlHostByteOrder())
762        {
763            const uint8_t *src_data = (const uint8_t *)src;
764            uint8_t *dst_data = (uint8_t *)&val;
765            for (size_t i=0; i<sizeof(float_type); ++i)
766                dst_data[sizeof(float_type) - 1 - i] = src_data[i];
767        }
768        else
769        {
770            val = *src;
771        }
772    }
773    return val;
774}
775
776
777long double
778DataExtractor::GetLongDouble (offset_t *offset_ptr) const
779{
780    long double val = 0.0;
781#if defined (__i386__) || defined (__amd64__) || defined (__x86_64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_X64)
782    *offset_ptr += CopyByteOrderedData (*offset_ptr, 10, &val, sizeof(val), lldb::endian::InlHostByteOrder());
783#else
784    *offset_ptr += CopyByteOrderedData (*offset_ptr, sizeof(val), &val, sizeof(val), lldb::endian::InlHostByteOrder());
785#endif
786    return val;
787}
788
789
790//------------------------------------------------------------------
791// Extract a single address from the data and update the offset
792// pointed to by "offset_ptr". The size of the extracted address
793// comes from the "this->m_addr_size" member variable and should be
794// set correctly prior to extracting any address values.
795//
796// RETURNS the address that was extracted, or zero on failure.
797//------------------------------------------------------------------
798uint64_t
799DataExtractor::GetAddress (offset_t *offset_ptr) const
800{
801    return GetMaxU64 (offset_ptr, m_addr_size);
802}
803
804uint64_t
805DataExtractor::GetAddress_unchecked (offset_t *offset_ptr) const
806{
807    return GetMaxU64_unchecked (offset_ptr, m_addr_size);
808}
809
810//------------------------------------------------------------------
811// Extract a single pointer from the data and update the offset
812// pointed to by "offset_ptr". The size of the extracted pointer
813// comes from the "this->m_addr_size" member variable and should be
814// set correctly prior to extracting any pointer values.
815//
816// RETURNS the pointer that was extracted, or zero on failure.
817//------------------------------------------------------------------
818uint64_t
819DataExtractor::GetPointer (offset_t *offset_ptr) const
820{
821    return GetMaxU64 (offset_ptr, m_addr_size);
822}
823
824//----------------------------------------------------------------------
825// GetDwarfEHPtr
826//
827// Used for calls when the value type is specified by a DWARF EH Frame
828// pointer encoding.
829//----------------------------------------------------------------------
830
831uint64_t
832DataExtractor::GetGNUEHPointer (offset_t *offset_ptr, uint32_t eh_ptr_enc, lldb::addr_t pc_rel_addr, lldb::addr_t text_addr, lldb::addr_t data_addr)//, BSDRelocs *data_relocs) const
833{
834    if (eh_ptr_enc == DW_EH_PE_omit)
835        return ULLONG_MAX;  // Value isn't in the buffer...
836
837    uint64_t baseAddress = 0;
838    uint64_t addressValue = 0;
839    const uint32_t addr_size = GetAddressByteSize();
840
841    bool signExtendValue = false;
842    // Decode the base part or adjust our offset
843    switch (eh_ptr_enc & 0x70)
844    {
845    case DW_EH_PE_pcrel:
846        signExtendValue = true;
847        baseAddress = *offset_ptr;
848        if (pc_rel_addr != LLDB_INVALID_ADDRESS)
849            baseAddress += pc_rel_addr;
850//      else
851//          Log::GlobalWarning ("PC relative pointer encoding found with invalid pc relative address.");
852        break;
853
854    case DW_EH_PE_textrel:
855        signExtendValue = true;
856        if (text_addr != LLDB_INVALID_ADDRESS)
857            baseAddress = text_addr;
858//      else
859//          Log::GlobalWarning ("text relative pointer encoding being decoded with invalid text section address, setting base address to zero.");
860        break;
861
862    case DW_EH_PE_datarel:
863        signExtendValue = true;
864        if (data_addr != LLDB_INVALID_ADDRESS)
865            baseAddress = data_addr;
866//      else
867//          Log::GlobalWarning ("data relative pointer encoding being decoded with invalid data section address, setting base address to zero.");
868        break;
869
870    case DW_EH_PE_funcrel:
871        signExtendValue = true;
872        break;
873
874    case DW_EH_PE_aligned:
875        {
876            // SetPointerSize should be called prior to extracting these so the
877            // pointer size is cached
878            assert(addr_size != 0);
879            if (addr_size)
880            {
881                // Align to a address size boundary first
882                uint32_t alignOffset = *offset_ptr % addr_size;
883                if (alignOffset)
884                    offset_ptr += addr_size - alignOffset;
885            }
886        }
887        break;
888
889    default:
890    break;
891    }
892
893    // Decode the value part
894    switch (eh_ptr_enc & DW_EH_PE_MASK_ENCODING)
895    {
896    case DW_EH_PE_absptr    :
897        {
898            addressValue = GetAddress (offset_ptr);
899//          if (data_relocs)
900//              addressValue = data_relocs->Relocate(*offset_ptr - addr_size, *this, addressValue);
901        }
902        break;
903    case DW_EH_PE_uleb128   : addressValue = GetULEB128(offset_ptr);        break;
904    case DW_EH_PE_udata2    : addressValue = GetU16(offset_ptr);            break;
905    case DW_EH_PE_udata4    : addressValue = GetU32(offset_ptr);            break;
906    case DW_EH_PE_udata8    : addressValue = GetU64(offset_ptr);            break;
907    case DW_EH_PE_sleb128   : addressValue = GetSLEB128(offset_ptr);        break;
908    case DW_EH_PE_sdata2    : addressValue = (int16_t)GetU16(offset_ptr);   break;
909    case DW_EH_PE_sdata4    : addressValue = (int32_t)GetU32(offset_ptr);   break;
910    case DW_EH_PE_sdata8    : addressValue = (int64_t)GetU64(offset_ptr);   break;
911    default:
912    // Unhandled encoding type
913    assert(eh_ptr_enc);
914    break;
915    }
916
917    // Since we promote everything to 64 bit, we may need to sign extend
918    if (signExtendValue && addr_size < sizeof(baseAddress))
919    {
920        uint64_t sign_bit = 1ull << ((addr_size * 8ull) - 1ull);
921        if (sign_bit & addressValue)
922        {
923            uint64_t mask = ~sign_bit + 1;
924            addressValue |= mask;
925        }
926    }
927    return baseAddress + addressValue;
928}
929
930size_t
931DataExtractor::ExtractBytes (offset_t offset, offset_t length, ByteOrder dst_byte_order, void *dst) const
932{
933    const uint8_t *src = PeekData (offset, length);
934    if (src)
935    {
936        if (dst_byte_order != GetByteOrder())
937        {
938            // Validate that only a word- or register-sized dst is byte swapped
939            assert (length == 1 || length == 2 || length == 4 || length == 8 ||
940                    length == 10 || length == 16 || length == 32);
941
942            for (uint32_t i=0; i<length; ++i)
943                ((uint8_t*)dst)[i] = src[length - i - 1];
944        }
945        else
946            ::memcpy (dst, src, length);
947        return length;
948    }
949    return 0;
950}
951
952// Extract data as it exists in target memory
953lldb::offset_t
954DataExtractor::CopyData (offset_t offset,
955                         offset_t length,
956                         void *dst) const
957{
958    const uint8_t *src = PeekData (offset, length);
959    if (src)
960    {
961        ::memcpy (dst, src, length);
962        return length;
963    }
964    return 0;
965}
966
967// Extract data and swap if needed when doing the copy
968lldb::offset_t
969DataExtractor::CopyByteOrderedData (offset_t src_offset,
970                                    offset_t src_len,
971                                    void *dst_void_ptr,
972                                    offset_t dst_len,
973                                    ByteOrder dst_byte_order) const
974{
975    // Validate the source info
976    if (!ValidOffsetForDataOfSize(src_offset, src_len))
977        assert (ValidOffsetForDataOfSize(src_offset, src_len));
978    assert (src_len > 0);
979    assert (m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle);
980
981    // Validate the destination info
982    assert (dst_void_ptr != NULL);
983    assert (dst_len > 0);
984    assert (dst_byte_order == eByteOrderBig || dst_byte_order == eByteOrderLittle);
985
986    // Validate that only a word- or register-sized dst is byte swapped
987    assert (dst_byte_order == m_byte_order || dst_len == 1 || dst_len == 2 ||
988            dst_len == 4 || dst_len == 8 || dst_len == 10 || dst_len == 16 ||
989            dst_len == 32);
990
991    // Must have valid byte orders set in this object and for destination
992    if (!(dst_byte_order == eByteOrderBig || dst_byte_order == eByteOrderLittle) ||
993        !(m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle))
994        return 0;
995
996    uint32_t i;
997    uint8_t* dst = (uint8_t*)dst_void_ptr;
998    const uint8_t* src = (const uint8_t *)PeekData (src_offset, src_len);
999    if (src)
1000    {
1001        if (dst_len >= src_len)
1002        {
1003            // We are copying the entire value from src into dst.
1004            // Calculate how many, if any, zeroes we need for the most
1005            // significant bytes if "dst_len" is greater than "src_len"...
1006            const size_t num_zeroes = dst_len - src_len;
1007            if (dst_byte_order == eByteOrderBig)
1008            {
1009                // Big endian, so we lead with zeroes...
1010                if (num_zeroes > 0)
1011                    ::memset (dst, 0, num_zeroes);
1012                // Then either copy or swap the rest
1013                if (m_byte_order == eByteOrderBig)
1014                {
1015                    ::memcpy (dst + num_zeroes, src, src_len);
1016                }
1017                else
1018                {
1019                    for (i=0; i<src_len; ++i)
1020                        dst[i+num_zeroes] = src[src_len - 1 - i];
1021                }
1022            }
1023            else
1024            {
1025                // Little endian destination, so we lead the value bytes
1026                if (m_byte_order == eByteOrderBig)
1027                {
1028                    for (i=0; i<src_len; ++i)
1029                        dst[i] = src[src_len - 1 - i];
1030                }
1031                else
1032                {
1033                    ::memcpy (dst, src, src_len);
1034                }
1035                // And zero the rest...
1036                if (num_zeroes > 0)
1037                    ::memset (dst + src_len, 0, num_zeroes);
1038            }
1039            return src_len;
1040        }
1041        else
1042        {
1043            // We are only copying some of the value from src into dst..
1044
1045            if (dst_byte_order == eByteOrderBig)
1046            {
1047                // Big endian dst
1048                if (m_byte_order == eByteOrderBig)
1049                {
1050                    // Big endian dst, with big endian src
1051                    ::memcpy (dst, src + (src_len - dst_len), dst_len);
1052                }
1053                else
1054                {
1055                    // Big endian dst, with little endian src
1056                    for (i=0; i<dst_len; ++i)
1057                        dst[i] = src[dst_len - 1 - i];
1058                }
1059            }
1060            else
1061            {
1062                // Little endian dst
1063                if (m_byte_order == eByteOrderBig)
1064                {
1065                    // Little endian dst, with big endian src
1066                    for (i=0; i<dst_len; ++i)
1067                        dst[i] = src[src_len - 1 - i];
1068                }
1069                else
1070                {
1071                    // Little endian dst, with big endian src
1072                    ::memcpy (dst, src, dst_len);
1073                }
1074            }
1075            return dst_len;
1076        }
1077
1078    }
1079    return 0;
1080}
1081
1082
1083//----------------------------------------------------------------------
1084// Extracts a variable length NULL terminated C string from
1085// the data at the offset pointed to by "offset_ptr".  The
1086// "offset_ptr" will be updated with the offset of the byte that
1087// follows the NULL terminator byte.
1088//
1089// If the offset pointed to by "offset_ptr" is out of bounds, or if
1090// "length" is non-zero and there aren't enough avaialable
1091// bytes, NULL will be returned and "offset_ptr" will not be
1092// updated.
1093//----------------------------------------------------------------------
1094const char*
1095DataExtractor::GetCStr (offset_t *offset_ptr) const
1096{
1097    const char *cstr = (const char *)PeekData (*offset_ptr, 1);
1098    if (cstr)
1099    {
1100        const char *cstr_end = cstr;
1101        const char *end = (const char *)m_end;
1102        while (cstr_end < end && *cstr_end)
1103            ++cstr_end;
1104
1105        // Now we are either at the end of the data or we point to the
1106        // NULL C string terminator with cstr_end...
1107        if (*cstr_end == '\0')
1108        {
1109            // Advance the offset with one extra byte for the NULL terminator
1110            *offset_ptr += (cstr_end - cstr + 1);
1111            return cstr;
1112        }
1113
1114        // We reached the end of the data without finding a NULL C string
1115        // terminator. Fall through and return NULL otherwise anyone that
1116        // would have used the result as a C string can wonder into
1117        // unknown memory...
1118    }
1119    return NULL;
1120}
1121
1122//----------------------------------------------------------------------
1123// Extracts a NULL terminated C string from the fixed length field of
1124// length "len" at the offset pointed to by "offset_ptr".
1125// The "offset_ptr" will be updated with the offset of the byte that
1126// follows the fixed length field.
1127//
1128// If the offset pointed to by "offset_ptr" is out of bounds, or if
1129// the offset plus the length of the field is out of bounds, or if the
1130// field does not contain a NULL terminator byte, NULL will be returned
1131// and "offset_ptr" will not be updated.
1132//----------------------------------------------------------------------
1133const char*
1134DataExtractor::GetCStr (offset_t *offset_ptr, offset_t len) const
1135{
1136    const char *cstr = (const char *)PeekData (*offset_ptr, len);
1137    if (cstr)
1138    {
1139        if (memchr (cstr, '\0', len) == NULL)
1140        {
1141            return NULL;
1142        }
1143        *offset_ptr += len;
1144        return cstr;
1145    }
1146    return NULL;
1147}
1148
1149//------------------------------------------------------------------
1150// Peeks at a string in the contained data. No verification is done
1151// to make sure the entire string lies within the bounds of this
1152// object's data, only "offset" is verified to be a valid offset.
1153//
1154// Returns a valid C string pointer if "offset" is a valid offset in
1155// this object's data, else NULL is returned.
1156//------------------------------------------------------------------
1157const char *
1158DataExtractor::PeekCStr (offset_t offset) const
1159{
1160    return (const char *)PeekData (offset, 1);
1161}
1162
1163//----------------------------------------------------------------------
1164// Extracts an unsigned LEB128 number from this object's data
1165// starting at the offset pointed to by "offset_ptr". The offset
1166// pointed to by "offset_ptr" will be updated with the offset of the
1167// byte following the last extracted byte.
1168//
1169// Returned the extracted integer value.
1170//----------------------------------------------------------------------
1171uint64_t
1172DataExtractor::GetULEB128 (offset_t *offset_ptr) const
1173{
1174    const uint8_t *src = (const uint8_t *)PeekData (*offset_ptr, 1);
1175    if (src == NULL)
1176        return 0;
1177
1178    const uint8_t *end = m_end;
1179
1180    if (src < end)
1181    {
1182        uint64_t result = *src++;
1183        if (result >= 0x80)
1184        {
1185            result &= 0x7f;
1186            int shift = 7;
1187            while (src < end)
1188            {
1189                uint8_t byte = *src++;
1190                result |= (byte & 0x7f) << shift;
1191                if ((byte & 0x80) == 0)
1192                    break;
1193                shift += 7;
1194            }
1195        }
1196        *offset_ptr = src - m_start;
1197        return result;
1198    }
1199
1200    return 0;
1201}
1202
1203//----------------------------------------------------------------------
1204// Extracts an signed LEB128 number from this object's data
1205// starting at the offset pointed to by "offset_ptr". The offset
1206// pointed to by "offset_ptr" will be updated with the offset of the
1207// byte following the last extracted byte.
1208//
1209// Returned the extracted integer value.
1210//----------------------------------------------------------------------
1211int64_t
1212DataExtractor::GetSLEB128 (offset_t *offset_ptr) const
1213{
1214    const uint8_t *src = (const uint8_t *)PeekData (*offset_ptr, 1);
1215    if (src == NULL)
1216        return 0;
1217
1218    const uint8_t *end = m_end;
1219
1220    if (src < end)
1221    {
1222        int64_t result = 0;
1223        int shift = 0;
1224        int size = sizeof (int64_t) * 8;
1225
1226        uint8_t byte = 0;
1227        int bytecount = 0;
1228
1229        while (src < end)
1230        {
1231            bytecount++;
1232            byte = *src++;
1233            result |= (byte & 0x7f) << shift;
1234            shift += 7;
1235            if ((byte & 0x80) == 0)
1236                break;
1237        }
1238
1239        // Sign bit of byte is 2nd high order bit (0x40)
1240        if (shift < size && (byte & 0x40))
1241            result |= - (1 << shift);
1242
1243        *offset_ptr += bytecount;
1244        return result;
1245    }
1246    return 0;
1247}
1248
1249//----------------------------------------------------------------------
1250// Skips a ULEB128 number (signed or unsigned) from this object's
1251// data starting at the offset pointed to by "offset_ptr". The
1252// offset pointed to by "offset_ptr" will be updated with the offset
1253// of the byte following the last extracted byte.
1254//
1255// Returns the number of bytes consumed during the extraction.
1256//----------------------------------------------------------------------
1257uint32_t
1258DataExtractor::Skip_LEB128 (offset_t *offset_ptr) const
1259{
1260    uint32_t bytes_consumed = 0;
1261    const uint8_t *src = (const uint8_t *)PeekData (*offset_ptr, 1);
1262    if (src == NULL)
1263        return 0;
1264
1265    const uint8_t *end = m_end;
1266
1267    if (src < end)
1268    {
1269        const uint8_t *src_pos = src;
1270        while ((src_pos < end) && (*src_pos++ & 0x80))
1271            ++bytes_consumed;
1272        *offset_ptr += src_pos - src;
1273    }
1274    return bytes_consumed;
1275}
1276
1277static bool
1278GetAPInt (const DataExtractor &data, lldb::offset_t *offset_ptr, lldb::offset_t byte_size, llvm::APInt &result)
1279{
1280    llvm::SmallVector<uint64_t, 2> uint64_array;
1281    lldb::offset_t bytes_left = byte_size;
1282    uint64_t u64;
1283    const lldb::ByteOrder byte_order = data.GetByteOrder();
1284    if (byte_order == lldb::eByteOrderLittle)
1285    {
1286        while (bytes_left > 0)
1287        {
1288            if (bytes_left >= 8)
1289            {
1290                u64 = data.GetU64(offset_ptr);
1291                bytes_left -= 8;
1292            }
1293            else
1294            {
1295                u64 = data.GetMaxU64(offset_ptr, (uint32_t)bytes_left);
1296                bytes_left = 0;
1297            }
1298            uint64_array.push_back(u64);
1299        }
1300        result = llvm::APInt(byte_size * 8, llvm::ArrayRef<uint64_t>(uint64_array));
1301        return true;
1302    }
1303    else if (byte_order == lldb::eByteOrderBig)
1304    {
1305        lldb::offset_t be_offset = *offset_ptr + byte_size;
1306        lldb::offset_t temp_offset;
1307        while (bytes_left > 0)
1308        {
1309            if (bytes_left >= 8)
1310            {
1311                be_offset -= 8;
1312                temp_offset = be_offset;
1313                u64 = data.GetU64(&temp_offset);
1314                bytes_left -= 8;
1315            }
1316            else
1317            {
1318                be_offset -= bytes_left;
1319                temp_offset = be_offset;
1320                u64 = data.GetMaxU64(&temp_offset, (uint32_t)bytes_left);
1321                bytes_left = 0;
1322            }
1323            uint64_array.push_back(u64);
1324        }
1325        *offset_ptr += byte_size;
1326        result = llvm::APInt(byte_size * 8, llvm::ArrayRef<uint64_t>(uint64_array));
1327        return true;
1328    }
1329    return false;
1330}
1331
1332static lldb::offset_t
1333DumpAPInt (Stream *s, const DataExtractor &data, lldb::offset_t offset, lldb::offset_t byte_size, bool is_signed, unsigned radix)
1334{
1335    llvm::APInt apint;
1336    if (GetAPInt (data, &offset, byte_size, apint))
1337    {
1338        std::string apint_str(apint.toString(radix, is_signed));
1339        switch (radix)
1340        {
1341            case 2:
1342                s->Write ("0b", 2);
1343                break;
1344            case 8:
1345                s->Write ("0", 1);
1346                break;
1347            case 10:
1348                break;
1349        }
1350        s->Write(apint_str.c_str(), apint_str.size());
1351    }
1352    return offset;
1353}
1354
1355static float half2float (uint16_t half)
1356{
1357#ifdef _MSC_VER
1358    llvm_unreachable("half2float not implemented for MSVC");
1359#else
1360    union{ float       f; uint32_t    u;}u;
1361    int32_t v = (int16_t) half;
1362
1363    if( 0 == (v & 0x7c00))
1364    {
1365        u.u = v & 0x80007FFFU;
1366        return u.f * ldexpf(1, 125);
1367    }
1368
1369    v <<= 13;
1370    u.u = v | 0x70000000U;
1371    return u.f * ldexpf(1, -112);
1372#endif
1373}
1374
1375lldb::offset_t
1376DataExtractor::Dump (Stream *s,
1377                     offset_t start_offset,
1378                     lldb::Format item_format,
1379                     size_t item_byte_size,
1380                     size_t item_count,
1381                     size_t num_per_line,
1382                     uint64_t base_addr,
1383                     uint32_t item_bit_size,     // If zero, this is not a bitfield value, if non-zero, the value is a bitfield
1384                     uint32_t item_bit_offset,    // If "item_bit_size" is non-zero, this is the shift amount to apply to a bitfield
1385                     ExecutionContextScope *exe_scope) const
1386{
1387    if (s == NULL)
1388        return start_offset;
1389
1390    if (item_format == eFormatPointer)
1391    {
1392        if (item_byte_size != 4 && item_byte_size != 8)
1393            item_byte_size = s->GetAddressByteSize();
1394    }
1395
1396    offset_t offset = start_offset;
1397
1398    if (item_format == eFormatInstruction)
1399    {
1400        TargetSP target_sp;
1401        if (exe_scope)
1402            target_sp = exe_scope->CalculateTarget();
1403        if (target_sp)
1404        {
1405            DisassemblerSP disassembler_sp (Disassembler::FindPlugin(target_sp->GetArchitecture(), NULL,  NULL));
1406            if (disassembler_sp)
1407            {
1408                lldb::addr_t addr = base_addr + start_offset;
1409                lldb_private::Address so_addr;
1410				bool data_from_file = true;
1411                if (target_sp->GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
1412                {
1413                    data_from_file = false;
1414                }
1415                else
1416                {
1417                    if (target_sp->GetSectionLoadList().IsEmpty() || !target_sp->GetImages().ResolveFileAddress(addr, so_addr))
1418                        so_addr.SetRawAddress(addr);
1419                }
1420
1421                size_t bytes_consumed = disassembler_sp->DecodeInstructions (so_addr, *this, start_offset, item_count, false, data_from_file);
1422
1423                if (bytes_consumed)
1424                {
1425                    offset += bytes_consumed;
1426                    const bool show_address = base_addr != LLDB_INVALID_ADDRESS;
1427                    const bool show_bytes = true;
1428                    ExecutionContext exe_ctx;
1429                    exe_scope->CalculateExecutionContext(exe_ctx);
1430                    disassembler_sp->GetInstructionList().Dump (s,  show_address, show_bytes, &exe_ctx);
1431
1432                    // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
1433                    // I'll fix that but for now, just clear the list and it will go away nicely.
1434                    disassembler_sp->GetInstructionList().Clear();
1435                }
1436            }
1437        }
1438        else
1439            s->Printf ("invalid target");
1440
1441        return offset;
1442    }
1443
1444    if ((item_format == eFormatOSType || item_format == eFormatAddressInfo) && item_byte_size > 8)
1445        item_format = eFormatHex;
1446
1447    lldb::offset_t line_start_offset = start_offset;
1448    for (uint32_t count = 0; ValidOffset(offset) && count < item_count; ++count)
1449    {
1450        if ((count % num_per_line) == 0)
1451        {
1452            if (count > 0)
1453            {
1454                if (item_format == eFormatBytesWithASCII && offset > line_start_offset)
1455                {
1456                    s->Printf("%*s", static_cast<int>((num_per_line - (offset - line_start_offset)) * 3 + 2), "");
1457                    Dump(s, line_start_offset, eFormatCharPrintable, 1, offset - line_start_offset, LLDB_INVALID_OFFSET, LLDB_INVALID_ADDRESS, 0, 0);
1458                }
1459                s->EOL();
1460            }
1461            if (base_addr != LLDB_INVALID_ADDRESS)
1462                s->Printf ("0x%8.8" PRIx64 ": ", (uint64_t)(base_addr + (offset - start_offset)));
1463            line_start_offset = offset;
1464        }
1465        else
1466        if (item_format != eFormatChar &&
1467            item_format != eFormatCharPrintable &&
1468            item_format != eFormatCharArray &&
1469            count > 0)
1470        {
1471            s->PutChar(' ');
1472        }
1473
1474        uint32_t i;
1475        switch (item_format)
1476        {
1477        case eFormatBoolean:
1478            if (item_byte_size <= 8)
1479                s->Printf ("%s", GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset) ? "true" : "false");
1480            else
1481            {
1482                s->Printf("error: unsupported byte size (%zu) for boolean format", item_byte_size);
1483                return offset;
1484            }
1485            break;
1486
1487        case eFormatBinary:
1488            if (item_byte_size <= 8)
1489            {
1490                uint64_t uval64 = GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset);
1491                // Avoid std::bitset<64>::to_string() since it is missing in
1492                // earlier C++ libraries
1493                std::string binary_value(64, '0');
1494                std::bitset<64> bits(uval64);
1495                for (i = 0; i < 64; ++i)
1496                    if (bits[i])
1497                        binary_value[64 - 1 - i] = '1';
1498                if (item_bit_size > 0)
1499                    s->Printf("0b%s", binary_value.c_str() + 64 - item_bit_size);
1500                else if (item_byte_size > 0 && item_byte_size <= 8)
1501                    s->Printf("0b%s", binary_value.c_str() + 64 - item_byte_size * 8);
1502            }
1503            else
1504            {
1505                const bool is_signed = false;
1506                const unsigned radix = 2;
1507                offset = DumpAPInt (s, *this, offset, item_byte_size, is_signed, radix);
1508            }
1509            break;
1510
1511        case eFormatBytes:
1512        case eFormatBytesWithASCII:
1513            for (i=0; i<item_byte_size; ++i)
1514            {
1515                s->Printf ("%2.2x", GetU8(&offset));
1516            }
1517            // Put an extra space between the groups of bytes if more than one
1518            // is being dumped in a group (item_byte_size is more than 1).
1519            if (item_byte_size > 1)
1520                s->PutChar(' ');
1521            break;
1522
1523        case eFormatChar:
1524        case eFormatCharPrintable:
1525        case eFormatCharArray:
1526            {
1527                // If we are only printing one character surround it with single
1528                // quotes
1529                if (item_count == 1 && item_format == eFormatChar)
1530                    s->PutChar('\'');
1531
1532                const uint64_t ch = GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset);
1533                if (isprint(ch))
1534                    s->Printf ("%c", (char)ch);
1535                else if (item_format != eFormatCharPrintable)
1536                {
1537                    switch (ch)
1538                    {
1539                    case '\033': s->Printf ("\\e"); break;
1540                    case '\a': s->Printf ("\\a"); break;
1541                    case '\b': s->Printf ("\\b"); break;
1542                    case '\f': s->Printf ("\\f"); break;
1543                    case '\n': s->Printf ("\\n"); break;
1544                    case '\r': s->Printf ("\\r"); break;
1545                    case '\t': s->Printf ("\\t"); break;
1546                    case '\v': s->Printf ("\\v"); break;
1547                    case '\0': s->Printf ("\\0"); break;
1548                    default:
1549                        if (item_byte_size == 1)
1550                            s->Printf ("\\x%2.2x", (uint8_t)ch);
1551                        else
1552                            s->Printf ("%" PRIu64, ch);
1553                        break;
1554                    }
1555                }
1556                else
1557                {
1558                    s->PutChar(NON_PRINTABLE_CHAR);
1559                }
1560
1561                // If we are only printing one character surround it with single quotes
1562                if (item_count == 1 && item_format == eFormatChar)
1563                    s->PutChar('\'');
1564            }
1565            break;
1566
1567        case eFormatEnum:       // Print enum value as a signed integer when we don't get the enum type
1568        case eFormatDecimal:
1569            if (item_byte_size <= 8)
1570                s->Printf ("%" PRId64, GetMaxS64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset));
1571            else
1572            {
1573                const bool is_signed = true;
1574                const unsigned radix = 10;
1575                offset = DumpAPInt (s, *this, offset, item_byte_size, is_signed, radix);
1576            }
1577            break;
1578
1579        case eFormatUnsigned:
1580            if (item_byte_size <= 8)
1581                s->Printf ("%" PRIu64, GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset));
1582            else
1583            {
1584                const bool is_signed = false;
1585                const unsigned radix = 10;
1586                offset = DumpAPInt (s, *this, offset, item_byte_size, is_signed, radix);
1587            }
1588            break;
1589
1590        case eFormatOctal:
1591            if (item_byte_size <= 8)
1592                s->Printf ("0%" PRIo64, GetMaxS64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset));
1593            else
1594            {
1595                const bool is_signed = false;
1596                const unsigned radix = 8;
1597                offset = DumpAPInt (s, *this, offset, item_byte_size, is_signed, radix);
1598            }
1599            break;
1600
1601        case eFormatOSType:
1602            {
1603                uint64_t uval64 = GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset);
1604                s->PutChar('\'');
1605                for (i=0; i<item_byte_size; ++i)
1606                {
1607                    uint8_t ch = (uint8_t)(uval64 >> ((item_byte_size - i - 1) * 8));
1608                    if (isprint(ch))
1609                        s->Printf ("%c", ch);
1610                    else
1611                    {
1612                        switch (ch)
1613                        {
1614                        case '\033': s->Printf ("\\e"); break;
1615                        case '\a': s->Printf ("\\a"); break;
1616                        case '\b': s->Printf ("\\b"); break;
1617                        case '\f': s->Printf ("\\f"); break;
1618                        case '\n': s->Printf ("\\n"); break;
1619                        case '\r': s->Printf ("\\r"); break;
1620                        case '\t': s->Printf ("\\t"); break;
1621                        case '\v': s->Printf ("\\v"); break;
1622                        case '\0': s->Printf ("\\0"); break;
1623                        default:   s->Printf ("\\x%2.2x", ch); break;
1624                        }
1625                    }
1626                }
1627                s->PutChar('\'');
1628            }
1629            break;
1630
1631        case eFormatCString:
1632            {
1633                const char *cstr = GetCStr(&offset);
1634
1635                if (!cstr)
1636                {
1637                    s->Printf("NULL");
1638                    offset = LLDB_INVALID_OFFSET;
1639                }
1640                else
1641                {
1642                    s->PutChar('\"');
1643
1644                    while (const char c = *cstr)
1645                    {
1646                        if (isprint(c))
1647                        {
1648                            s->PutChar(c);
1649                        }
1650                        else
1651                        {
1652                            switch (c)
1653                            {
1654                            case '\033': s->Printf ("\\e"); break;
1655                            case '\a': s->Printf ("\\a"); break;
1656                            case '\b': s->Printf ("\\b"); break;
1657                            case '\f': s->Printf ("\\f"); break;
1658                            case '\n': s->Printf ("\\n"); break;
1659                            case '\r': s->Printf ("\\r"); break;
1660                            case '\t': s->Printf ("\\t"); break;
1661                            case '\v': s->Printf ("\\v"); break;
1662                            default:   s->Printf ("\\x%2.2x", c); break;
1663                            }
1664                        }
1665
1666                        ++cstr;
1667                    }
1668
1669                    s->PutChar('\"');
1670                }
1671            }
1672            break;
1673
1674
1675        case eFormatPointer:
1676            s->Address(GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset), sizeof (addr_t));
1677            break;
1678
1679
1680        case eFormatComplexInteger:
1681            {
1682                size_t complex_int_byte_size = item_byte_size / 2;
1683
1684                if (complex_int_byte_size <= 8)
1685                {
1686                    s->Printf("%" PRIu64, GetMaxU64Bitfield(&offset, complex_int_byte_size, 0, 0));
1687                    s->Printf(" + %" PRIu64 "i", GetMaxU64Bitfield(&offset, complex_int_byte_size, 0, 0));
1688                }
1689                else
1690                {
1691                    s->Printf("error: unsupported byte size (%zu) for complex integer format", item_byte_size);
1692                    return offset;
1693                }
1694            }
1695            break;
1696
1697        case eFormatComplex:
1698            if (sizeof(float) * 2 == item_byte_size)
1699            {
1700                float f32_1 = GetFloat (&offset);
1701                float f32_2 = GetFloat (&offset);
1702
1703                s->Printf ("%g + %gi", f32_1, f32_2);
1704                break;
1705            }
1706            else if (sizeof(double) * 2 == item_byte_size)
1707            {
1708                double d64_1 = GetDouble (&offset);
1709                double d64_2 = GetDouble (&offset);
1710
1711                s->Printf ("%lg + %lgi", d64_1, d64_2);
1712                break;
1713            }
1714            else if (sizeof(long double) * 2 == item_byte_size)
1715            {
1716                long double ld64_1 = GetLongDouble (&offset);
1717                long double ld64_2 = GetLongDouble (&offset);
1718                s->Printf ("%Lg + %Lgi", ld64_1, ld64_2);
1719                break;
1720            }
1721            else
1722            {
1723                s->Printf("error: unsupported byte size (%zu) for complex float format", item_byte_size);
1724                return offset;
1725            }
1726            break;
1727
1728        default:
1729        case eFormatDefault:
1730        case eFormatHex:
1731        case eFormatHexUppercase:
1732            {
1733                bool wantsuppercase  = (item_format == eFormatHexUppercase);
1734                switch (item_byte_size)
1735                {
1736                case 1:
1737                case 2:
1738                case 4:
1739                case 8:
1740                    s->Printf(wantsuppercase ? "0x%*.*" PRIX64 : "0x%*.*" PRIx64, (int)(2 * item_byte_size), (int)(2 * item_byte_size), GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset));
1741                    break;
1742                default:
1743                    {
1744                        assert (item_bit_size == 0 && item_bit_offset == 0);
1745                        const uint8_t *bytes = (const uint8_t* )GetData(&offset, item_byte_size);
1746                        if (bytes)
1747                        {
1748                            s->PutCString("0x");
1749                            uint32_t idx;
1750                                if (m_byte_order == eByteOrderBig)
1751                            {
1752                                for (idx = 0; idx < item_byte_size; ++idx)
1753                                    s->Printf(wantsuppercase ? "%2.2X" : "%2.2x", bytes[idx]);
1754                            }
1755                            else
1756                            {
1757                                for (idx = 0; idx < item_byte_size; ++idx)
1758                                    s->Printf(wantsuppercase ? "%2.2X" : "%2.2x", bytes[item_byte_size - 1 - idx]);
1759                            }
1760                        }
1761                    }
1762                    break;
1763                }
1764            }
1765            break;
1766
1767        case eFormatFloat:
1768            {
1769                TargetSP target_sp;
1770                bool used_apfloat = false;
1771                if (exe_scope)
1772                    target_sp = exe_scope->CalculateTarget();
1773                if (target_sp)
1774                {
1775                    ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext();
1776                    if (clang_ast)
1777                    {
1778                        clang::ASTContext *ast = clang_ast->getASTContext();
1779                        if (ast)
1780                        {
1781                            llvm::SmallVector<char, 256> sv;
1782                            // Show full precision when printing float values
1783                            const unsigned format_precision = 0;
1784                            const unsigned format_max_padding = 100;
1785                            size_t item_bit_size = item_byte_size * 8;
1786
1787                            if (item_bit_size == ast->getTypeSize(ast->FloatTy))
1788                            {
1789                                llvm::APInt apint(item_bit_size, this->GetMaxU64(&offset, item_byte_size));
1790                                llvm::APFloat apfloat (ast->getFloatTypeSemantics(ast->FloatTy), apint);
1791                                apfloat.toString(sv, format_precision, format_max_padding);
1792                            }
1793                            else if (item_bit_size == ast->getTypeSize(ast->DoubleTy))
1794                            {
1795                                llvm::APInt apint;
1796                                if (GetAPInt (*this, &offset, item_byte_size, apint))
1797                                {
1798                                    llvm::APFloat apfloat (ast->getFloatTypeSemantics(ast->DoubleTy), apint);
1799                                    apfloat.toString(sv, format_precision, format_max_padding);
1800                                }
1801                            }
1802                            else if (item_bit_size == ast->getTypeSize(ast->LongDoubleTy))
1803                            {
1804                                llvm::APInt apint;
1805                                switch (target_sp->GetArchitecture().GetCore())
1806                                {
1807                                    case ArchSpec::eCore_x86_32_i386:
1808                                    case ArchSpec::eCore_x86_32_i486:
1809                                    case ArchSpec::eCore_x86_32_i486sx:
1810                                    case ArchSpec::eCore_x86_64_x86_64:
1811                                        // clang will assert when contructing the apfloat if we use a 16 byte integer value
1812                                        if (GetAPInt (*this, &offset, 10, apint))
1813                                        {
1814                                            llvm::APFloat apfloat (ast->getFloatTypeSemantics(ast->LongDoubleTy), apint);
1815                                            apfloat.toString(sv, format_precision, format_max_padding);
1816                                        }
1817                                        break;
1818
1819                                    default:
1820                                        if (GetAPInt (*this, &offset, item_byte_size, apint))
1821                                        {
1822                                            llvm::APFloat apfloat (ast->getFloatTypeSemantics(ast->LongDoubleTy), apint);
1823                                            apfloat.toString(sv, format_precision, format_max_padding);
1824                                        }
1825                                        break;
1826                                }
1827                            }
1828                            else if (item_bit_size == ast->getTypeSize(ast->HalfTy))
1829                            {
1830                                llvm::APInt apint(item_bit_size, this->GetU16(&offset));
1831                                llvm::APFloat apfloat (ast->getFloatTypeSemantics(ast->HalfTy), apint);
1832                                apfloat.toString(sv, format_precision, format_max_padding);
1833                            }
1834
1835                            if (!sv.empty())
1836                            {
1837                                s->Printf("%*.*s", (int)sv.size(), (int)sv.size(), sv.data());
1838                                used_apfloat = true;
1839                            }
1840                        }
1841                    }
1842                }
1843
1844                if (!used_apfloat)
1845                {
1846                    std::ostringstream ss;
1847                    if (item_byte_size == sizeof(float) || item_byte_size == 2)
1848                    {
1849                        float f;
1850                        if (item_byte_size == 2)
1851                        {
1852                            uint16_t half = this->GetU16(&offset);
1853                            f = half2float(half);
1854                        }
1855                        else
1856                        {
1857                            f = GetFloat (&offset);
1858                        }
1859                        ss.precision(std::numeric_limits<float>::digits10);
1860                        ss << f;
1861                    }
1862                    else if (item_byte_size == sizeof(double))
1863                    {
1864                        ss.precision(std::numeric_limits<double>::digits10);
1865                        ss << GetDouble(&offset);
1866                    }
1867                    else if (item_byte_size == sizeof(long double) || item_byte_size == 10)
1868                    {
1869                        ss.precision(std::numeric_limits<long double>::digits10);
1870                        ss << GetLongDouble(&offset);
1871                    }
1872                    else
1873                    {
1874                        s->Printf("error: unsupported byte size (%zu) for float format", item_byte_size);
1875                        return offset;
1876                    }
1877                    ss.flush();
1878                    s->Printf("%s", ss.str().c_str());
1879                }
1880            }
1881            break;
1882
1883        case eFormatUnicode16:
1884            s->Printf("U+%4.4x", GetU16 (&offset));
1885            break;
1886
1887        case eFormatUnicode32:
1888            s->Printf("U+0x%8.8x", GetU32 (&offset));
1889            break;
1890
1891        case eFormatAddressInfo:
1892            {
1893                addr_t addr = GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size, item_bit_offset);
1894                s->Printf("0x%*.*" PRIx64, (int)(2 * item_byte_size), (int)(2 * item_byte_size), addr);
1895                if (exe_scope)
1896                {
1897                    TargetSP target_sp (exe_scope->CalculateTarget());
1898                    lldb_private::Address so_addr;
1899                    if (target_sp)
1900                    {
1901                        if (target_sp->GetSectionLoadList().ResolveLoadAddress(addr, so_addr))
1902                        {
1903                            s->PutChar(' ');
1904                            so_addr.Dump (s,
1905                                          exe_scope,
1906                                          Address::DumpStyleResolvedDescription,
1907                                          Address::DumpStyleModuleWithFileAddress);
1908                        }
1909                        else
1910                        {
1911                            so_addr.SetOffset(addr);
1912                            so_addr.Dump (s, exe_scope, Address::DumpStyleResolvedPointerDescription);
1913                        }
1914                    }
1915                }
1916            }
1917            break;
1918
1919        case eFormatHexFloat:
1920            if (sizeof(float) == item_byte_size)
1921            {
1922                char float_cstr[256];
1923                llvm::APFloat ap_float (GetFloat (&offset));
1924                ap_float.convertToHexString (float_cstr, 0, false, llvm::APFloat::rmNearestTiesToEven);
1925                s->Printf ("%s", float_cstr);
1926                break;
1927            }
1928            else if (sizeof(double) == item_byte_size)
1929            {
1930                char float_cstr[256];
1931                llvm::APFloat ap_float (GetDouble (&offset));
1932                ap_float.convertToHexString (float_cstr, 0, false, llvm::APFloat::rmNearestTiesToEven);
1933                s->Printf ("%s", float_cstr);
1934                break;
1935            }
1936            else
1937            {
1938                s->Printf("error: unsupported byte size (%zu) for hex float format", item_byte_size);
1939                return offset;
1940            }
1941            break;
1942
1943// please keep the single-item formats below in sync with FormatManager::GetSingleItemFormat
1944// if you fail to do so, users will start getting different outputs depending on internal
1945// implementation details they should not care about ||
1946        case eFormatVectorOfChar:               //   ||
1947            s->PutChar('{');                    //   \/
1948            offset = Dump (s, offset, eFormatCharArray, 1, item_byte_size, item_byte_size, LLDB_INVALID_ADDRESS, 0, 0);
1949            s->PutChar('}');
1950            break;
1951
1952        case eFormatVectorOfSInt8:
1953            s->PutChar('{');
1954            offset = Dump (s, offset, eFormatDecimal, 1, item_byte_size, item_byte_size, LLDB_INVALID_ADDRESS, 0, 0);
1955            s->PutChar('}');
1956            break;
1957
1958        case eFormatVectorOfUInt8:
1959            s->PutChar('{');
1960            offset = Dump (s, offset, eFormatHex, 1, item_byte_size, item_byte_size, LLDB_INVALID_ADDRESS, 0, 0);
1961            s->PutChar('}');
1962            break;
1963
1964        case eFormatVectorOfSInt16:
1965            s->PutChar('{');
1966            offset = Dump (s, offset, eFormatDecimal, sizeof(uint16_t), item_byte_size / sizeof(uint16_t), item_byte_size / sizeof(uint16_t), LLDB_INVALID_ADDRESS, 0, 0);
1967            s->PutChar('}');
1968            break;
1969
1970        case eFormatVectorOfUInt16:
1971            s->PutChar('{');
1972            offset = Dump (s, offset, eFormatHex,     sizeof(uint16_t), item_byte_size / sizeof(uint16_t), item_byte_size / sizeof(uint16_t), LLDB_INVALID_ADDRESS, 0, 0);
1973            s->PutChar('}');
1974            break;
1975
1976        case eFormatVectorOfSInt32:
1977            s->PutChar('{');
1978            offset = Dump (s, offset, eFormatDecimal, sizeof(uint32_t), item_byte_size / sizeof(uint32_t), item_byte_size / sizeof(uint32_t), LLDB_INVALID_ADDRESS, 0, 0);
1979            s->PutChar('}');
1980            break;
1981
1982        case eFormatVectorOfUInt32:
1983            s->PutChar('{');
1984            offset = Dump (s, offset, eFormatHex,     sizeof(uint32_t), item_byte_size / sizeof(uint32_t), item_byte_size / sizeof(uint32_t), LLDB_INVALID_ADDRESS, 0, 0);
1985            s->PutChar('}');
1986            break;
1987
1988        case eFormatVectorOfSInt64:
1989            s->PutChar('{');
1990            offset = Dump (s, offset, eFormatDecimal, sizeof(uint64_t), item_byte_size / sizeof(uint64_t), item_byte_size / sizeof(uint64_t), LLDB_INVALID_ADDRESS, 0, 0);
1991            s->PutChar('}');
1992            break;
1993
1994        case eFormatVectorOfUInt64:
1995            s->PutChar('{');
1996            offset = Dump (s, offset, eFormatHex,     sizeof(uint64_t), item_byte_size / sizeof(uint64_t), item_byte_size / sizeof(uint64_t), LLDB_INVALID_ADDRESS, 0, 0);
1997            s->PutChar('}');
1998            break;
1999
2000        case eFormatVectorOfFloat32:
2001            s->PutChar('{');
2002            offset = Dump (s, offset, eFormatFloat,       4, item_byte_size / 4, item_byte_size / 4, LLDB_INVALID_ADDRESS, 0, 0);
2003            s->PutChar('}');
2004            break;
2005
2006        case eFormatVectorOfFloat64:
2007            s->PutChar('{');
2008            offset = Dump (s, offset, eFormatFloat,       8, item_byte_size / 8, item_byte_size / 8, LLDB_INVALID_ADDRESS, 0, 0);
2009            s->PutChar('}');
2010            break;
2011
2012        case eFormatVectorOfUInt128:
2013            s->PutChar('{');
2014            offset = Dump (s, offset, eFormatHex, 16, item_byte_size / 16, item_byte_size / 16, LLDB_INVALID_ADDRESS, 0, 0);
2015            s->PutChar('}');
2016            break;
2017        }
2018    }
2019
2020    if (item_format == eFormatBytesWithASCII && offset > line_start_offset)
2021    {
2022        s->Printf("%*s", static_cast<int>((num_per_line - (offset - line_start_offset)) * 3 + 2), "");
2023        Dump(s, line_start_offset, eFormatCharPrintable, 1, offset - line_start_offset, LLDB_INVALID_OFFSET, LLDB_INVALID_ADDRESS, 0, 0);
2024    }
2025    return offset;  // Return the offset at which we ended up
2026}
2027
2028//----------------------------------------------------------------------
2029// Dumps bytes from this object's data to the stream "s" starting
2030// "start_offset" bytes into this data, and ending with the byte
2031// before "end_offset". "base_addr" will be added to the offset
2032// into the dumped data when showing the offset into the data in the
2033// output information. "num_per_line" objects of type "type" will
2034// be dumped with the option to override the format for each object
2035// with "type_format". "type_format" is a printf style formatting
2036// string. If "type_format" is NULL, then an appropriate format
2037// string will be used for the supplied "type". If the stream "s"
2038// is NULL, then the output will be send to Log().
2039//----------------------------------------------------------------------
2040lldb::offset_t
2041DataExtractor::PutToLog
2042(
2043    Log *log,
2044    offset_t start_offset,
2045    offset_t length,
2046    uint64_t base_addr,
2047    uint32_t num_per_line,
2048    DataExtractor::Type type,
2049    const char *format
2050) const
2051{
2052    if (log == NULL)
2053        return start_offset;
2054
2055    offset_t offset;
2056    offset_t end_offset;
2057    uint32_t count;
2058    StreamString sstr;
2059    for (offset = start_offset, end_offset = offset + length, count = 0; ValidOffset(offset) && offset < end_offset; ++count)
2060    {
2061        if ((count % num_per_line) == 0)
2062        {
2063            // Print out any previous string
2064            if (sstr.GetSize() > 0)
2065            {
2066                log->Printf("%s", sstr.GetData());
2067                sstr.Clear();
2068            }
2069            // Reset string offset and fill the current line string with address:
2070            if (base_addr != LLDB_INVALID_ADDRESS)
2071                sstr.Printf("0x%8.8" PRIx64 ":", (uint64_t)(base_addr + (offset - start_offset)));
2072        }
2073
2074        switch (type)
2075        {
2076            case TypeUInt8:   sstr.Printf (format ? format : " %2.2x", GetU8(&offset)); break;
2077            case TypeChar:
2078                {
2079                    char ch = GetU8(&offset);
2080                    sstr.Printf (format ? format : " %c",    isprint(ch) ? ch : ' ');
2081                }
2082                break;
2083            case TypeUInt16:  sstr.Printf (format ? format : " %4.4x",       GetU16(&offset)); break;
2084            case TypeUInt32:  sstr.Printf (format ? format : " %8.8x",       GetU32(&offset)); break;
2085            case TypeUInt64:  sstr.Printf (format ? format : " %16.16" PRIx64,   GetU64(&offset)); break;
2086            case TypePointer: sstr.Printf (format ? format : " 0x%" PRIx64,      GetAddress(&offset)); break;
2087            case TypeULEB128: sstr.Printf (format ? format : " 0x%" PRIx64,      GetULEB128(&offset)); break;
2088            case TypeSLEB128: sstr.Printf (format ? format : " %" PRId64,        GetSLEB128(&offset)); break;
2089        }
2090    }
2091
2092    if (sstr.GetSize() > 0)
2093        log->Printf("%s", sstr.GetData());
2094
2095    return offset;  // Return the offset at which we ended up
2096}
2097
2098//----------------------------------------------------------------------
2099// DumpUUID
2100//
2101// Dump out a UUID starting at 'offset' bytes into the buffer
2102//----------------------------------------------------------------------
2103void
2104DataExtractor::DumpUUID (Stream *s, offset_t offset) const
2105{
2106    if (s)
2107    {
2108        const uint8_t *uuid_data = PeekData(offset, 16);
2109        if ( uuid_data )
2110        {
2111            lldb_private::UUID uuid(uuid_data, 16);
2112            uuid.Dump(s);
2113        }
2114        else
2115        {
2116            s->Printf("<not enough data for UUID at offset 0x%8.8" PRIx64 ">", offset);
2117        }
2118    }
2119}
2120
2121void
2122DataExtractor::DumpHexBytes (Stream *s,
2123                             const void *src,
2124                             size_t src_len,
2125                             uint32_t bytes_per_line,
2126                             addr_t base_addr)
2127{
2128    DataExtractor data (src, src_len, eByteOrderLittle, 4);
2129    data.Dump (s,
2130               0,               // Offset into "src"
2131               eFormatBytes,    // Dump as hex bytes
2132               1,               // Size of each item is 1 for single bytes
2133               src_len,         // Number of bytes
2134               bytes_per_line,  // Num bytes per line
2135               base_addr,       // Base address
2136               0, 0);           // Bitfield info
2137}
2138
2139size_t
2140DataExtractor::Copy (DataExtractor &dest_data) const
2141{
2142    if (m_data_sp.get())
2143    {
2144        // we can pass along the SP to the data
2145        dest_data.SetData(m_data_sp);
2146    }
2147    else
2148    {
2149        const uint8_t *base_ptr = m_start;
2150        size_t data_size = GetByteSize();
2151        dest_data.SetData(DataBufferSP(new DataBufferHeap(base_ptr, data_size)));
2152    }
2153    return GetByteSize();
2154}
2155
2156bool
2157DataExtractor::Append(DataExtractor& rhs)
2158{
2159    if (rhs.GetByteOrder() != GetByteOrder())
2160        return false;
2161
2162    if (rhs.GetByteSize() == 0)
2163        return true;
2164
2165    if (GetByteSize() == 0)
2166        return (rhs.Copy(*this) > 0);
2167
2168    size_t bytes = GetByteSize() + rhs.GetByteSize();
2169
2170    DataBufferHeap *buffer_heap_ptr = NULL;
2171    DataBufferSP buffer_sp(buffer_heap_ptr = new DataBufferHeap(bytes, 0));
2172
2173    if (buffer_sp.get() == NULL || buffer_heap_ptr == NULL)
2174        return false;
2175
2176    uint8_t* bytes_ptr = buffer_heap_ptr->GetBytes();
2177
2178    memcpy(bytes_ptr, GetDataStart(), GetByteSize());
2179    memcpy(bytes_ptr + GetByteSize(), rhs.GetDataStart(), rhs.GetByteSize());
2180
2181    SetData(buffer_sp);
2182
2183    return true;
2184}
2185
2186bool
2187DataExtractor::Append(void* buf, offset_t length)
2188{
2189    if (buf == NULL)
2190        return false;
2191
2192    if (length == 0)
2193        return true;
2194
2195    size_t bytes = GetByteSize() + length;
2196
2197    DataBufferHeap *buffer_heap_ptr = NULL;
2198    DataBufferSP buffer_sp(buffer_heap_ptr = new DataBufferHeap(bytes, 0));
2199
2200    if (buffer_sp.get() == NULL || buffer_heap_ptr == NULL)
2201        return false;
2202
2203    uint8_t* bytes_ptr = buffer_heap_ptr->GetBytes();
2204
2205    if (GetByteSize() > 0)
2206        memcpy(bytes_ptr, GetDataStart(), GetByteSize());
2207
2208    memcpy(bytes_ptr + GetByteSize(), buf, length);
2209
2210    SetData(buffer_sp);
2211
2212    return true;
2213}
2214