xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Platform/Windows/PlatformWindows.cpp (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 //===-- PlatformWindows.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 
9 #include "PlatformWindows.h"
10 
11 #include <stdio.h>
12 #if defined(_WIN32)
13 #include "lldb/Host/windows/windows.h"
14 #include <winsock2.h>
15 #endif
16 
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 #include "lldb/Breakpoint/BreakpointSite.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Host/HostInfo.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Utility/Status.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 LLDB_PLUGIN_DEFINE(PlatformWindows)
30 
31 static uint32_t g_initialize_count = 0;
32 
33 namespace {
34 class SupportedArchList {
35 public:
36   SupportedArchList() {
37     AddArch(ArchSpec("i686-pc-windows"));
38     AddArch(HostInfo::GetArchitecture(HostInfo::eArchKindDefault));
39     AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind32));
40     AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind64));
41     AddArch(ArchSpec("i386-pc-windows"));
42   }
43 
44   size_t Count() const { return m_archs.size(); }
45 
46   const ArchSpec &operator[](int idx) { return m_archs[idx]; }
47 
48 private:
49   void AddArch(const ArchSpec &spec) {
50     auto iter = std::find_if(
51         m_archs.begin(), m_archs.end(),
52         [spec](const ArchSpec &rhs) { return spec.IsExactMatch(rhs); });
53     if (iter != m_archs.end())
54       return;
55     if (spec.IsValid())
56       m_archs.push_back(spec);
57   }
58 
59   std::vector<ArchSpec> m_archs;
60 };
61 } // anonymous namespace
62 
63 PlatformSP PlatformWindows::CreateInstance(bool force,
64                                            const lldb_private::ArchSpec *arch) {
65   // The only time we create an instance is when we are creating a remote
66   // windows platform
67   const bool is_host = false;
68 
69   bool create = force;
70   if (!create && arch && arch->IsValid()) {
71     const llvm::Triple &triple = arch->GetTriple();
72     switch (triple.getVendor()) {
73     case llvm::Triple::PC:
74       create = true;
75       break;
76 
77     case llvm::Triple::UnknownVendor:
78       create = !arch->TripleVendorWasSpecified();
79       break;
80 
81     default:
82       break;
83     }
84 
85     if (create) {
86       switch (triple.getOS()) {
87       case llvm::Triple::Win32:
88         break;
89 
90       case llvm::Triple::UnknownOS:
91         create = arch->TripleOSWasSpecified();
92         break;
93 
94       default:
95         create = false;
96         break;
97       }
98     }
99   }
100   if (create)
101     return PlatformSP(new PlatformWindows(is_host));
102   return PlatformSP();
103 }
104 
105 lldb_private::ConstString PlatformWindows::GetPluginNameStatic(bool is_host) {
106   if (is_host) {
107     static ConstString g_host_name(Platform::GetHostPlatformName());
108     return g_host_name;
109   } else {
110     static ConstString g_remote_name("remote-windows");
111     return g_remote_name;
112   }
113 }
114 
115 const char *PlatformWindows::GetPluginDescriptionStatic(bool is_host) {
116   return is_host ? "Local Windows user platform plug-in."
117                  : "Remote Windows user platform plug-in.";
118 }
119 
120 lldb_private::ConstString PlatformWindows::GetPluginName() {
121   return GetPluginNameStatic(IsHost());
122 }
123 
124 void PlatformWindows::Initialize() {
125   Platform::Initialize();
126 
127   if (g_initialize_count++ == 0) {
128 #if defined(_WIN32)
129     // Force a host flag to true for the default platform object.
130     PlatformSP default_platform_sp(new PlatformWindows(true));
131     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
132     Platform::SetHostPlatform(default_platform_sp);
133 #endif
134     PluginManager::RegisterPlugin(
135         PlatformWindows::GetPluginNameStatic(false),
136         PlatformWindows::GetPluginDescriptionStatic(false),
137         PlatformWindows::CreateInstance);
138   }
139 }
140 
141 void PlatformWindows::Terminate() {
142   if (g_initialize_count > 0) {
143     if (--g_initialize_count == 0) {
144       PluginManager::UnregisterPlugin(PlatformWindows::CreateInstance);
145     }
146   }
147 
148   Platform::Terminate();
149 }
150 
151 /// Default Constructor
152 PlatformWindows::PlatformWindows(bool is_host) : RemoteAwarePlatform(is_host) {}
153 
154 /// Destructor.
155 ///
156 /// The destructor is virtual since this class is designed to be
157 /// inherited from by the plug-in instance.
158 PlatformWindows::~PlatformWindows() = default;
159 
160 Status PlatformWindows::ConnectRemote(Args &args) {
161   Status error;
162   if (IsHost()) {
163     error.SetErrorStringWithFormat(
164         "can't connect to the host platform '%s', always connected",
165         GetPluginName().AsCString());
166   } else {
167     if (!m_remote_platform_sp)
168       m_remote_platform_sp =
169           Platform::Create(ConstString("remote-gdb-server"), error);
170 
171     if (m_remote_platform_sp) {
172       if (error.Success()) {
173         if (m_remote_platform_sp) {
174           error = m_remote_platform_sp->ConnectRemote(args);
175         } else {
176           error.SetErrorString(
177               "\"platform connect\" takes a single argument: <connect-url>");
178         }
179       }
180     } else
181       error.SetErrorString("failed to create a 'remote-gdb-server' platform");
182 
183     if (error.Fail())
184       m_remote_platform_sp.reset();
185   }
186 
187   return error;
188 }
189 
190 Status PlatformWindows::DisconnectRemote() {
191   Status error;
192 
193   if (IsHost()) {
194     error.SetErrorStringWithFormat(
195         "can't disconnect from the host platform '%s', always connected",
196         GetPluginName().AsCString());
197   } else {
198     if (m_remote_platform_sp)
199       error = m_remote_platform_sp->DisconnectRemote();
200     else
201       error.SetErrorString("the platform is not currently connected");
202   }
203   return error;
204 }
205 
206 ProcessSP PlatformWindows::DebugProcess(ProcessLaunchInfo &launch_info,
207                                         Debugger &debugger, Target *target,
208                                         Status &error) {
209   // Windows has special considerations that must be followed when launching or
210   // attaching to a process.  The key requirement is that when launching or
211   // attaching to a process, you must do it from the same the thread that will
212   // go into a permanent loop which will then receive debug events from the
213   // process.  In particular, this means we can't use any of LLDB's generic
214   // mechanisms to do it for us, because it doesn't have the special knowledge
215   // required for setting up the background thread or passing the right flags.
216   //
217   // Another problem is that that LLDB's standard model for debugging a process
218   // is to first launch it, have it stop at the entry point, and then attach to
219   // it.  In Windows this doesn't quite work, you have to specify as an
220   // argument to CreateProcess() that you're going to debug the process.  So we
221   // override DebugProcess here to handle this.  Launch operations go directly
222   // to the process plugin, and attach operations almost go directly to the
223   // process plugin (but we hijack the events first).  In essence, we
224   // encapsulate all the logic of Launching and Attaching in the process
225   // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to
226   // the process plugin.
227 
228   if (IsRemote()) {
229     if (m_remote_platform_sp)
230       return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
231                                                 error);
232     else
233       error.SetErrorString("the platform is not currently connected");
234   }
235 
236   if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
237     // This is a process attach.  Don't need to launch anything.
238     ProcessAttachInfo attach_info(launch_info);
239     return Attach(attach_info, debugger, target, error);
240   } else {
241     ProcessSP process_sp = target->CreateProcess(
242         launch_info.GetListener(), launch_info.GetProcessPluginName(), nullptr);
243 
244     // We need to launch and attach to the process.
245     launch_info.GetFlags().Set(eLaunchFlagDebug);
246     if (process_sp)
247       error = process_sp->Launch(launch_info);
248 
249     return process_sp;
250   }
251 }
252 
253 lldb::ProcessSP PlatformWindows::Attach(ProcessAttachInfo &attach_info,
254                                         Debugger &debugger, Target *target,
255                                         Status &error) {
256   error.Clear();
257   lldb::ProcessSP process_sp;
258   if (!IsHost()) {
259     if (m_remote_platform_sp)
260       process_sp =
261           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
262     else
263       error.SetErrorString("the platform is not currently connected");
264     return process_sp;
265   }
266 
267   if (target == nullptr) {
268     TargetSP new_target_sp;
269     FileSpec emptyFileSpec;
270     ArchSpec emptyArchSpec;
271 
272     error = debugger.GetTargetList().CreateTarget(
273         debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
274     target = new_target_sp.get();
275   }
276 
277   if (!target || error.Fail())
278     return process_sp;
279 
280   debugger.GetTargetList().SetSelectedTarget(target);
281 
282   const char *plugin_name = attach_info.GetProcessPluginName();
283   process_sp = target->CreateProcess(
284       attach_info.GetListenerForProcess(debugger), plugin_name, nullptr);
285 
286   process_sp->HijackProcessEvents(attach_info.GetHijackListener());
287   if (process_sp)
288     error = process_sp->Attach(attach_info);
289 
290   return process_sp;
291 }
292 
293 bool PlatformWindows::GetSupportedArchitectureAtIndex(uint32_t idx,
294                                                       ArchSpec &arch) {
295   static SupportedArchList architectures;
296 
297   if (idx >= architectures.Count())
298     return false;
299   arch = architectures[idx];
300   return true;
301 }
302 
303 void PlatformWindows::GetStatus(Stream &strm) {
304   Platform::GetStatus(strm);
305 
306 #ifdef _WIN32
307   llvm::VersionTuple version = HostInfo::GetOSVersion();
308   strm << "      Host: Windows " << version.getAsString() << '\n';
309 #endif
310 }
311 
312 bool PlatformWindows::CanDebugProcess() { return true; }
313 
314 ConstString PlatformWindows::GetFullNameForDylib(ConstString basename) {
315   if (basename.IsEmpty())
316     return basename;
317 
318   StreamString stream;
319   stream.Printf("%s.dll", basename.GetCString());
320   return ConstString(stream.GetString());
321 }
322