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)
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/ModuleSpec.h"
22 #include "lldb/Core/PluginManager.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 
30 static uint32_t g_initialize_count = 0;
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.
157 PlatformWindows::~PlatformWindows() = default;
158 
159 Status PlatformWindows::ResolveExecutable(
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()))
179       FileSystem::Instance().ResolveExecutableLocation(
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();
214         error.SetErrorStringWithFormat(
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;
224       for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
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) {
245         if (FileSystem::Instance().Readable(
246                 resolved_module_spec.GetFileSpec())) {
247           error.SetErrorStringWithFormat(
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 {
252           error.SetErrorStringWithFormat(
253               "'%s' is not readable",
254               resolved_module_spec.GetFileSpec().GetPath().c_str());
255         }
256       }
257     }
258   }
259 
260   return error;
261 }
262 
263 Status PlatformWindows::ConnectRemote(Args &args) {
264   Status error;
265   if (IsHost()) {
266     error.SetErrorStringWithFormat(
267         "can't connect to the host platform '%s', always connected",
268         GetPluginName().AsCString());
269   } else {
270     if (!m_remote_platform_sp)
271       m_remote_platform_sp =
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 
293 Status PlatformWindows::DisconnectRemote() {
294   Status error;
295 
296   if (IsHost()) {
297     error.SetErrorStringWithFormat(
298         "can't disconnect from the host platform '%s', always connected",
299         GetPluginName().AsCString());
300   } else {
301     if (m_remote_platform_sp)
302       error = m_remote_platform_sp->DisconnectRemote();
303     else
304       error.SetErrorString("the platform is not currently connected");
305   }
306   return error;
307 }
308 
309 ProcessSP PlatformWindows::DebugProcess(ProcessLaunchInfo &launch_info,
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()) {
332     if (m_remote_platform_sp)
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()) {
362     if (m_remote_platform_sp)
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 
396 bool PlatformWindows::GetSupportedArchitectureAtIndex(uint32_t idx,
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 
406 void PlatformWindows::GetStatus(Stream &strm) {
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 
417 ConstString PlatformWindows::GetFullNameForDylib(ConstString basename) {
418   if (basename.IsEmpty())
419     return basename;
420 
421   StreamString stream;
422   stream.Printf("%s.dll", basename.GetCString());
423   return ConstString(stream.GetString());
424 }
425