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
51llvm::StringRef ProcessWasm::GetPluginNameStatic() { return "wasm"; }
52
54 return "GDB Remote protocol based WebAssembly debugging plug-in.";
55}
56
60
62 ListenerSP listener_sp,
63 const FileSpec *crash_file_path,
64 bool can_connect) {
65 if (crash_file_path == nullptr)
66 return std::make_shared<ProcessWasm>(target_sp, listener_sp);
67 return {};
68}
69
71 bool plugin_specified_by_name) {
72 if (plugin_specified_by_name)
73 return true;
74
75 if (Module *exe_module = target_sp->GetExecutableModulePointer()) {
76 if (ObjectFile *exe_objfile = exe_module->GetObjectFile())
77 return exe_objfile->GetArchitecture().GetTriple().isWasm();
78 }
79
80 // However, if there is no wasm module, we return false, otherwise,
81 // we might use ProcessWasm to attach gdb remote.
82 return false;
83}
84
85std::shared_ptr<ThreadGDBRemote> ProcessWasm::CreateThread(lldb::tid_t tid) {
86 if (!GetTarget().GetArchitecture().GetTriple().isWasm())
88
89 return std::make_shared<ThreadWasm>(*this, tid);
90}
91
92static size_t CopyGlobal(llvm::Expected<lldb::DataBufferSP> global, void *buf,
93 size_t size, Status &error) {
94 if (!global) {
95 error = Status::FromError(global.takeError());
96 return 0;
97 }
98
99 // A global comes back whole. Reading more than it holds would have to come
100 // from somewhere else, and the next index is not adjacent storage.
101 const size_t global_size = (*global)->GetByteSize();
102 if (size > global_size) {
104 "Wasm global read failed: requested {0} bytes from a {1}-byte global",
105 size, global_size);
106 return 0;
107 }
108
109 std::memcpy(buf, (*global)->GetBytes(), size);
110 return size;
111}
112
113size_t ProcessWasm::ReadGlobal(uint32_t module_id, uint32_t index, void *buf,
114 size_t size, Status &error) {
115 if (CanNameInstance(module_id))
116 return CopyGlobal(GetWasmGlobalForModule(module_id, index), buf, size,
117 error);
118
119 // Looking for a frame drives the unwinder, so only pay for it where the
120 // instance cannot be named.
121 llvm::Expected<uint32_t> frame_index = GetFallbackFrameIndex(module_id);
122 if (!frame_index) {
123 error = Status::FromError(frame_index.takeError());
124 return 0;
125 }
126
127 return CopyGlobal(GetWasmGlobalForFrame(*frame_index, index), buf, size,
128 error);
129}
130
131llvm::Expected<uint32_t>
133 if (module_id == kWasmInvalidModuleID)
134 return llvm::createStringError(
135 "the global belongs to no known module instance");
136
138 StackFrameSP frame =
139 thread ? thread->GetSelectedFrame(DoNoSelectMostRelevantFrame) : nullptr;
140 if (frame) {
141 // A frame can only stand in for the module the stub reports it executing.
142 const uint32_t frame_index = frame->GetConcreteFrameIndex();
143 ThreadWasm &wasm_thread = static_cast<ThreadWasm &>(*thread);
144 if (GetWasmModuleID(wasm_thread.GetConcreteFramePC(frame_index)) ==
145 module_id)
146 return frame_index;
147 }
148
149 return llvm::createStringErrorV(
150 "the Wasm stub can only read a global through a frame, and no frame is "
151 "executing module {0:x}",
152 module_id);
153}
154
155size_t ProcessWasm::ReadMemory(const ProcessAddress &process_addr, void *buf,
156 size_t size, Status &error) {
157 // A caller may reuse one error across reads, as the overridden
158 // Process::ReadMemory allows.
159 error.Clear();
160
161 lldb::addr_t vm_addr = process_addr.GetValue();
162 wasm_addr_t wasm_addr(vm_addr);
163
164 switch (wasm_addr.GetType()) {
167 return ProcessGDBRemote::ReadMemory(vm_addr, buf, size, error);
169 return ReadGlobal(wasm_addr.GetModuleID(), wasm_addr.GetOffset(), buf, size,
170 error);
172 break;
173 }
174
176 "Wasm read failed for invalid address {0:x} (type = {1:x}, module = "
177 "{2:x}, offset = {3:x})",
178 vm_addr, wasm_addr.GetType(), wasm_addr.GetModuleID(),
179 wasm_addr.GetOffset());
180 return 0;
181}
182
183llvm::Expected<std::vector<lldb::addr_t>>
185 StreamString packet;
186 packet.Printf("qWasmCallStack:");
187 packet.Printf("%" PRIx64, tid);
188
190 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
192 return llvm::createStringError("failed to send qWasmCallStack");
193
194 if (!response.IsNormalResponse())
195 return llvm::createStringError("failed to get response for qWasmCallStack");
196
197 WritableDataBufferSP data_buffer_sp =
198 std::make_shared<DataBufferHeap>(response.GetStringRef().size() / 2, 0);
199 const size_t bytes = response.GetHexBytes(data_buffer_sp->GetData(), '\xcc');
200 if (bytes == 0 || bytes % sizeof(uint64_t) != 0)
201 return llvm::createStringError("invalid response for qWasmCallStack");
202
203 // To match the Wasm specification, the addresses are encoded in little endian
204 // byte order.
205 DataExtractor data(data_buffer_sp, lldb::eByteOrderLittle,
207 lldb::offset_t offset = 0;
208 std::vector<lldb::addr_t> call_stack_pcs;
209 while (offset < bytes)
210 call_stack_pcs.push_back(data.GetU64(&offset));
211
212 return call_stack_pcs;
213}
214
215llvm::Expected<lldb::DataBufferSP>
216ProcessWasm::SendWasmValueQuery(llvm::StringRef packet) {
218 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) !=
220 return llvm::createStringErrorV("failed to send {0}", packet);
221
222 if (!response.IsNormalResponse())
223 return llvm::createStringErrorV("failed to get response for {0}", packet);
224
225 WritableDataBufferSP buffer_sp(
226 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
227 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
228 return buffer_sp;
229}
230
231llvm::Expected<lldb::DataBufferSP>
233 uint32_t frame_index, uint32_t index) {
234 switch (kind) {
235 case eWasmTagLocal:
236 return SendWasmValueQuery(
237 llvm::formatv("qWasmLocal:{0};{1}", frame_index, index).str());
239 return SendWasmValueQuery(
240 llvm::formatv("qWasmStackValue:{0};{1}", frame_index, index).str());
241 case eWasmTagGlobal:
242 return llvm::createStringError("a Wasm global does not belong to a frame");
244 return llvm::createStringError("not a Wasm location");
245 }
246 llvm_unreachable("unhandled Wasm virtual register kind");
247}
248
249llvm::Expected<lldb::DataBufferSP>
250ProcessWasm::GetWasmGlobalForModule(uint32_t module_id, uint32_t index) {
251 return SendWasmValueQuery(
252 llvm::formatv("qWasmGlobal:{0};instance:{1};", index, module_id).str());
253}
254
255llvm::Expected<lldb::DataBufferSP>
256ProcessWasm::GetWasmGlobalForFrame(uint32_t frame_index, uint32_t index) {
257 return SendWasmValueQuery(
258 llvm::formatv("qWasmGlobal:{0};{1}", frame_index, index).str());
259}
260
261bool ProcessWasm::CanNameInstance(uint32_t module_id) {
262 return module_id != kWasmInvalidModuleID &&
263 m_gdb_comm.GetWasmInstanceSupported();
264}
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:2395
virtual size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2038
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2757
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3546
uint32_t GetAddressByteSize() const
Definition Process.cpp:3932
friend class Debugger
Definition Process.h:362
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1259
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()
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