1// Copyright 2020 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/debug/wasm/gdb-server/gdb-remote-util.h"
6using std::string;
7
8namespace v8 {
9namespace internal {
10namespace wasm {
11namespace gdb_server {
12
13// GDB expects lower case values.
14static const char kHexChars[] = "0123456789abcdef";
15
16void UInt8ToHex(uint8_t byte, char chars[2]) {
17  DCHECK(chars);
18  chars[0] = kHexChars[byte >> 4];
19  chars[1] = kHexChars[byte & 0xF];
20}
21
22bool HexToUInt8(const char chars[2], uint8_t* byte) {
23  uint8_t o1, o2;
24  if (NibbleToUInt8(chars[0], &o1) && NibbleToUInt8(chars[1], &o2)) {
25    *byte = (o1 << 4) + o2;
26    return true;
27  }
28
29  return false;
30}
31
32bool NibbleToUInt8(char ch, uint8_t* byte) {
33  DCHECK(byte);
34
35  // Check for nibble of a-f
36  if ((ch >= 'a') && (ch <= 'f')) {
37    *byte = (ch - 'a' + 10);
38    return true;
39  }
40
41  // Check for nibble of A-F
42  if ((ch >= 'A') && (ch <= 'F')) {
43    *byte = (ch - 'A' + 10);
44    return true;
45  }
46
47  // Check for nibble of 0-9
48  if ((ch >= '0') && (ch <= '9')) {
49    *byte = (ch - '0');
50    return true;
51  }
52
53  // Not a valid nibble representation
54  return false;
55}
56
57std::vector<std::string> StringSplit(const string& instr, const char* delim) {
58  std::vector<std::string> result;
59
60  const char* in = instr.data();
61  if (nullptr == in) return result;
62
63  // Check if we have nothing to do
64  if (nullptr == delim) {
65    result.push_back(string(in));
66    return result;
67  }
68
69  while (*in) {
70    // Toss all preceeding delimiters
71    while (*in && strchr(delim, *in)) in++;
72
73    // If we still have something to process
74    if (*in) {
75      const char* start = in;
76      size_t len = 0;
77      // Keep moving forward for all valid chars
78      while (*in && (strchr(delim, *in) == nullptr)) {
79        len++;
80        in++;
81      }
82
83      // Build this token and add it to the array.
84      result.push_back(string{start, len});
85    }
86  }
87  return result;
88}
89
90std::string Mem2Hex(const uint8_t* mem, size_t count) {
91  std::vector<char> result(count * 2 + 1);
92  for (size_t i = 0; i < count; i++) UInt8ToHex(*mem++, &result[i * 2]);
93  result[count * 2] = '\0';
94  return result.data();
95}
96
97std::string Mem2Hex(const std::string& str) {
98  return Mem2Hex(reinterpret_cast<const uint8_t*>(str.data()), str.size());
99}
100
101}  // namespace gdb_server
102}  // namespace wasm
103}  // namespace internal
104}  // namespace v8
105