LLDB mainline
ProcessWasm.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ProcessWasm.h"
10#include "ThreadWasm.h"
11#include "lldb/Core/Module.h"
13#include "lldb/Core/Value.h"
16#include "llvm/Support/ErrorExtras.h"
17#include <cstring>
18
20
21using namespace lldb;
22using namespace lldb_private;
24using namespace lldb_private::wasm;
25
27
29 : ProcessGDBRemote(target_sp, listener_sp) {
30 assert(target_sp);
31 // Wasm doesn't have any Unix-like signals as a platform concept, but pretend
32 // like it does to appease LLDB.
33 m_unix_signals_sp = UnixSignals::Create(target_sp->GetArchitecture());
34 // FIXME: LLVM's RuntimeDyld doesn't support the Wasm object format, so we
35 // can't JIT expressions for this target.
36 SetCanJIT(false);
37}
38
44
48
49llvm::StringRef ProcessWasm::GetPluginName() { return GetPluginNameStatic(); }
50
52 return "GDB Remote protocol based WebAssembly debugging plug-in.";
53}
54
58
60 ListenerSP listener_sp,
61 const FileSpec *crash_file_path,
62 bool can_connect) {
63 if (crash_file_path == nullptr)
64 return std::make_shared<ProcessWasm>(target_sp, listener_sp);
65 return {};
66}
67
69 bool plugin_specified_by_name) {
70 if (plugin_specified_by_name)
71 return true;
72
73 if (Module *exe_module = target_sp->GetExecutableModulePointer()) {
74 if (ObjectFile *exe_objfile = exe_module->GetObjectFile())
75 return exe_objfile->GetArchitecture().GetTriple().isWasm();
76 }
77
78 // However, if there is no wasm module, we return false, otherwise,
79 // we might use ProcessWasm to attach gdb remote.
80 return false;
81}
82
83std::shared_ptr<ThreadGDBRemote> ProcessWasm::CreateThread(lldb::tid_t tid) {
84 if (!GetTarget().GetArchitecture().GetTriple().isWasm())
86
87 return std::make_shared<ThreadWasm>(*this, tid);
88}
89
90static size_t CopyGlobal(llvm::Expected<lldb::DataBufferSP> global, void *buf,
91 size_t size, Status &error) {
92 if (!global) {
93 error = Status::FromError(global.takeError());
94 return 0;
95 }
96
97 // A global comes back whole. Reading more than it holds would have to come
98 // from somewhere else, and the next index is not adjacent storage.
99 const size_t global_size = (*global)->GetByteSize();
100 if (size > global_size) {
102 "Wasm global read failed: requested {0} bytes from a {1}-byte global",
103 size, global_size);
104 return 0;
105 }
106
107 std::memcpy(buf, (*global)->GetBytes(), size);
108 return size;
109}
110
111size_t ProcessWasm::ReadGlobal(uint32_t module_id, uint32_t index, void *buf,
112 size_t size, Status &error) {
113 if (CanNameInstance(module_id))
114 return CopyGlobal(GetWasmGlobalForModule(module_id, index), buf, size,
115 error);
116
117 // Looking for a frame drives the unwinder, so only pay for it where the
118 // instance cannot be named.
119 llvm::Expected<uint32_t> frame_index = GetFallbackFrameIndex(module_id);
120 if (!frame_index) {
121 error = Status::FromError(frame_index.takeError());
122 return 0;
123 }
124
125 return CopyGlobal(GetWasmGlobalForFrame(*frame_index, index), buf, size,
126 error);
127}
128
129llvm::Expected<uint32_t>
131 if (module_id == kWasmInvalidModuleID)
132 return llvm::createStringError(
133 "the global belongs to no known module instance");
134
136 StackFrameSP frame =
137 thread ? thread->GetSelectedFrame(DoNoSelectMostRelevantFrame) : nullptr;
138 if (frame) {
139 // A frame can only stand in for the module the stub reports it executing.
140 const uint32_t frame_index = frame->GetConcreteFrameIndex();
141 ThreadWasm &wasm_thread = static_cast<ThreadWasm &>(*thread);
142 if (GetWasmModuleID(wasm_thread.GetConcreteFramePC(frame_index)) ==
143 module_id)
144 return frame_index;
145 }
146
147 return llvm::createStringErrorV(
148 "the Wasm stub can only read a global through a frame, and no frame is "
149 "executing module {0:x}",
150 module_id);
151}
152
153size_t ProcessWasm::ReadMemory(const ProcessAddress &process_addr, void *buf,
154 size_t size, Status &error) {
155 // A caller may reuse one error across reads, as the overridden
156 // Process::ReadMemory allows.
157 error.Clear();
158
159 lldb::addr_t vm_addr = process_addr.GetValue();
160 wasm_addr_t wasm_addr(vm_addr);
161
162 switch (wasm_addr.GetType()) {
165 return ProcessGDBRemote::ReadMemory(vm_addr, buf, size, error);
167 return ReadGlobal(wasm_addr.GetModuleID(), wasm_addr.GetOffset(), buf, size,
168 error);
170 break;
171 }
172
174 "Wasm read failed for invalid address {0:x} (type = {1:x}, module = "
175 "{2:x}, offset = {3:x})",
176 vm_addr, wasm_addr.GetType(), wasm_addr.GetModuleID(),
177 wasm_addr.GetOffset());
178 return 0;
179}
180
181llvm::Expected<std::vector<lldb::addr_t>>
183 StreamString packet;
184 packet.Printf("qWasmCallStack:");
185 packet.Printf("%" PRIx64, tid);
186
188 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
190 return llvm::createStringError("failed to send qWasmCallStack");
191
192 if (!response.IsNormalResponse())
193 return llvm::createStringError("failed to get response for qWasmCallStack");
194
195 WritableDataBufferSP data_buffer_sp =
196 std::make_shared<DataBufferHeap>(response.GetStringRef().size() / 2, 0);
197 const size_t bytes = response.GetHexBytes(data_buffer_sp->GetData(), '\xcc');
198 if (bytes == 0 || bytes % sizeof(uint64_t) != 0)
199 return llvm::createStringError("invalid response for qWasmCallStack");
200
201 // To match the Wasm specification, the addresses are encoded in little endian
202 // byte order.
203 DataExtractor data(data_buffer_sp, lldb::eByteOrderLittle,
205 lldb::offset_t offset = 0;
206 std::vector<lldb::addr_t> call_stack_pcs;
207 while (offset < bytes)
208 call_stack_pcs.push_back(data.GetU64(&offset));
209
210 return call_stack_pcs;
211}
212
213llvm::Expected<lldb::DataBufferSP>
214ProcessWasm::SendWasmValueQuery(llvm::StringRef packet) {
216 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) !=
218 return llvm::createStringErrorV("failed to send {0}", packet);
219
220 if (!response.IsNormalResponse())
221 return llvm::createStringErrorV("failed to get response for {0}", packet);
222
223 WritableDataBufferSP buffer_sp(
224 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
225 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
226 return buffer_sp;
227}
228
229llvm::Expected<lldb::DataBufferSP>
231 uint32_t frame_index, uint32_t index) {
232 switch (kind) {
233 case eWasmTagLocal:
234 return SendWasmValueQuery(
235 llvm::formatv("qWasmLocal:{0};{1}", frame_index, index).str());
237 return SendWasmValueQuery(
238 llvm::formatv("qWasmStackValue:{0};{1}", frame_index, index).str());
239 case eWasmTagGlobal:
240 return llvm::createStringError("a Wasm global does not belong to a frame");
242 return llvm::createStringError("not a Wasm location");
243 }
244 llvm_unreachable("unhandled Wasm virtual register kind");
245}
246
247llvm::Expected<lldb::DataBufferSP>
248ProcessWasm::GetWasmGlobalForModule(uint32_t module_id, uint32_t index) {
249 return SendWasmValueQuery(
250 llvm::formatv("qWasmGlobal:{0};instance:{1};", index, module_id).str());
251}
252
253llvm::Expected<lldb::DataBufferSP>
254ProcessWasm::GetWasmGlobalForFrame(uint32_t frame_index, uint32_t index) {
255 return SendWasmValueQuery(
256 llvm::formatv("qWasmGlobal:{0};{1}", frame_index, index).str());
257}
258
259bool ProcessWasm::CanNameInstance(uint32_t module_id) {
260 return module_id != kWasmInvalidModuleID &&
261 m_gdb_comm.GetWasmInstanceSupported();
262}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_PLUGIN_DEFINE(PluginName)
static size_t CopyGlobal(llvm::Expected< lldb::DataBufferSP > global, void *buf, size_t size, Status &error)
size_t GetHexBytes(llvm::MutableArrayRef< uint8_t > dest, uint8_t fail_fill_value)
llvm::StringRef GetStringRef() const
A subclass of DataBuffer that stores a data buffer on the heap.
An data extractor class.
uint64_t GetU64(lldb::offset_t *offset_ptr) const
Extract a uint64_t value from *offset_ptr.
A file utility class.
Definition FileSpec.h:56
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
ThreadList & GetThreadList()
Definition Process.h:2408
virtual size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2081
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2802
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3562
uint32_t GetAddressByteSize() const
Definition Process.cpp:3977
friend class Debugger
Definition Process.h:369
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1266
An error handling class.
Definition Status.h:118
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
lldb::ThreadSP GetSelectedThread()
static lldb::UnixSignalsSP Create(const ArchSpec &arch)
virtual std::shared_ptr< ThreadGDBRemote > CreateThread(lldb::tid_t tid)
ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
ProcessWasm provides the access to the Wasm program state retrieved from the Wasm engine.
Definition ProcessWasm.h:21
llvm::Expected< uint32_t > GetFallbackFrameIndex(uint32_t module_id)
The frame to read a global of module_id through, for a stub that cannot be told which instance to rea...
size_t ReadGlobal(uint32_t module_id, uint32_t index, void *buf, size_t size, Status &error)
Read a WebAssembly global of the module instance module_id names, through whichever scope that stub c...
llvm::Expected< lldb::DataBufferSP > GetWasmGlobalForModule(uint32_t module_id, uint32_t index)
Query the value of the global at index in the global index space of the module instance module_id nam...
llvm::Expected< lldb::DataBufferSP > GetWasmVariable(WasmVirtualRegisterKinds kind, uint32_t frame_index, uint32_t index)
Query the value of a frame-scoped WebAssembly variable, which is a local or a value on the operand st...
llvm::StringRef GetPluginName() override
std::shared_ptr< process_gdb_remote::ThreadGDBRemote > CreateThread(lldb::tid_t tid) override
llvm::Expected< lldb::DataBufferSP > GetWasmGlobalForFrame(uint32_t frame_index, uint32_t index)
Query the value of a WebAssembly global through the frame at frame_index, which reaches only the glob...
bool CanNameInstance(uint32_t module_id)
Whether the instance holding a global can be named to the stub, which needs both a valid id to name i...
static llvm::StringRef GetPluginNameStatic()
Definition ProcessWasm.h:35
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
static void DebuggerInitialize(Debugger &debugger)
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
size_t ReadMemory(const ProcessAddress &vm_addr, void *buf, size_t size, Status &error) override
Read of memory from a process.
llvm::Expected< std::vector< lldb::addr_t > > GetWasmCallStack(lldb::tid_t tid)
Retrieve the current call stack from the WebAssembly remote process.
llvm::Expected< lldb::DataBufferSP > SendWasmValueQuery(llvm::StringRef packet)
Ask the WebAssembly stub for a single value, which comes back as the hex-encoded bytes of the whole v...
ProcessWasm(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
static llvm::StringRef GetPluginDescriptionStatic()
lldb::addr_t GetConcreteFramePC(uint32_t concrete_frame_idx)
Return the program counter the Wasm unwinder recorded for the given concrete frame index,...
@ DoNoSelectMostRelevantFrame
static constexpr uint32_t kWasmInvalidModuleID
A value that names no module.
Definition WasmAddress.h:62
uint32_t GetWasmModuleID(lldb::addr_t addr)
The module an address belongs to, or kWasmInvalidModuleID for an invalid address.
Definition WasmAddress.h:94
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t offset_t
Definition lldb-types.h:86
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
uint64_t tid_t
Definition lldb-types.h:85
For the purpose of debugging, we can represent all these separated 32-bit address spaces with a singl...
Definition WasmAddress.h:70
WasmAddressType GetType() const
Definition WasmAddress.h:83