LLDB mainline
PlatformQemuUser.cpp
Go to the documentation of this file.
1//===-- PlatformQemuUser.cpp ----------------------------------------------===//
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
15#include "lldb/Target/Process.h"
16#include "lldb/Target/Target.h"
19#include "lldb/Utility/Log.h"
20
21using namespace lldb;
22using namespace lldb_private;
23
25
26namespace {
27#define LLDB_PROPERTIES_platformqemuuser
28#include "PlatformQemuUserProperties.inc"
29
30enum {
31#define LLDB_PROPERTIES_platformqemuuser
32#include "PlatformQemuUserPropertiesEnum.inc"
33};
34
35class PluginProperties : public Properties {
36public:
37 PluginProperties() {
38 m_collection_sp = std::make_shared<OptionValueProperties>(
40 m_collection_sp->Initialize(g_platformqemuuser_properties);
41 }
42
43 llvm::StringRef GetArchitecture() {
44 return m_collection_sp->GetPropertyAtIndexAsString(
45 nullptr, ePropertyArchitecture, "");
46 }
47
48 FileSpec GetEmulatorPath() {
49 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr,
50 ePropertyEmulatorPath);
51 }
52
53 Args GetEmulatorArgs() {
54 Args result;
55 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEmulatorArgs,
56 result);
57 return result;
58 }
59
60 Environment GetEmulatorEnvVars() {
61 Args args;
62 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEmulatorEnvVars,
63 args);
64 return Environment(args);
65 }
66
67 Environment GetTargetEnvVars() {
68 Args args;
69 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyTargetEnvVars,
70 args);
71 return Environment(args);
72 }
73};
74
75} // namespace
76
77static PluginProperties &GetGlobalProperties() {
78 static PluginProperties g_settings;
79 return g_settings;
80}
81
83 return "Platform for debugging binaries under user mode qemu";
84}
85
90}
91
94}
95
98 debugger, ConstString(GetPluginNameStatic()))) {
100 debugger, GetGlobalProperties().GetValueProperties(),
101 ConstString("Properties for the qemu-user platform plugin."),
102 /*is_global_property=*/true);
103 }
104}
105
106PlatformSP PlatformQemuUser::CreateInstance(bool force, const ArchSpec *arch) {
107 if (force)
108 return PlatformSP(new PlatformQemuUser());
109 return nullptr;
110}
111
112std::vector<ArchSpec>
114 llvm::Triple triple = HostInfo::GetArchitecture().GetTriple();
115 triple.setEnvironment(llvm::Triple::UnknownEnvironment);
116 triple.setArchName(GetGlobalProperties().GetArchitecture());
117 if (triple.getArch() != llvm::Triple::UnknownArch)
118 return {ArchSpec(triple)};
119 return {};
120}
121
122static auto get_arg_range(const Args &args) {
123 return llvm::make_range(args.GetArgumentArrayRef().begin(),
124 args.GetArgumentArrayRef().end());
125}
126
127// Returns the emulator environment which result in the desired environment
128// being presented to the emulated process. We want to be careful about
129// preserving the host environment, as it may contain entries (LD_LIBRARY_PATH,
130// for example) needed for the operation of the emulator itself.
132 Environment host) {
133 std::vector<std::string> set_env;
134 for (const auto &KV : target) {
135 // If the host value differs from the target (or is unset), then set it
136 // through QEMU_SET_ENV. Identical entries will be forwarded automatically.
137 auto host_it = host.find(KV.first());
138 if (host_it == host.end() || host_it->second != KV.second)
139 set_env.push_back(Environment::compose(KV));
140 }
141 llvm::sort(set_env);
142
143 std::vector<llvm::StringRef> unset_env;
144 for (const auto &KV : host) {
145 // If the target is missing some host entries, then unset them through
146 // QEMU_UNSET_ENV.
147 if (target.count(KV.first()) == 0)
148 unset_env.push_back(KV.first());
149 }
150 llvm::sort(unset_env);
151
152 // The actual QEMU_(UN)SET_ENV variables should not be forwarded to the
153 // target.
154 if (!set_env.empty()) {
155 host["QEMU_SET_ENV"] = llvm::join(set_env, ",");
156 unset_env.push_back("QEMU_SET_ENV");
157 }
158 if (!unset_env.empty()) {
159 unset_env.push_back("QEMU_UNSET_ENV");
160 host["QEMU_UNSET_ENV"] = llvm::join(unset_env, ",");
161 }
162 return host;
163}
164
166 Debugger &debugger,
167 Target &target, Status &error) {
169
170 FileSpec qemu = GetGlobalProperties().GetEmulatorPath();
171 if (!qemu)
172 qemu.SetPath(("qemu-" + GetGlobalProperties().GetArchitecture()).str());
174
175 llvm::SmallString<0> socket_model, socket_path;
176 HostInfo::GetProcessTempDir().GetPath(socket_model);
177 llvm::sys::path::append(socket_model, "qemu-%%%%%%%%.socket");
178 do {
179 llvm::sys::fs::createUniquePath(socket_model, socket_path, false);
180 } while (FileSystem::Instance().Exists(socket_path));
181
182 Args args({qemu.GetPath(), "-g", socket_path});
183 if (!launch_info.GetArg0().empty()) {
184 args.AppendArgument("-0");
185 args.AppendArgument(launch_info.GetArg0());
186 }
187 args.AppendArguments(GetGlobalProperties().GetEmulatorArgs());
188 args.AppendArgument("--");
189 args.AppendArgument(launch_info.GetExecutableFile().GetPath());
190 for (size_t i = 1; i < launch_info.GetArguments().size(); ++i)
191 args.AppendArgument(launch_info.GetArguments()[i].ref());
192
193 LLDB_LOG(log, "{0} -> {1}", get_arg_range(launch_info.GetArguments()),
194 get_arg_range(args));
195
196 launch_info.SetArguments(args, true);
197
198 Environment emulator_env = Host::GetEnvironment();
199 if (ConstString sysroot = GetSDKRootDirectory())
200 emulator_env["QEMU_LD_PREFIX"] = sysroot.GetStringRef().str();
201 for (const auto &KV : GetGlobalProperties().GetEmulatorEnvVars())
202 emulator_env[KV.first()] = KV.second;
204 std::move(launch_info.GetEnvironment()), std::move(emulator_env));
205
206 launch_info.SetLaunchInSeparateProcessGroup(true);
207 launch_info.GetFlags().Clear(eLaunchFlagDebug);
209
210 // This is automatically done for host platform in
211 // Target::FinalizeFileActions, but we're not a host platform.
212 llvm::Error Err = launch_info.SetUpPtyRedirection();
213 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
214
215 error = Host::LaunchProcess(launch_info);
216 if (error.Fail())
217 return nullptr;
218
219 ProcessSP process_sp = target.CreateProcess(
220 launch_info.GetListener(),
222 true);
223 if (!process_sp) {
224 error.SetErrorString("Failed to create GDB process");
225 return nullptr;
226 }
227
228 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
229
230 error = process_sp->ConnectRemote(("unix-connect://" + socket_path).str());
231 if (error.Fail())
232 return nullptr;
233
234 if (launch_info.GetPTY().GetPrimaryFileDescriptor() !=
236 process_sp->SetSTDIOFileDescriptor(
237 launch_info.GetPTY().ReleasePrimaryFileDescriptor());
238
239 return process_sp;
240}
241
244 for (const auto &KV : GetGlobalProperties().GetTargetEnvVars())
245 env[KV.first()] = KV.second;
246 return env;
247}
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:337
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:360
static PluginProperties & GetGlobalProperties()
static Environment ComputeLaunchEnvironment(Environment target, Environment host)
static auto get_arg_range(const Args &args)
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
An architecture specification class.
Definition: ArchSpec.h:32
A command line argument class.
Definition: Args.h:33
llvm::ArrayRef< const char * > GetArgumentArrayRef() const
Gets the argument as an ArrayRef.
Definition: Args.h:169
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition: Args.cpp:323
A uniqued constant string class.
Definition: ConstString.h:39
A class to manage flag bits.
Definition: Debugger.h:77
static std::string compose(const value_type &KeyValue)
Definition: Environment.h:80
A file utility class.
Definition: FileSpec.h:56
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition: FileSpec.h:279
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:366
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()
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...
static llvm::StringRef GetPluginDescriptionStatic()
static llvm::StringRef GetPluginNameStatic()
Environment GetEnvironment() override
static void DebuggerInitialize(Debugger &debugger)
static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch)
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.
ConstString GetSDKRootDirectory() const
Definition: Platform.h:451
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForPlatformPlugin(Debugger &debugger, ConstString setting_name)
static bool CreateSettingForPlatformPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, ConstString description, bool is_global_property)
static bool UnregisterPlugin(ABICreateInstance create_callback)
llvm::StringRef GetArg0() const
Definition: ProcessInfo.cpp:76
void SetArguments(const Args &args, bool first_arg_is_executable)
Definition: ProcessInfo.cpp:96
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:41
Environment & GetEnvironment()
Definition: ProcessInfo.h:86
static void NoOpMonitorCallback(lldb::pid_t pid, int signal, int status)
A Monitor callback which does not take any action on process events.
lldb::ListenerSP GetHijackListener() const
void SetMonitorProcessCallback(Host::MonitorChildProcessCallback callback)
void SetLaunchInSeparateProcessGroup(bool separate)
lldb::ListenerSP GetListener() const
int GetPrimaryFileDescriptor() const
The primary file descriptor accessor.
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
@ invalid_fd
Invalid file descriptor value.
An error handling class.
Definition: Status.h:44
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition: Target.cpp:206
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:309
Definition: SBAddress.h:15