brintos

brintos / llvm-project-archived public Read only

0
0
Text · 35.1 KiB · a9aea16 Raw
1044 lines · cpp
1//===-- DataExtractor.cpp -------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "lldb/Utility/DataExtractor.h"10 11#include "lldb/lldb-defines.h"12#include "lldb/lldb-enumerations.h"13#include "lldb/lldb-forward.h"14#include "lldb/lldb-types.h"15 16#include "lldb/Utility/DataBuffer.h"17#include "lldb/Utility/DataBufferHeap.h"18#include "lldb/Utility/LLDBAssert.h"19#include "lldb/Utility/Log.h"20#include "lldb/Utility/Stream.h"21#include "lldb/Utility/StreamString.h"22#include "lldb/Utility/UUID.h"23 24#include "llvm/ADT/ArrayRef.h"25#include "llvm/ADT/SmallVector.h"26#include "llvm/ADT/StringExtras.h"27#include "llvm/Support/LEB128.h"28#include "llvm/Support/MD5.h"29#include "llvm/Support/MathExtras.h"30 31#include <algorithm>32#include <array>33#include <cassert>34#include <cstdint>35#include <string>36 37#include <cctype>38#include <cinttypes>39#include <cstring>40 41using namespace lldb;42using namespace lldb_private;43 44static inline uint16_t ReadInt16(const unsigned char *ptr, offset_t offset) {45  uint16_t value;46  memcpy(&value, ptr + offset, 2);47  return value;48}49 50static inline uint32_t ReadInt32(const unsigned char *ptr,51                                 offset_t offset = 0) {52  uint32_t value;53  memcpy(&value, ptr + offset, 4);54  return value;55}56 57static inline uint64_t ReadInt64(const unsigned char *ptr,58                                 offset_t offset = 0) {59  uint64_t value;60  memcpy(&value, ptr + offset, 8);61  return value;62}63 64static inline uint16_t ReadInt16(const void *ptr) {65  uint16_t value;66  memcpy(&value, ptr, 2);67  return value;68}69 70static inline uint16_t ReadSwapInt16(const unsigned char *ptr,71                                     offset_t offset) {72  uint16_t value;73  memcpy(&value, ptr + offset, 2);74  return llvm::byteswap<uint16_t>(value);75}76 77static inline uint32_t ReadSwapInt32(const unsigned char *ptr,78                                     offset_t offset) {79  uint32_t value;80  memcpy(&value, ptr + offset, 4);81  return llvm::byteswap<uint32_t>(value);82}83 84static inline uint64_t ReadSwapInt64(const unsigned char *ptr,85                                     offset_t offset) {86  uint64_t value;87  memcpy(&value, ptr + offset, 8);88  return llvm::byteswap<uint64_t>(value);89}90 91static inline uint16_t ReadSwapInt16(const void *ptr) {92  uint16_t value;93  memcpy(&value, ptr, 2);94  return llvm::byteswap<uint16_t>(value);95}96 97static inline uint32_t ReadSwapInt32(const void *ptr) {98  uint32_t value;99  memcpy(&value, ptr, 4);100  return llvm::byteswap<uint32_t>(value);101}102 103static inline uint64_t ReadSwapInt64(const void *ptr) {104  uint64_t value;105  memcpy(&value, ptr, 8);106  return llvm::byteswap<uint64_t>(value);107}108 109static inline uint64_t ReadMaxInt64(const uint8_t *data, size_t byte_size,110                                    ByteOrder byte_order) {111  uint64_t res = 0;112  if (byte_order == eByteOrderBig)113    for (size_t i = 0; i < byte_size; ++i)114      res = (res << 8) | data[i];115  else {116    assert(byte_order == eByteOrderLittle);117    for (size_t i = 0; i < byte_size; ++i)118      res = (res << 8) | data[byte_size - 1 - i];119  }120  return res;121}122 123DataExtractor::DataExtractor()124    : m_byte_order(endian::InlHostByteOrder()), m_addr_size(sizeof(void *)),125      m_data_sp() {}126 127// This constructor allows us to use data that is owned by someone else. The128// data must stay around as long as this object is valid.129DataExtractor::DataExtractor(const void *data, offset_t length,130                             ByteOrder endian, uint32_t addr_size,131                             uint32_t target_byte_size /*=1*/)132    : m_start(const_cast<uint8_t *>(static_cast<const uint8_t *>(data))),133      m_end(const_cast<uint8_t *>(static_cast<const uint8_t *>(data)) + length),134      m_byte_order(endian), m_addr_size(addr_size), m_data_sp(),135      m_target_byte_size(target_byte_size) {136  assert(addr_size >= 1 && addr_size <= 8);137}138 139// Make a shared pointer reference to the shared data in "data_sp" and set the140// endian swapping setting to "swap", and the address size to "addr_size". The141// shared data reference will ensure the data lives as long as any142// DataExtractor objects exist that have a reference to this data.143DataExtractor::DataExtractor(const DataBufferSP &data_sp, ByteOrder endian,144                             uint32_t addr_size,145                             uint32_t target_byte_size /*=1*/)146    : m_byte_order(endian), m_addr_size(addr_size), m_data_sp(),147      m_target_byte_size(target_byte_size) {148  assert(addr_size >= 1 && addr_size <= 8);149  SetData(data_sp);150}151 152// Initialize this object with a subset of the data bytes in "data". If "data"153// contains shared data, then a reference to this shared data will added and154// the shared data will stay around as long as any object contains a reference155// to that data. The endian swap and address size settings are copied from156// "data".157DataExtractor::DataExtractor(const DataExtractor &data, offset_t offset,158                             offset_t length, uint32_t target_byte_size /*=1*/)159    : m_byte_order(data.m_byte_order), m_addr_size(data.m_addr_size),160      m_data_sp(), m_target_byte_size(target_byte_size) {161  assert(m_addr_size >= 1 && m_addr_size <= 8);162  if (data.ValidOffset(offset)) {163    offset_t bytes_available = data.GetByteSize() - offset;164    if (length > bytes_available)165      length = bytes_available;166    SetData(data, offset, length);167  }168}169 170DataExtractor::DataExtractor(const DataExtractor &rhs)171    : m_start(rhs.m_start), m_end(rhs.m_end), m_byte_order(rhs.m_byte_order),172      m_addr_size(rhs.m_addr_size), m_data_sp(rhs.m_data_sp),173      m_target_byte_size(rhs.m_target_byte_size) {174  assert(m_addr_size >= 1 && m_addr_size <= 8);175}176 177// Assignment operator178const DataExtractor &DataExtractor::operator=(const DataExtractor &rhs) {179  if (this != &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  return *this;187}188 189DataExtractor::~DataExtractor() = default;190 191// Clears the object contents back to a default invalid state, and release any192// references to shared data that this object may contain.193void DataExtractor::Clear() {194  m_start = nullptr;195  m_end = nullptr;196  m_byte_order = endian::InlHostByteOrder();197  m_addr_size = sizeof(void *);198  m_data_sp.reset();199}200 201// If this object contains shared data, this function returns the offset into202// that shared data. Else zero is returned.203size_t DataExtractor::GetSharedDataOffset() const {204  if (m_start != nullptr) {205    const DataBuffer *data = m_data_sp.get();206    if (data != nullptr) {207      const uint8_t *data_bytes = data->GetBytes();208      if (data_bytes != nullptr) {209        assert(m_start >= data_bytes);210        return m_start - data_bytes;211      }212    }213  }214  return 0;215}216 217// Set the data with which this object will extract from to data starting at218// BYTES and set the length of the data to LENGTH bytes long. The data is219// externally owned must be around at least as long as this object points to220// the data. No copy of the data is made, this object just refers to this data221// and can extract from it. If this object refers to any shared data upon222// entry, the reference to that data will be released. Is SWAP is set to true,223// any data extracted will be endian swapped.224lldb::offset_t DataExtractor::SetData(const void *bytes, offset_t length,225                                      ByteOrder endian) {226  m_byte_order = endian;227  m_data_sp.reset();228  if (bytes == nullptr || length == 0) {229    m_start = nullptr;230    m_end = nullptr;231  } else {232    m_start = const_cast<uint8_t *>(static_cast<const uint8_t *>(bytes));233    m_end = m_start + length;234  }235  return GetByteSize();236}237 238// Assign the data for this object to be a subrange in "data" starting239// "data_offset" bytes into "data" and ending "data_length" bytes later. If240// "data_offset" is not a valid offset into "data", then this object will241// contain no bytes. If "data_offset" is within "data" yet "data_length" is too242// large, the length will be capped at the number of bytes remaining in "data".243// If "data" contains a shared pointer to other data, then a ref counted244// pointer to that data will be made in this object. If "data" doesn't contain245// a shared pointer to data, then the bytes referred to in "data" will need to246// exist at least as long as this object refers to those bytes. The address247// size and endian swap settings are copied from the current values in "data".248lldb::offset_t DataExtractor::SetData(const DataExtractor &data,249                                      offset_t data_offset,250                                      offset_t data_length) {251  m_addr_size = data.m_addr_size;252  assert(m_addr_size >= 1 && m_addr_size <= 8);253  // If "data" contains shared pointer to data, then we can use that254  if (data.m_data_sp) {255    m_byte_order = data.m_byte_order;256    return SetData(data.m_data_sp, data.GetSharedDataOffset() + data_offset,257                   data_length);258  }259 260  // We have a DataExtractor object that just has a pointer to bytes261  if (data.ValidOffset(data_offset)) {262    if (data_length > data.GetByteSize() - data_offset)263      data_length = data.GetByteSize() - data_offset;264    return SetData(data.GetDataStart() + data_offset, data_length,265                   data.GetByteOrder());266  }267  return 0;268}269 270// Assign the data for this object to be a subrange of the shared data in271// "data_sp" starting "data_offset" bytes into "data_sp" and ending272// "data_length" bytes later. If "data_offset" is not a valid offset into273// "data_sp", then this object will contain no bytes. If "data_offset" is274// within "data_sp" yet "data_length" is too large, the length will be capped275// at the number of bytes remaining in "data_sp". A ref counted pointer to the276// data in "data_sp" will be made in this object IF the number of bytes this277// object refers to in greater than zero (if at least one byte was available278// starting at "data_offset") to ensure the data stays around as long as it is279// needed. The address size and endian swap settings will remain unchanged from280// their current settings.281lldb::offset_t DataExtractor::SetData(const DataBufferSP &data_sp,282                                      offset_t data_offset,283                                      offset_t data_length) {284  m_start = m_end = nullptr;285 286  if (data_length > 0) {287    m_data_sp = data_sp;288    if (data_sp) {289      const size_t data_size = data_sp->GetByteSize();290      if (data_offset < data_size) {291        m_start = data_sp->GetBytes() + data_offset;292        const size_t bytes_left = data_size - data_offset;293        // Cap the length of we asked for too many294        if (data_length <= bytes_left)295          m_end = m_start + data_length; // We got all the bytes we wanted296        else297          m_end = m_start + bytes_left; // Not all the bytes requested were298                                        // available in the shared data299      }300    }301  }302 303  size_t new_size = GetByteSize();304 305  // Don't hold a shared pointer to the data buffer if we don't share any valid306  // bytes in the shared buffer.307  if (new_size == 0)308    m_data_sp.reset();309 310  return new_size;311}312 313// Extract a single unsigned char from the binary data and update the offset314// pointed to by "offset_ptr".315//316// RETURNS the byte that was extracted, or zero on failure.317uint8_t DataExtractor::GetU8(offset_t *offset_ptr) const {318  const uint8_t *data = static_cast<const uint8_t *>(GetData(offset_ptr, 1));319  if (data)320    return *data;321  return 0;322}323 324// Extract "count" unsigned chars from the binary data and update the offset325// pointed to by "offset_ptr". The extracted data is copied into "dst".326//327// RETURNS the non-nullptr buffer pointer upon successful extraction of328// all the requested bytes, or nullptr when the data is not available in the329// buffer due to being out of bounds, or insufficient data.330void *DataExtractor::GetU8(offset_t *offset_ptr, void *dst,331                           uint32_t count) const {332  const uint8_t *data =333      static_cast<const uint8_t *>(GetData(offset_ptr, count));334  if (data) {335    // Copy the data into the buffer336    memcpy(dst, data, count);337    // Return a non-nullptr pointer to the converted data as an indicator of338    // success339    return dst;340  }341  return nullptr;342}343 344// Extract a single uint16_t from the data and update the offset pointed to by345// "offset_ptr".346//347// RETURNS the uint16_t that was extracted, or zero on failure.348uint16_t DataExtractor::GetU16(offset_t *offset_ptr) const {349  uint16_t val = 0;350  const uint8_t *data =351      static_cast<const uint8_t *>(GetData(offset_ptr, sizeof(val)));352  if (data) {353    if (m_byte_order != endian::InlHostByteOrder())354      val = ReadSwapInt16(data);355    else356      val = ReadInt16(data);357  }358  return val;359}360 361uint16_t DataExtractor::GetU16_unchecked(offset_t *offset_ptr) const {362  uint16_t val;363  if (m_byte_order == endian::InlHostByteOrder())364    val = ReadInt16(m_start, *offset_ptr);365  else366    val = ReadSwapInt16(m_start, *offset_ptr);367  *offset_ptr += sizeof(val);368  return val;369}370 371uint32_t DataExtractor::GetU32_unchecked(offset_t *offset_ptr) const {372  uint32_t val;373  if (m_byte_order == endian::InlHostByteOrder())374    val = ReadInt32(m_start, *offset_ptr);375  else376    val = ReadSwapInt32(m_start, *offset_ptr);377  *offset_ptr += sizeof(val);378  return val;379}380 381uint64_t DataExtractor::GetU64_unchecked(offset_t *offset_ptr) const {382  uint64_t val;383  if (m_byte_order == endian::InlHostByteOrder())384    val = ReadInt64(m_start, *offset_ptr);385  else386    val = ReadSwapInt64(m_start, *offset_ptr);387  *offset_ptr += sizeof(val);388  return val;389}390 391// Extract "count" uint16_t values from the binary data and update the offset392// pointed to by "offset_ptr". The extracted data is copied into "dst".393//394// RETURNS the non-nullptr buffer pointer upon successful extraction of395// all the requested bytes, or nullptr when the data is not available in the396// buffer due to being out of bounds, or insufficient data.397void *DataExtractor::GetU16(offset_t *offset_ptr, void *void_dst,398                            uint32_t count) const {399  const size_t src_size = sizeof(uint16_t) * count;400  const uint16_t *src =401      static_cast<const uint16_t *>(GetData(offset_ptr, src_size));402  if (src) {403    if (m_byte_order != endian::InlHostByteOrder()) {404      uint16_t *dst_pos = static_cast<uint16_t *>(void_dst);405      uint16_t *dst_end = dst_pos + count;406      const uint16_t *src_pos = src;407      while (dst_pos < dst_end) {408        *dst_pos = ReadSwapInt16(src_pos);409        ++dst_pos;410        ++src_pos;411      }412    } else {413      memcpy(void_dst, src, src_size);414    }415    // Return a non-nullptr pointer to the converted data as an indicator of416    // success417    return void_dst;418  }419  return nullptr;420}421 422// Extract a single uint32_t from the data and update the offset pointed to by423// "offset_ptr".424//425// RETURNS the uint32_t that was extracted, or zero on failure.426uint32_t DataExtractor::GetU32(offset_t *offset_ptr) const {427  uint32_t val = 0;428  const uint8_t *data =429      static_cast<const uint8_t *>(GetData(offset_ptr, sizeof(val)));430  if (data) {431    if (m_byte_order != endian::InlHostByteOrder()) {432      val = ReadSwapInt32(data);433    } else {434      memcpy(&val, data, 4);435    }436  }437  return val;438}439 440// Extract "count" uint32_t values from the binary data and update the offset441// pointed to by "offset_ptr". The extracted data is copied into "dst".442//443// RETURNS the non-nullptr buffer pointer upon successful extraction of444// all the requested bytes, or nullptr when the data is not available in the445// buffer due to being out of bounds, or insufficient data.446void *DataExtractor::GetU32(offset_t *offset_ptr, void *void_dst,447                            uint32_t count) const {448  const size_t src_size = sizeof(uint32_t) * count;449  const uint32_t *src =450      static_cast<const uint32_t *>(GetData(offset_ptr, src_size));451  if (src) {452    if (m_byte_order != endian::InlHostByteOrder()) {453      uint32_t *dst_pos = static_cast<uint32_t *>(void_dst);454      uint32_t *dst_end = dst_pos + count;455      const uint32_t *src_pos = src;456      while (dst_pos < dst_end) {457        *dst_pos = ReadSwapInt32(src_pos);458        ++dst_pos;459        ++src_pos;460      }461    } else {462      memcpy(void_dst, src, src_size);463    }464    // Return a non-nullptr pointer to the converted data as an indicator of465    // success466    return void_dst;467  }468  return nullptr;469}470 471// Extract a single uint64_t from the data and update the offset pointed to by472// "offset_ptr".473//474// RETURNS the uint64_t that was extracted, or zero on failure.475uint64_t DataExtractor::GetU64(offset_t *offset_ptr) const {476  uint64_t val = 0;477  const uint8_t *data =478      static_cast<const uint8_t *>(GetData(offset_ptr, sizeof(val)));479  if (data) {480    if (m_byte_order != endian::InlHostByteOrder()) {481      val = ReadSwapInt64(data);482    } else {483      memcpy(&val, data, 8);484    }485  }486  return val;487}488 489// GetU64490//491// Get multiple consecutive 64 bit values. Return true if the entire read492// succeeds and increment the offset pointed to by offset_ptr, else return493// false and leave the offset pointed to by offset_ptr unchanged.494void *DataExtractor::GetU64(offset_t *offset_ptr, void *void_dst,495                            uint32_t count) const {496  const size_t src_size = sizeof(uint64_t) * count;497  const uint64_t *src =498      static_cast<const uint64_t *>(GetData(offset_ptr, src_size));499  if (src) {500    if (m_byte_order != endian::InlHostByteOrder()) {501      uint64_t *dst_pos = static_cast<uint64_t *>(void_dst);502      uint64_t *dst_end = dst_pos + count;503      const uint64_t *src_pos = src;504      while (dst_pos < dst_end) {505        *dst_pos = ReadSwapInt64(src_pos);506        ++dst_pos;507        ++src_pos;508      }509    } else {510      memcpy(void_dst, src, src_size);511    }512    // Return a non-nullptr pointer to the converted data as an indicator of513    // success514    return void_dst;515  }516  return nullptr;517}518 519uint32_t DataExtractor::GetMaxU32(offset_t *offset_ptr,520                                  size_t byte_size) const {521  lldbassert(byte_size > 0 && byte_size <= 4 && "GetMaxU32 invalid byte_size!");522  return GetMaxU64(offset_ptr, byte_size);523}524 525uint64_t DataExtractor::GetMaxU64(offset_t *offset_ptr,526                                  size_t byte_size) const {527  lldbassert(byte_size > 0 && byte_size <= 8 && "GetMaxU64 invalid byte_size!");528  switch (byte_size) {529  case 1:530    return GetU8(offset_ptr);531  case 2:532    return GetU16(offset_ptr);533  case 4:534    return GetU32(offset_ptr);535  case 8:536    return GetU64(offset_ptr);537  default: {538    // General case.539    const uint8_t *data =540        static_cast<const uint8_t *>(GetData(offset_ptr, byte_size));541    if (data == nullptr)542      return 0;543    return ReadMaxInt64(data, byte_size, m_byte_order);544  }545  }546  return 0;547}548 549uint64_t DataExtractor::GetMaxU64_unchecked(offset_t *offset_ptr,550                                            size_t byte_size) const {551  switch (byte_size) {552  case 1:553    return GetU8_unchecked(offset_ptr);554  case 2:555    return GetU16_unchecked(offset_ptr);556  case 4:557    return GetU32_unchecked(offset_ptr);558  case 8:559    return GetU64_unchecked(offset_ptr);560  default: {561    uint64_t res = ReadMaxInt64(&m_start[*offset_ptr], byte_size, m_byte_order);562    *offset_ptr += byte_size;563    return res;564  }565  }566  return 0;567}568 569int64_t DataExtractor::GetMaxS64(offset_t *offset_ptr, size_t byte_size) const {570  uint64_t u64 = GetMaxU64(offset_ptr, byte_size);571  return llvm::SignExtend64(u64, 8 * byte_size);572}573 574uint64_t DataExtractor::GetMaxU64Bitfield(offset_t *offset_ptr, size_t size,575                                          uint32_t bitfield_bit_size,576                                          uint32_t bitfield_bit_offset) const {577  assert(bitfield_bit_size <= 64);578  uint64_t uval64 = GetMaxU64(offset_ptr, size);579 580  if (bitfield_bit_size == 0)581    return uval64;582 583  int32_t lsbcount = bitfield_bit_offset;584  if (m_byte_order == eByteOrderBig)585    lsbcount = size * 8 - bitfield_bit_offset - bitfield_bit_size;586 587  if (lsbcount > 0)588    uval64 >>= lsbcount;589 590  uint64_t bitfield_mask =591      (bitfield_bit_size == 64592           ? std::numeric_limits<uint64_t>::max()593           : ((static_cast<uint64_t>(1) << bitfield_bit_size) - 1));594  if (!bitfield_mask && bitfield_bit_offset == 0 && bitfield_bit_size == 64)595    return uval64;596 597  uval64 &= bitfield_mask;598 599  return uval64;600}601 602int64_t DataExtractor::GetMaxS64Bitfield(offset_t *offset_ptr, size_t size,603                                         uint32_t bitfield_bit_size,604                                         uint32_t bitfield_bit_offset) const {605  assert(size >= 1 && "GetMaxS64Bitfield size must be >= 1");606  assert(size <= 8 && "GetMaxS64Bitfield size must be <= 8");607  int64_t sval64 = GetMaxS64(offset_ptr, size);608  if (bitfield_bit_size == 0)609    return sval64;610  int32_t lsbcount = bitfield_bit_offset;611  if (m_byte_order == eByteOrderBig)612    lsbcount = size * 8 - bitfield_bit_offset - bitfield_bit_size;613  if (lsbcount > 0)614    sval64 >>= lsbcount;615  uint64_t bitfield_mask = llvm::maskTrailingOnes<uint64_t>(bitfield_bit_size);616  sval64 &= bitfield_mask;617  // sign extend if needed618  if (sval64 & ((static_cast<uint64_t>(1)) << (bitfield_bit_size - 1)))619    sval64 |= ~bitfield_mask;620  return sval64;621}622 623float DataExtractor::GetFloat(offset_t *offset_ptr) const {624  return Get<float>(offset_ptr, 0.0f);625}626 627double DataExtractor::GetDouble(offset_t *offset_ptr) const {628  return Get<double>(offset_ptr, 0.0);629}630 631long double DataExtractor::GetLongDouble(offset_t *offset_ptr) const {632  long double val = 0.0;633#if defined(__i386__) || defined(__amd64__) || defined(__x86_64__) ||          \634    defined(_M_IX86) || defined(_M_IA64) || defined(_M_X64)635  *offset_ptr += CopyByteOrderedData(*offset_ptr, 10, &val, sizeof(val),636                                     endian::InlHostByteOrder());637#else638  *offset_ptr += CopyByteOrderedData(*offset_ptr, sizeof(val), &val,639                                     sizeof(val), endian::InlHostByteOrder());640#endif641  return val;642}643 644// Extract a single address from the data and update the offset pointed to by645// "offset_ptr". The size of the extracted address comes from the646// "this->m_addr_size" member variable and should be set correctly prior to647// extracting any address values.648//649// RETURNS the address that was extracted, or zero on failure.650uint64_t DataExtractor::GetAddress(offset_t *offset_ptr) const {651  assert(m_addr_size >= 1 && m_addr_size <= 8);652  return GetMaxU64(offset_ptr, m_addr_size);653}654 655uint64_t DataExtractor::GetAddress_unchecked(offset_t *offset_ptr) const {656  assert(m_addr_size >= 1 && m_addr_size <= 8);657  return GetMaxU64_unchecked(offset_ptr, m_addr_size);658}659 660size_t DataExtractor::ExtractBytes(offset_t offset, offset_t length,661                                   ByteOrder dst_byte_order, void *dst) const {662  const uint8_t *src = PeekData(offset, length);663  if (src) {664    if (dst_byte_order != GetByteOrder()) {665      for (uint32_t i = 0; i < length; ++i)666        (static_cast<uint8_t *>(dst))[i] = src[length - i - 1];667    } else668      ::memcpy(dst, src, length);669    return length;670  }671  return 0;672}673 674// Extract data as it exists in target memory675lldb::offset_t DataExtractor::CopyData(offset_t offset, offset_t length,676                                       void *dst) const {677  const uint8_t *src = PeekData(offset, length);678  if (src) {679    ::memcpy(dst, src, length);680    return length;681  }682  return 0;683}684 685// Extract data and swap if needed when doing the copy686lldb::offset_t687DataExtractor::CopyByteOrderedData(offset_t src_offset, offset_t src_len,688                                   void *dst_void_ptr, offset_t dst_len,689                                   ByteOrder dst_byte_order) const {690  // Validate the source info691  if (!ValidOffsetForDataOfSize(src_offset, src_len))692    assert(ValidOffsetForDataOfSize(src_offset, src_len));693  assert(src_len > 0);694  assert(m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle);695 696  // Validate the destination info697  assert(dst_void_ptr != nullptr);698  assert(dst_len > 0);699  assert(dst_byte_order == eByteOrderBig || dst_byte_order == eByteOrderLittle);700 701  // Validate that only a word- or register-sized dst is byte swapped702  assert(dst_byte_order == m_byte_order || dst_len == 1 || dst_len == 2 ||703         dst_len == 4 || dst_len == 8 || dst_len == 10 || dst_len == 16 ||704         dst_len == 32);705 706  // Must have valid byte orders set in this object and for destination707  if (!(dst_byte_order == eByteOrderBig ||708        dst_byte_order == eByteOrderLittle) ||709      !(m_byte_order == eByteOrderBig || m_byte_order == eByteOrderLittle))710    return 0;711 712  uint8_t *dst = static_cast<uint8_t *>(dst_void_ptr);713  const uint8_t *src = PeekData(src_offset, src_len);714  if (src) {715    if (dst_len >= src_len) {716      // We are copying the entire value from src into dst. Calculate how many,717      // if any, zeroes we need for the most significant bytes if "dst_len" is718      // greater than "src_len"...719      const size_t num_zeroes = dst_len - src_len;720      if (dst_byte_order == eByteOrderBig) {721        // Big endian, so we lead with zeroes...722        if (num_zeroes > 0)723          ::memset(dst, 0, num_zeroes);724        // Then either copy or swap the rest725        if (m_byte_order == eByteOrderBig) {726          ::memcpy(dst + num_zeroes, src, src_len);727        } else {728          for (uint32_t i = 0; i < src_len; ++i)729            dst[i + num_zeroes] = src[src_len - 1 - i];730        }731      } else {732        // Little endian destination, so we lead the value bytes733        if (m_byte_order == eByteOrderBig) {734          for (uint32_t i = 0; i < src_len; ++i)735            dst[i] = src[src_len - 1 - i];736        } else {737          ::memcpy(dst, src, src_len);738        }739        // And zero the rest...740        if (num_zeroes > 0)741          ::memset(dst + src_len, 0, num_zeroes);742      }743      return src_len;744    } else {745      // We are only copying some of the value from src into dst..746 747      if (dst_byte_order == eByteOrderBig) {748        // Big endian dst749        if (m_byte_order == eByteOrderBig) {750          // Big endian dst, with big endian src751          ::memcpy(dst, src + (src_len - dst_len), dst_len);752        } else {753          // Big endian dst, with little endian src754          for (uint32_t i = 0; i < dst_len; ++i)755            dst[i] = src[dst_len - 1 - i];756        }757      } else {758        // Little endian dst759        if (m_byte_order == eByteOrderBig) {760          // Little endian dst, with big endian src761          for (uint32_t i = 0; i < dst_len; ++i)762            dst[i] = src[src_len - 1 - i];763        } else {764          // Little endian dst, with big endian src765          ::memcpy(dst, src, dst_len);766        }767      }768      return dst_len;769    }770  }771  return 0;772}773 774// Extracts a variable length NULL terminated C string from the data at the775// offset pointed to by "offset_ptr".  The "offset_ptr" will be updated with776// the offset of the byte that follows the NULL terminator byte.777//778// If the offset pointed to by "offset_ptr" is out of bounds, or if "length" is779// non-zero and there aren't enough available bytes, nullptr will be returned780// and "offset_ptr" will not be updated.781const char *DataExtractor::GetCStr(offset_t *offset_ptr) const {782  const char *start = reinterpret_cast<const char *>(PeekData(*offset_ptr, 1));783  // Already at the end of the data.784  if (!start)785    return nullptr;786 787  const char *end = reinterpret_cast<const char *>(m_end);788 789  // Check all bytes for a null terminator that terminates a C string.790  const char *terminator_or_end = std::find(start, end, '\0');791 792  // We didn't find a null terminator, so return nullptr to indicate that there793  // is no valid C string at that offset.794  if (terminator_or_end == end)795    return nullptr;796 797  // Update offset_ptr for the caller to point to the data behind the798  // terminator (which is 1 byte long).799  *offset_ptr += (terminator_or_end - start + 1UL);800  return start;801}802 803// Extracts a NULL terminated C string from the fixed length field of length804// "len" at the offset pointed to by "offset_ptr". The "offset_ptr" will be805// updated with the offset of the byte that follows the fixed length field.806//807// If the offset pointed to by "offset_ptr" is out of bounds, or if the offset808// plus the length of the field is out of bounds, or if the field does not809// contain a NULL terminator byte, nullptr will be returned and "offset_ptr"810// will not be updated.811const char *DataExtractor::GetCStr(offset_t *offset_ptr, offset_t len) const {812  const char *cstr = reinterpret_cast<const char *>(PeekData(*offset_ptr, len));813  if (cstr != nullptr) {814    if (memchr(cstr, '\0', len) == nullptr) {815      return nullptr;816    }817    *offset_ptr += len;818    return cstr;819  }820  return nullptr;821}822 823// Peeks at a string in the contained data. No verification is done to make824// sure the entire string lies within the bounds of this object's data, only825// "offset" is verified to be a valid offset.826//827// Returns a valid C string pointer if "offset" is a valid offset in this828// object's data, else nullptr is returned.829const char *DataExtractor::PeekCStr(offset_t offset) const {830  return reinterpret_cast<const char *>(PeekData(offset, 1));831}832 833// Extracts an unsigned LEB128 number from this object's data starting at the834// offset pointed to by "offset_ptr". The offset pointed to by "offset_ptr"835// will be updated with the offset of the byte following the last extracted836// byte.837//838// Returned the extracted integer value.839uint64_t DataExtractor::GetULEB128(offset_t *offset_ptr) const {840  const uint8_t *src = PeekData(*offset_ptr, 1);841  if (src == nullptr)842    return 0;843 844  unsigned byte_count = 0;845  uint64_t result = llvm::decodeULEB128(src, &byte_count, m_end);846  *offset_ptr += byte_count;847  return result;848}849 850// Extracts an signed LEB128 number from this object's data starting at the851// offset pointed to by "offset_ptr". The offset pointed to by "offset_ptr"852// will be updated with the offset of the byte following the last extracted853// byte.854//855// Returned the extracted integer value.856int64_t DataExtractor::GetSLEB128(offset_t *offset_ptr) const {857  const uint8_t *src = PeekData(*offset_ptr, 1);858  if (src == nullptr)859    return 0;860 861  unsigned byte_count = 0;862  int64_t result = llvm::decodeSLEB128(src, &byte_count, m_end);863  *offset_ptr += byte_count;864  return result;865}866 867// Skips a ULEB128 number (signed or unsigned) from this object's data starting868// at the offset pointed to by "offset_ptr". The offset pointed to by869// "offset_ptr" will be updated with the offset of the byte following the last870// extracted byte.871//872// Returns the number of bytes consumed during the extraction.873uint32_t DataExtractor::Skip_LEB128(offset_t *offset_ptr) const {874  uint32_t bytes_consumed = 0;875  const uint8_t *src = PeekData(*offset_ptr, 1);876  if (src == nullptr)877    return 0;878 879  const uint8_t *end = m_end;880 881  if (src < end) {882    const uint8_t *src_pos = src;883    while ((src_pos < end) && (*src_pos++ & 0x80))884      ++bytes_consumed;885    *offset_ptr += src_pos - src;886  }887  return bytes_consumed;888}889 890// Dumps bytes from this object's data to the stream "s" starting891// "start_offset" bytes into this data, and ending with the byte before892// "end_offset". "base_addr" will be added to the offset into the dumped data893// when showing the offset into the data in the output information.894// "num_per_line" objects of type "type" will be dumped with the option to895// override the format for each object with "type_format". "type_format" is a896// printf style formatting string. If "type_format" is nullptr, then an897// appropriate format string will be used for the supplied "type". If the898// stream "s" is nullptr, then the output will be send to Log().899lldb::offset_t DataExtractor::PutToLog(Log *log, offset_t start_offset,900                                       offset_t length, uint64_t base_addr,901                                       uint32_t num_per_line,902                                       DataExtractor::Type type) const {903  if (log == nullptr)904    return start_offset;905 906  offset_t offset;907  offset_t end_offset;908  uint32_t count;909  StreamString sstr;910  for (offset = start_offset, end_offset = offset + length, count = 0;911       ValidOffset(offset) && offset < end_offset; ++count) {912    if ((count % num_per_line) == 0) {913      // Print out any previous string914      if (sstr.GetSize() > 0) {915        log->PutString(sstr.GetString());916        sstr.Clear();917      }918      // Reset string offset and fill the current line string with address:919      if (base_addr != LLDB_INVALID_ADDRESS)920        sstr.Printf("0x%8.8" PRIx64 ":",921                    static_cast<uint64_t>(base_addr + (offset - start_offset)));922    }923 924    switch (type) {925    case TypeUInt8:926      sstr.Printf(" %2.2x", GetU8(&offset));927      break;928    case TypeChar: {929      char ch = GetU8(&offset);930      sstr.Printf(" %c", llvm::isPrint(ch) ? ch : ' ');931    } break;932    case TypeUInt16:933      sstr.Printf(" %4.4x", GetU16(&offset));934      break;935    case TypeUInt32:936      sstr.Printf(" %8.8x", GetU32(&offset));937      break;938    case TypeUInt64:939      sstr.Printf(" %16.16" PRIx64, GetU64(&offset));940      break;941    case TypePointer:942      sstr.Printf(" 0x%" PRIx64, GetAddress(&offset));943      break;944    case TypeULEB128:945      sstr.Printf(" 0x%" PRIx64, GetULEB128(&offset));946      break;947    case TypeSLEB128:948      sstr.Printf(" %" PRId64, GetSLEB128(&offset));949      break;950    }951  }952 953  if (!sstr.Empty())954    log->PutString(sstr.GetString());955 956  return offset; // Return the offset at which we ended up957}958 959size_t DataExtractor::Copy(DataExtractor &dest_data) const {960  if (m_data_sp) {961    // we can pass along the SP to the data962    dest_data.SetData(m_data_sp);963  } else {964    const uint8_t *base_ptr = m_start;965    size_t data_size = GetByteSize();966    dest_data.SetData(DataBufferSP(new DataBufferHeap(base_ptr, data_size)));967  }968  return GetByteSize();969}970 971bool DataExtractor::Append(DataExtractor &rhs) {972  if (rhs.GetByteOrder() != GetByteOrder())973    return false;974 975  if (rhs.GetByteSize() == 0)976    return true;977 978  if (GetByteSize() == 0)979    return (rhs.Copy(*this) > 0);980 981  size_t bytes = GetByteSize() + rhs.GetByteSize();982 983  DataBufferHeap *buffer_heap_ptr = nullptr;984  DataBufferSP buffer_sp(buffer_heap_ptr = new DataBufferHeap(bytes, 0));985 986  if (!buffer_sp || buffer_heap_ptr == nullptr)987    return false;988 989  uint8_t *bytes_ptr = buffer_heap_ptr->GetBytes();990 991  memcpy(bytes_ptr, GetDataStart(), GetByteSize());992  memcpy(bytes_ptr + GetByteSize(), rhs.GetDataStart(), rhs.GetByteSize());993 994  SetData(buffer_sp);995 996  return true;997}998 999bool DataExtractor::Append(void *buf, offset_t length) {1000  if (buf == nullptr)1001    return false;1002 1003  if (length == 0)1004    return true;1005 1006  size_t bytes = GetByteSize() + length;1007 1008  DataBufferHeap *buffer_heap_ptr = nullptr;1009  DataBufferSP buffer_sp(buffer_heap_ptr = new DataBufferHeap(bytes, 0));1010 1011  if (!buffer_sp || buffer_heap_ptr == nullptr)1012    return false;1013 1014  uint8_t *bytes_ptr = buffer_heap_ptr->GetBytes();1015 1016  if (GetByteSize() > 0)1017    memcpy(bytes_ptr, GetDataStart(), GetByteSize());1018 1019  memcpy(bytes_ptr + GetByteSize(), buf, length);1020 1021  SetData(buffer_sp);1022 1023  return true;1024}1025 1026void DataExtractor::Checksum(llvm::SmallVectorImpl<uint8_t> &dest,1027                             uint64_t max_data) {1028  if (max_data == 0)1029    max_data = GetByteSize();1030  else1031    max_data = std::min(max_data, GetByteSize());1032 1033  llvm::MD5 md5;1034 1035  const llvm::ArrayRef<uint8_t> data(GetDataStart(), max_data);1036  md5.update(data);1037 1038  llvm::MD5::MD5Result result;1039  md5.final(result);1040 1041  dest.clear();1042  dest.append(result.begin(), result.end());1043}1044