LLDB mainline
PlatformWasm.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
18#include "lldb/Target/Process.h"
19#include "lldb/Target/Target.h"
23#include "lldb/Utility/Log.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/ErrorExtras.h"
26
27using namespace lldb;
28using namespace lldb_private;
29
31
32namespace {
33#define LLDB_PROPERTIES_platformwasm
34#include "PlatformWasmProperties.inc"
35
36enum {
37#define LLDB_PROPERTIES_platformwasm
38#include "PlatformWasmPropertiesEnum.inc"
39};
40
41class PluginProperties : public Properties {
42public:
43 PluginProperties() {
44 m_collection_sp = std::make_shared<OptionValueProperties>(
46 m_collection_sp->Initialize(g_platformwasm_properties_def);
47 }
48
49 FileSpec GetRuntimePath() const {
50 return GetPropertyAtIndexAs<FileSpec>(ePropertyRuntimePath, {});
51 }
52
53 Args GetRuntimeArgs() const {
54 Args result;
55 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyRuntimeArgs, result);
56 return result;
57 }
58
59 llvm::StringRef GetPortArg() const {
60 return GetPropertyAtIndexAs<llvm::StringRef>(ePropertyPortArg, {});
61 }
62
63 llvm::StringRef GetEnvArg() const {
64 return GetPropertyAtIndexAs<llvm::StringRef>(ePropertyEnvArg, {});
65 }
66};
67
68} // namespace
69
70static PluginProperties &GetGlobalProperties() {
71 static PluginProperties g_settings;
72 return g_settings;
73}
74
76 return "Platform for debugging Wasm";
77}
78
85
90
95 debugger, GetGlobalProperties().GetValueProperties(),
96 "Properties for the wasm platform plugin.",
97 /*is_global_property=*/true);
98 }
99}
100
103 LLDB_LOG(log, "force = {0}, arch = ({1}, {2})", force,
104 arch ? arch->GetArchitectureName() : "<null>",
105 arch ? arch->GetTriple().getTriple() : "<null>");
106
107 bool create = force;
108 if (!create && arch && arch->IsValid()) {
109 const llvm::Triple &triple = arch->GetTriple();
110 switch (triple.getArch()) {
111 case llvm::Triple::wasm32:
112 case llvm::Triple::wasm64:
113 create = true;
114 break;
115 default:
116 break;
117 }
118 }
119
120 LLDB_LOG(log, "create = {0}", create);
121 return create ? PlatformSP(new PlatformWasm()) : PlatformSP();
122}
123
124llvm::Expected<uint16_t> PlatformWasm::FindFreeTCPPort() {
125 TCPSocket sock(/*should_close=*/true);
126 Status status = sock.Listen("localhost:0", /*backlog=*/5);
127 if (status.Fail())
128 return status.takeError();
129 return sock.GetLocalPortNumber();
130}
131
132std::vector<ArchSpec>
134 return {ArchSpec("wasm32"), ArchSpec("wasm64")};
135}
136
138 Debugger &debugger, Target *target,
139 Status &status) {
141 return m_remote_platform_sp->Attach(attach_info, debugger, target, status);
142
144 "attaching is only supported when connected to a remote Wasm platform");
145 return nullptr;
146}
147
149 Debugger &debugger, Target &target,
150 Status &error) {
152 return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
153 error);
154
156
157 const PluginProperties &properties = GetGlobalProperties();
158
159 FileSpec runtime = properties.GetRuntimePath();
161
162 if (!FileSystem::Instance().Exists(runtime)) {
164 "WebAssembly runtime does not exist: {0}", runtime.GetPath());
165 return nullptr;
166 }
167
168 llvm::Expected<uint16_t> expected_port = FindFreeTCPPort();
169 if (!expected_port) {
170 error = Status::FromError(expected_port.takeError());
171 return nullptr;
172 }
173 uint16_t port = *expected_port;
174
175 Args args({runtime.GetPath(),
176 llvm::formatv("{0}{1}", properties.GetPortArg(), port).str()});
177 args.AppendArguments(properties.GetRuntimeArgs());
178
179 // Forward the inferior's environment into the WASI runtime. How arguments are
180 // passed is configurable. When not configured, no environment is passed.
181 if (llvm::StringRef env_arg = properties.GetEnvArg(); !env_arg.empty())
182 for (const auto &kv : launch_info.GetEnvironment())
183 args.AppendArgument(
184 llvm::formatv("{0}{1}", env_arg, Environment::compose(kv)).str());
185
186 args.AppendArguments(launch_info.GetArguments());
187
188 launch_info.SetArguments(args, true);
189 launch_info.SetLaunchInSeparateProcessGroup(true);
190 // We're launching the Wasm runtime (a native host binary), not the target
191 // being debugged. Clear flags that don't apply to the runtime process.
192 launch_info.GetFlags().Clear(eLaunchFlagDebug | eLaunchFlagDisableASLR);
193 // The runtime itself runs with the host environment.
194 launch_info.GetEnvironment() = Host::GetEnvironment();
195
196 auto exit_code = std::make_shared<std::optional<int>>();
197 launch_info.SetMonitorProcessCallback(
198 [=](lldb::pid_t pid, int signal, int status) {
199 LLDB_LOG(
200 log,
201 "WebAssembly runtime exited: pid = {0}, signal = {1}, status = {2}",
202 pid, signal, status);
203 exit_code->emplace(status);
204 });
205
206 // This is automatically done for host platform in
207 // Target::FinalizeFileActions, but we're not a host platform.
208 llvm::Error Err = launch_info.SetUpPtyRedirection();
209 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
210
211 LLDB_LOG(log, "{0}", GetArgRange(launch_info.GetArguments()));
212 error = Host::LaunchProcess(launch_info);
213 if (error.Fail())
214 return nullptr;
215
216 ProcessSP process_sp = target.CreateProcess(
218 nullptr, true);
219 if (!process_sp) {
220 error = Status::FromErrorString("failed to create WebAssembly process");
221 return nullptr;
222 }
223
224 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
225
226 error = process_sp->ConnectRemote(
227 llvm::formatv("connect://localhost:{0}", port).str());
228 if (error.Fail()) {
229 // If we know the runtime has exited, that's a better error message than
230 // failing to connect.
231 if (*exit_code)
232 error = Status::FromError(llvm::joinErrors(
233 llvm::createStringErrorV(
234 "WebAssembly runtime exited with exit code {0}", **exit_code),
235 error.takeError()));
236
237 return nullptr;
238 }
239#ifndef _WIN32
240 if (launch_info.GetPTY().GetPrimaryFileDescriptor() !=
242 process_sp->SetSTDIOFileDescriptor(
243 launch_info.GetPTY().ReleasePrimaryFileDescriptor());
244#endif
245 return process_sp;
246}
247
249 if (IsHost())
251 "can't connect to the host platform, always connected");
252
255
256 return m_remote_platform_sp->ConnectRemote(args);
257}
static llvm::raw_ostream & error(Stream &strm)
static DynamicLoaderDarwinKernelProperties & GetGlobalProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:406
static PluginProperties & GetGlobalProperties()
#define LLDB_PLUGIN_DEFINE(PluginName)
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:452
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:740
A command line argument class.
Definition Args.h:33
void AppendArguments(const Args &rhs)
Definition Args.cpp:307
A class to manage flag bits.
Definition Debugger.h:100
static std::string compose(const value_type &KeyValue)
Definition Environment.h:80
A file utility class.
Definition FileSpec.h:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
static FileSystem & Instance()
ValueType Clear(ValueType mask=~static_cast< ValueType >(0))
Clear one or more flags.
Definition Flags.h:61
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static Environment GetEnvironment()
static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch)
static auto GetArgRange(const Args &args)
lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target &target, Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
Status ConnectRemote(Args &args) override
static void DebuggerInitialize(Debugger &debugger)
static llvm::Expected< uint16_t > FindFreeTCPPort()
Find a free TCP port by binding to port 0.
static llvm::StringRef GetPluginNameStatic()
lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, Status &status) override
Attach to an existing process using a process ID.
std::vector< ArchSpec > GetSupportedArchitectures(const ArchSpec &process_host_arch) override
Get the platform's supported architectures in the order in which they should be searched.
static llvm::StringRef GetPluginDescriptionStatic()
bool IsHost() const
Definition Platform.h:557
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForPlatformPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool CreateSettingForPlatformPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static bool UnregisterPlugin(ABICreateInstance create_callback)
lldb::ListenerSP GetHijackListener() const
void SetArguments(const Args &args, bool first_arg_is_executable)
lldb::ListenerSP GetListener() const
Environment & GetEnvironment()
Definition ProcessInfo.h:86
void SetMonitorProcessCallback(Host::MonitorChildProcessCallback callback)
void SetLaunchInSeparateProcessGroup(bool separate)
@ invalid_fd
Invalid file descriptor value.
int GetPrimaryFileDescriptor() const
The primary file descriptor accessor.
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
An error handling class.
Definition Status.h:118
llvm::Error takeError()
Definition Status.h:170
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
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
Status Listen(llvm::StringRef name, int backlog) override
uint16_t GetLocalPortNumber() const
Definition TCPSocket.cpp:86
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:317
static llvm::StringRef GetPluginNameStatic()
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:339
std::shared_ptr< lldb_private::Platform > PlatformSP
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t pid_t
Definition lldb-types.h:83