LLDB  mainline
PlatformWindows.cpp
Go to the documentation of this file.
1 //===-- PlatformWindows.cpp -------------------------------------*- C++ -*-===//
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 "PlatformWindows.h"
10 
11 #include <stdio.h>
12 #if defined(_WIN32)
14 #include <winsock2.h>
15 #endif
16 
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Host/HostInfo.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Utility/Status.h"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
31 
32 namespace {
33 class SupportedArchList {
34 public:
35  SupportedArchList() {
36  AddArch(ArchSpec("i686-pc-windows"));
37  AddArch(HostInfo::GetArchitecture(HostInfo::eArchKindDefault));
38  AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind32));
39  AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind64));
40  AddArch(ArchSpec("i386-pc-windows"));
41  }
42 
43  size_t Count() const { return m_archs.size(); }
44 
45  const ArchSpec &operator[](int idx) { return m_archs[idx]; }
46 
47 private:
48  void AddArch(const ArchSpec &spec) {
49  auto iter = std::find_if(
50  m_archs.begin(), m_archs.end(),
51  [spec](const ArchSpec &rhs) { return spec.IsExactMatch(rhs); });
52  if (iter != m_archs.end())
53  return;
54  if (spec.IsValid())
55  m_archs.push_back(spec);
56  }
57 
58  std::vector<ArchSpec> m_archs;
59 };
60 } // anonymous namespace
61 
62 PlatformSP PlatformWindows::CreateInstance(bool force,
63  const lldb_private::ArchSpec *arch) {
64  // The only time we create an instance is when we are creating a remote
65  // windows platform
66  const bool is_host = false;
67 
68  bool create = force;
69  if (!create && arch && arch->IsValid()) {
70  const llvm::Triple &triple = arch->GetTriple();
71  switch (triple.getVendor()) {
72  case llvm::Triple::PC:
73  create = true;
74  break;
75 
76  case llvm::Triple::UnknownVendor:
77  create = !arch->TripleVendorWasSpecified();
78  break;
79 
80  default:
81  break;
82  }
83 
84  if (create) {
85  switch (triple.getOS()) {
86  case llvm::Triple::Win32:
87  break;
88 
89  case llvm::Triple::UnknownOS:
90  create = arch->TripleOSWasSpecified();
91  break;
92 
93  default:
94  create = false;
95  break;
96  }
97  }
98  }
99  if (create)
100  return PlatformSP(new PlatformWindows(is_host));
101  return PlatformSP();
102 }
103 
104 lldb_private::ConstString PlatformWindows::GetPluginNameStatic(bool is_host) {
105  if (is_host) {
106  static ConstString g_host_name(Platform::GetHostPlatformName());
107  return g_host_name;
108  } else {
109  static ConstString g_remote_name("remote-windows");
110  return g_remote_name;
111  }
112 }
113 
114 const char *PlatformWindows::GetPluginDescriptionStatic(bool is_host) {
115  return is_host ? "Local Windows user platform plug-in."
116  : "Remote Windows user platform plug-in.";
117 }
118 
119 lldb_private::ConstString PlatformWindows::GetPluginName() {
120  return GetPluginNameStatic(IsHost());
121 }
122 
123 void PlatformWindows::Initialize() {
124  Platform::Initialize();
125 
126  if (g_initialize_count++ == 0) {
127 #if defined(_WIN32)
128  // Force a host flag to true for the default platform object.
129  PlatformSP default_platform_sp(new PlatformWindows(true));
130  default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
131  Platform::SetHostPlatform(default_platform_sp);
132 #endif
133  PluginManager::RegisterPlugin(
134  PlatformWindows::GetPluginNameStatic(false),
135  PlatformWindows::GetPluginDescriptionStatic(false),
136  PlatformWindows::CreateInstance);
137  }
138 }
139 
140 void PlatformWindows::Terminate() {
141  if (g_initialize_count > 0) {
142  if (--g_initialize_count == 0) {
143  PluginManager::UnregisterPlugin(PlatformWindows::CreateInstance);
144  }
145  }
146 
147  Platform::Terminate();
148 }
149 
150 /// Default Constructor
151 PlatformWindows::PlatformWindows(bool is_host) : RemoteAwarePlatform(is_host) {}
152 
153 /// Destructor.
154 ///
155 /// The destructor is virtual since this class is designed to be
156 /// inherited from by the plug-in instance.
158 
160  const ModuleSpec &ms, lldb::ModuleSP &exe_module_sp,
161  const FileSpecList *module_search_paths_ptr) {
162  Status error;
163  // Nothing special to do here, just use the actual file and architecture
164 
165  char exe_path[PATH_MAX];
166  ModuleSpec resolved_module_spec(ms);
167 
168  if (IsHost()) {
169  // if we cant resolve the executable loation based on the current path
170  // variables
171  if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec())) {
172  resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
173  resolved_module_spec.GetFileSpec().SetFile(exe_path,
174  FileSpec::Style::native);
175  FileSystem::Instance().Resolve(resolved_module_spec.GetFileSpec());
176  }
177 
178  if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
180  resolved_module_spec.GetFileSpec());
181 
182  if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
183  error.Clear();
184  else {
185  ms.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
186  error.SetErrorStringWithFormat("unable to find executable for '%s'",
187  exe_path);
188  }
189  } else {
190  if (m_remote_platform_sp) {
191  error =
192  GetCachedExecutable(resolved_module_spec, exe_module_sp,
193  module_search_paths_ptr, *m_remote_platform_sp);
194  } else {
195  // We may connect to a process and use the provided executable (Don't use
196  // local $PATH).
197  if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()))
198  error.Clear();
199  else
200  error.SetErrorStringWithFormat("the platform is not currently "
201  "connected, and '%s' doesn't exist in "
202  "the system root.",
203  exe_path);
204  }
205  }
206 
207  if (error.Success()) {
208  if (resolved_module_spec.GetArchitecture().IsValid()) {
209  error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
210  nullptr, nullptr, nullptr);
211 
212  if (!exe_module_sp || exe_module_sp->GetObjectFile() == nullptr) {
213  exe_module_sp.reset();
215  "'%s' doesn't contain the architecture %s",
216  resolved_module_spec.GetFileSpec().GetPath().c_str(),
217  resolved_module_spec.GetArchitecture().GetArchitectureName());
218  }
219  } else {
220  // No valid architecture was specified, ask the platform for the
221  // architectures that we should be using (in the correct order) and see
222  // if we can find a match that way
223  StreamString arch_names;
225  idx, resolved_module_spec.GetArchitecture());
226  ++idx) {
227  error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
228  module_search_paths_ptr, nullptr,
229  nullptr);
230  // Did we find an executable using one of the
231  if (error.Success()) {
232  if (exe_module_sp && exe_module_sp->GetObjectFile())
233  break;
234  else
235  error.SetErrorToGenericError();
236  }
237 
238  if (idx > 0)
239  arch_names.PutCString(", ");
240  arch_names.PutCString(
241  resolved_module_spec.GetArchitecture().GetArchitectureName());
242  }
243 
244  if (error.Fail() || !exe_module_sp) {
246  resolved_module_spec.GetFileSpec())) {
248  "'%s' doesn't contain any '%s' platform architectures: %s",
249  resolved_module_spec.GetFileSpec().GetPath().c_str(),
250  GetPluginName().GetCString(), arch_names.GetData());
251  } else {
253  "'%s' is not readable",
254  resolved_module_spec.GetFileSpec().GetPath().c_str());
255  }
256  }
257  }
258  }
259 
260  return error;
261 }
262 
264  Status error;
265  if (IsHost()) {
267  "can't connect to the host platform '%s', always connected",
268  GetPluginName().AsCString());
269  } else {
272  Platform::Create(ConstString("remote-gdb-server"), error);
273 
274  if (m_remote_platform_sp) {
275  if (error.Success()) {
276  if (m_remote_platform_sp) {
277  error = m_remote_platform_sp->ConnectRemote(args);
278  } else {
279  error.SetErrorString(
280  "\"platform connect\" takes a single argument: <connect-url>");
281  }
282  }
283  } else
284  error.SetErrorString("failed to create a 'remote-gdb-server' platform");
285 
286  if (error.Fail())
287  m_remote_platform_sp.reset();
288  }
289 
290  return error;
291 }
292 
294  Status error;
295 
296  if (IsHost()) {
298  "can't disconnect from the host platform '%s', always connected",
299  GetPluginName().AsCString());
300  } else {
302  error = m_remote_platform_sp->DisconnectRemote();
303  else
304  error.SetErrorString("the platform is not currently connected");
305  }
306  return error;
307 }
308 
310  Debugger &debugger, Target *target,
311  Status &error) {
312  // Windows has special considerations that must be followed when launching or
313  // attaching to a process. The key requirement is that when launching or
314  // attaching to a process, you must do it from the same the thread that will
315  // go into a permanent loop which will then receive debug events from the
316  // process. In particular, this means we can't use any of LLDB's generic
317  // mechanisms to do it for us, because it doesn't have the special knowledge
318  // required for setting up the background thread or passing the right flags.
319  //
320  // Another problem is that that LLDB's standard model for debugging a process
321  // is to first launch it, have it stop at the entry point, and then attach to
322  // it. In Windows this doesn't quite work, you have to specify as an
323  // argument to CreateProcess() that you're going to debug the process. So we
324  // override DebugProcess here to handle this. Launch operations go directly
325  // to the process plugin, and attach operations almost go directly to the
326  // process plugin (but we hijack the events first). In essence, we
327  // encapsulate all the logic of Launching and Attaching in the process
328  // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to
329  // the process plugin.
330 
331  if (IsRemote()) {
333  return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
334  error);
335  else
336  error.SetErrorString("the platform is not currently connected");
337  }
338 
339  if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
340  // This is a process attach. Don't need to launch anything.
341  ProcessAttachInfo attach_info(launch_info);
342  return Attach(attach_info, debugger, target, error);
343  } else {
344  ProcessSP process_sp = target->CreateProcess(
345  launch_info.GetListener(), launch_info.GetProcessPluginName(), nullptr);
346 
347  // We need to launch and attach to the process.
348  launch_info.GetFlags().Set(eLaunchFlagDebug);
349  if (process_sp)
350  error = process_sp->Launch(launch_info);
351 
352  return process_sp;
353  }
354 }
355 
356 lldb::ProcessSP PlatformWindows::Attach(ProcessAttachInfo &attach_info,
357  Debugger &debugger, Target *target,
358  Status &error) {
359  error.Clear();
360  lldb::ProcessSP process_sp;
361  if (!IsHost()) {
363  process_sp =
364  m_remote_platform_sp->Attach(attach_info, debugger, target, error);
365  else
366  error.SetErrorString("the platform is not currently connected");
367  return process_sp;
368  }
369 
370  if (target == nullptr) {
371  TargetSP new_target_sp;
372  FileSpec emptyFileSpec;
373  ArchSpec emptyArchSpec;
374 
375  error = debugger.GetTargetList().CreateTarget(
376  debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
377  target = new_target_sp.get();
378  }
379 
380  if (!target || error.Fail())
381  return process_sp;
382 
383  debugger.GetTargetList().SetSelectedTarget(target);
384 
385  const char *plugin_name = attach_info.GetProcessPluginName();
386  process_sp = target->CreateProcess(
387  attach_info.GetListenerForProcess(debugger), plugin_name, nullptr);
388 
389  process_sp->HijackProcessEvents(attach_info.GetHijackListener());
390  if (process_sp)
391  error = process_sp->Attach(attach_info);
392 
393  return process_sp;
394 }
395 
397  ArchSpec &arch) {
398  static SupportedArchList architectures;
399 
400  if (idx >= architectures.Count())
401  return false;
402  arch = architectures[idx];
403  return true;
404 }
405 
407  Platform::GetStatus(strm);
408 
409 #ifdef _WIN32
410  llvm::VersionTuple version = HostInfo::GetOSVersion();
411  strm << " Host: Windows " << version.getAsString() << '\n';
412 #endif
413 }
414 
415 bool PlatformWindows::CanDebugProcess() { return true; }
416 
418  if (basename.IsEmpty())
419  return basename;
420 
421  StreamString stream;
422  stream.Printf("%s.dll", basename.GetCString());
423  return ConstString(stream.GetString());
424 }
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, lldb::ModuleSP *old_module_sp_ptr, bool *did_create_ptr, bool always_create=false)
Definition: ModuleList.cpp:765
bool CanDebugProcess() override
Not all platforms will support debugging a process by spawning somehow halted for a debugger (specifi...
A class to manage flag bits.
Definition: Debugger.h:82
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:61
bool IsExactMatch(const ArchSpec &rhs) const
Compare an ArchSpec to another ArchSpec, requiring an exact cpu type match between them...
Definition: ArchSpec.cpp:977
A command line argument class.
Definition: Args.h:32
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
static uint32_t g_initialize_count
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
lldb_private::Status ConnectRemote(lldb_private::Args &args) override
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:92
~PlatformWindows() override
Destructor.
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file)
Definition: Target.cpp:195
bool IsHost() const
Definition: Platform.h:450
A file utility class.
Definition: FileSpec.h:55
An architecture specification class.
Definition: ArchSpec.h:32
lldb::ListenerSP GetListener() const
const char * GetData() const
Definition: StreamString.h:43
bool IsValid() const
Tests if this ArchSpec is valid.
Definition: ArchSpec.h:329
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
static FileSystem & Instance()
const char * GetProcessPluginName() const
Definition: Process.h:140
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:431
Status GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, Platform &remote_platform)
Definition: Platform.cpp:1515
bool TripleVendorWasSpecified() const
Definition: ArchSpec.h:334
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:591
void SetErrorToGenericError()
Set the current error to a generic error.
Definition: Status.cpp:231
bool IsRemote() const
Definition: Platform.h:454
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition: Process.cpp:2786
void Clear()
Clear the object state.
Definition: Status.cpp:167
llvm::StringRef GetString() const
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
lldb::ProcessSP DebugProcess(lldb_private::ProcessLaunchInfo &launch_info, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
lldb_private::Status DisconnectRemote() override
bool Success() const
Test for success condition.
Definition: Status.cpp:287
TargetList & GetTargetList()
Get accessor for the target list.
Definition: Debugger.h:180
void GetStatus(lldb_private::Stream &strm) override
Report the current status for this platform.
ValueType Set(ValueType mask)
Set one or more flags by logical OR&#39;ing mask with the current flags.
Definition: Flags.h:84
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
FileSpec & GetFileSpec()
Definition: ModuleSpec.h:75
ArchSpec & GetArchitecture()
Definition: ModuleSpec.h:111
lldb::ProcessSP Attach(lldb_private::ProcessAttachInfo &attach_info, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error) override
Attach to an existing process using a process ID.
bool Readable(const FileSpec &file_spec) const
Returns whether the given file is readable.
A uniqued constant string class.
Definition: ConstString.h:38
bool GetSupportedArchitectureAtIndex(uint32_t idx, lldb_private::ArchSpec &arch) override
Get the platform&#39;s supported architectures in the order in which they should be searched.
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:247
char * basename(char *path)
Definition: SBAddress.h:15
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
uint32_t SetSelectedTarget(Target *target)
Definition: TargetList.cpp:601
bool TripleOSWasSpecified() const
Definition: ArchSpec.h:338
ConstString GetFullNameForDylib(ConstString basename) override
#define PATH_MAX
Status ResolveExecutable(const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr) override
Find a platform plugin for a given process.
A base class for platforms which automatically want to be able to forward operations to a remote plat...
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:198
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 IsEmpty() const
Test for empty string.
Definition: ConstString.h:340
lldb_private::ConstString GetPluginName() override
static lldb::PlatformSP Create(ConstString name, Status &error)
Definition: Platform.cpp:283
lldb::ListenerSP GetHijackListener() const
Definition: Process.h:165
lldb::pid_t GetProcessID() const
Definition: ProcessInfo.h:68
const char * GetProcessPluginName() const
An error handling class.
Definition: Status.h:44
virtual void GetStatus(Stream &strm)
Report the current status for this platform.
Definition: Platform.cpp:403