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#ifndef V8_DEBUG_WASM_GDB_SERVER_GDB_REMOTE_UTIL_H_
6#define V8_DEBUG_WASM_GDB_SERVER_GDB_REMOTE_UTIL_H_
7
8#include <string>
9#include <vector>
10#include "src/flags/flags.h"
11#include "src/utils/utils.h"
12
13namespace v8 {
14namespace internal {
15namespace wasm {
16namespace gdb_server {
17
18#define TRACE_GDB_REMOTE(...)                                            \
19  do {                                                                   \
20    if (FLAG_trace_wasm_gdb_remote) PrintF("[gdb-remote] " __VA_ARGS__); \
21  } while (false)
22
23// Convert from 0-255 to a pair of ASCII chars (0-9,a-f).
24void UInt8ToHex(uint8_t byte, char chars[2]);
25
26// Convert a pair of hex chars into a value 0-255 or return false if either
27// input character is not a valid nibble.
28bool HexToUInt8(const char chars[2], uint8_t* byte);
29
30// Convert from ASCII (0-9,a-f,A-F) to 4b unsigned or return false if the
31// input char is unexpected.
32bool NibbleToUInt8(char ch, uint8_t* byte);
33
34std::vector<std::string> V8_EXPORT_PRIVATE StringSplit(const std::string& instr,
35                                                       const char* delim);
36
37// Convert the memory pointed to by {mem} into a hex string in GDB-remote
38// format.
39std::string Mem2Hex(const uint8_t* mem, size_t count);
40std::string Mem2Hex(const std::string& str);
41
42// For LLDB debugging, an address in a Wasm module code space is represented
43// with 64 bits, where the first 32 bits identify the module id:
44// +--------------------+--------------------+
45// |     module_id      |       offset       |
46// +--------------------+--------------------+
47//  <----- 32 bit -----> <----- 32 bit ----->
48class wasm_addr_t {
49 public:
50  wasm_addr_t(uint32_t module_id, uint32_t offset)
51      : module_id_(module_id), offset_(offset) {}
52  explicit wasm_addr_t(uint64_t address)
53      : module_id_(address >> 32), offset_(address & 0xffffffff) {}
54
55  inline uint32_t ModuleId() const { return module_id_; }
56  inline uint32_t Offset() const { return offset_; }
57
58  inline operator uint64_t() const {
59    return static_cast<uint64_t>(module_id_) << 32 | offset_;
60  }
61
62 private:
63  uint32_t module_id_;
64  uint32_t offset_;
65};
66
67}  // namespace gdb_server
68}  // namespace wasm
69}  // namespace internal
70}  // namespace v8
71
72#endif  // V8_DEBUG_WASM_GDB_SERVER_GDB_REMOTE_UTIL_H_
73