1 //===-- PlatformWindows.cpp ---------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "PlatformWindows.h"
11 
12 // C Includes
13 #include <stdio.h>
14 #if defined (_WIN32)
15 #include "lldb/Host/windows/windows.h"
16 #include <winsock2.h>
17 #endif
18 
19 // C++ Includes
20 // Other libraries and framework includes
21 // Project includes
22 #include "lldb/Core/Error.h"
23 #include "lldb/Core/Debugger.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/Module.h"
28 #include "lldb/Breakpoint/BreakpointLocation.h"
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 static uint32_t g_initialize_count = 0;
34 
35 namespace
36 {
37     class SupportedArchList
38     {
39     public:
40         SupportedArchList()
41         {
42             AddArch(ArchSpec("i686-pc-windows"));
43             AddArch(Host::GetArchitecture(Host::eSystemDefaultArchitecture));
44             AddArch(Host::GetArchitecture(Host::eSystemDefaultArchitecture32));
45             AddArch(Host::GetArchitecture(Host::eSystemDefaultArchitecture64));
46             AddArch(ArchSpec("i386-pc-windows"));
47         }
48 
49         size_t Count() const { return m_archs.size(); }
50 
51         const ArchSpec& operator[](int idx) { return m_archs[idx]; }
52 
53     private:
54         void AddArch(const ArchSpec& spec)
55         {
56             auto iter = std::find_if(
57                 m_archs.begin(), m_archs.end(),
58                 [spec](const ArchSpec& rhs) { return spec.IsExactMatch(rhs); });
59             if (iter != m_archs.end())
60                 return;
61             if (spec.IsValid())
62                 m_archs.push_back(spec);
63         }
64 
65         std::vector<ArchSpec> m_archs;
66     };
67 }
68 
69 Platform *
70 PlatformWindows::CreateInstance (bool force, const lldb_private::ArchSpec *arch)
71 {
72     // The only time we create an instance is when we are creating a remote
73     // windows platform
74     const bool is_host = false;
75 
76     bool create = force;
77     if (create == false && arch && arch->IsValid())
78     {
79         const llvm::Triple &triple = arch->GetTriple();
80         switch (triple.getVendor())
81         {
82         case llvm::Triple::PC:
83             create = true;
84             break;
85 
86         case llvm::Triple::UnknownArch:
87             create = !arch->TripleVendorWasSpecified();
88             break;
89 
90         default:
91             break;
92         }
93 
94         if (create)
95         {
96             switch (triple.getOS())
97             {
98             case llvm::Triple::Win32:
99                 break;
100 
101             case llvm::Triple::UnknownOS:
102                 create = arch->TripleOSWasSpecified();
103                 break;
104 
105             default:
106                 create = false;
107                 break;
108             }
109         }
110     }
111     if (create)
112         return new PlatformWindows (is_host);
113     return NULL;
114 
115 }
116 
117 lldb_private::ConstString
118 PlatformWindows::GetPluginNameStatic(bool is_host)
119 {
120     if (is_host)
121     {
122         static ConstString g_host_name(Platform::GetHostPlatformName ());
123         return g_host_name;
124     }
125     else
126     {
127         static ConstString g_remote_name("remote-windows");
128         return g_remote_name;
129     }
130 }
131 
132 const char *
133 PlatformWindows::GetPluginDescriptionStatic(bool is_host)
134 {
135     return is_host ?
136         "Local Windows user platform plug-in." :
137         "Remote Windows user platform plug-in.";
138 }
139 
140 lldb_private::ConstString
141 PlatformWindows::GetPluginName(void)
142 {
143     return GetPluginNameStatic(IsHost());
144 }
145 
146 void
147 PlatformWindows::Initialize(void)
148 {
149     if (g_initialize_count++ == 0)
150     {
151 #if defined (_WIN32)
152         WSADATA dummy;
153         WSAStartup(MAKEWORD(2,2), &dummy);
154         // Force a host flag to true for the default platform object.
155         PlatformSP default_platform_sp (new PlatformWindows(true));
156         default_platform_sp->SetSystemArchitecture (Host::GetArchitecture());
157         Platform::SetDefaultPlatform (default_platform_sp);
158 #endif
159         PluginManager::RegisterPlugin(PlatformWindows::GetPluginNameStatic(false),
160                                       PlatformWindows::GetPluginDescriptionStatic(false),
161                                       PlatformWindows::CreateInstance);
162     }
163 }
164 
165 void
166 PlatformWindows::Terminate( void )
167 {
168     if (g_initialize_count > 0)
169     {
170         if (--g_initialize_count == 0)
171         {
172 #ifdef _WIN32
173             WSACleanup();
174 #endif
175             PluginManager::UnregisterPlugin (PlatformWindows::CreateInstance);
176         }
177     }
178 }
179 
180 //------------------------------------------------------------------
181 /// Default Constructor
182 //------------------------------------------------------------------
183 PlatformWindows::PlatformWindows (bool is_host) :
184     Platform(is_host)
185 {
186 }
187 
188 //------------------------------------------------------------------
189 /// Destructor.
190 ///
191 /// The destructor is virtual since this class is designed to be
192 /// inherited from by the plug-in instance.
193 //------------------------------------------------------------------
194 PlatformWindows::~PlatformWindows()
195 {
196 }
197 
198 Error
199 PlatformWindows::ResolveExecutable (const FileSpec &exe_file,
200                                     const ArchSpec &exe_arch,
201                                     lldb::ModuleSP &exe_module_sp,
202                                     const FileSpecList *module_search_paths_ptr)
203 {
204     Error error;
205     // Nothing special to do here, just use the actual file and architecture
206 
207     char exe_path[PATH_MAX];
208     FileSpec resolved_exe_file (exe_file);
209 
210     if (IsHost())
211     {
212         // if we cant resolve the executable loation based on the current path variables
213         if (!resolved_exe_file.Exists())
214         {
215             exe_file.GetPath(exe_path, sizeof(exe_path));
216             resolved_exe_file.SetFile(exe_path, true);
217         }
218 
219         if (!resolved_exe_file.Exists())
220             resolved_exe_file.ResolveExecutableLocation ();
221 
222         if (resolved_exe_file.Exists())
223             error.Clear();
224         else
225         {
226             exe_file.GetPath(exe_path, sizeof(exe_path));
227             error.SetErrorStringWithFormat("unable to find executable for '%s'", exe_path);
228         }
229     }
230     else
231     {
232         if (m_remote_platform_sp)
233         {
234             error = m_remote_platform_sp->ResolveExecutable (exe_file,
235                                                              exe_arch,
236                                                              exe_module_sp,
237                                                              NULL);
238         }
239         else
240         {
241             // We may connect to a process and use the provided executable (Don't use local $PATH).
242             if (resolved_exe_file.Exists())
243                 error.Clear();
244             else
245                 error.SetErrorStringWithFormat("the platform is not currently connected, and '%s' doesn't exist in the system root.", exe_path);
246         }
247     }
248 
249     if (error.Success())
250     {
251         ModuleSpec module_spec (resolved_exe_file, exe_arch);
252         if (exe_arch.IsValid())
253         {
254             error = ModuleList::GetSharedModule (module_spec,
255                                                  exe_module_sp,
256                                                  NULL,
257                                                  NULL,
258                                                  NULL);
259 
260             if (!exe_module_sp || exe_module_sp->GetObjectFile() == NULL)
261             {
262                 exe_module_sp.reset();
263                 error.SetErrorStringWithFormat ("'%s' doesn't contain the architecture %s",
264                                                 exe_file.GetPath().c_str(),
265                                                 exe_arch.GetArchitectureName());
266             }
267         }
268         else
269         {
270             // No valid architecture was specified, ask the platform for
271             // the architectures that we should be using (in the correct order)
272             // and see if we can find a match that way
273             StreamString arch_names;
274             for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, module_spec.GetArchitecture()); ++idx)
275             {
276                 error = ModuleList::GetSharedModule (module_spec,
277                                                      exe_module_sp,
278                                                      NULL,
279                                                      NULL,
280                                                      NULL);
281                 // Did we find an executable using one of the
282                 if (error.Success())
283                 {
284                     if (exe_module_sp && exe_module_sp->GetObjectFile())
285                         break;
286                     else
287                         error.SetErrorToGenericError();
288                 }
289 
290                 if (idx > 0)
291                     arch_names.PutCString (", ");
292                 arch_names.PutCString (module_spec.GetArchitecture().GetArchitectureName());
293             }
294 
295             if (error.Fail() || !exe_module_sp)
296             {
297                 error.SetErrorStringWithFormat ("'%s' doesn't contain any '%s' platform architectures: %s",
298                                                 exe_file.GetPath().c_str(),
299                                                 GetPluginName().GetCString(),
300                                                 arch_names.GetString().c_str());
301             }
302         }
303     }
304 
305     return error;
306 }
307 
308 size_t
309 PlatformWindows::GetSoftwareBreakpointTrapOpcode (Target &target, BreakpointSite *bp_site)
310 {
311     ArchSpec arch = target.GetArchitecture();
312     const uint8_t *trap_opcode = NULL;
313     size_t trap_opcode_size = 0;
314 
315     switch (arch.GetMachine())
316     {
317     case llvm::Triple::x86:
318     case llvm::Triple::x86_64:
319         {
320             static const uint8_t g_i386_opcode[] = { 0xCC };
321             trap_opcode = g_i386_opcode;
322             trap_opcode_size = sizeof(g_i386_opcode);
323         }
324         break;
325 
326     case llvm::Triple::hexagon:
327         {
328             static const uint8_t g_hex_opcode[] = { 0x0c, 0xdb, 0x00, 0x54 };
329             trap_opcode = g_hex_opcode;
330             trap_opcode_size = sizeof(g_hex_opcode);
331         }
332         break;
333     default:
334         llvm_unreachable("Unhandled architecture in PlatformWindows::GetSoftwareBreakpointTrapOpcode()");
335         break;
336     }
337 
338     if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
339         return trap_opcode_size;
340 
341     return 0;
342 }
343 
344 bool
345 PlatformWindows::GetRemoteOSVersion ()
346 {
347     if (m_remote_platform_sp)
348         return m_remote_platform_sp->GetOSVersion (m_major_os_version,
349                                                    m_minor_os_version,
350                                                    m_update_os_version);
351     return false;
352 }
353 
354 bool
355 PlatformWindows::GetRemoteOSBuildString (std::string &s)
356 {
357     if (m_remote_platform_sp)
358         return m_remote_platform_sp->GetRemoteOSBuildString (s);
359     s.clear();
360     return false;
361 }
362 
363 bool
364 PlatformWindows::GetRemoteOSKernelDescription (std::string &s)
365 {
366     if (m_remote_platform_sp)
367         return m_remote_platform_sp->GetRemoteOSKernelDescription (s);
368     s.clear();
369     return false;
370 }
371 
372 // Remote Platform subclasses need to override this function
373 ArchSpec
374 PlatformWindows::GetRemoteSystemArchitecture ()
375 {
376     if (m_remote_platform_sp)
377         return m_remote_platform_sp->GetRemoteSystemArchitecture ();
378     return ArchSpec();
379 }
380 
381 const char *
382 PlatformWindows::GetHostname ()
383 {
384     if (IsHost())
385         return Platform::GetHostname();
386 
387     if (m_remote_platform_sp)
388         return m_remote_platform_sp->GetHostname ();
389     return NULL;
390 }
391 
392 bool
393 PlatformWindows::IsConnected () const
394 {
395     if (IsHost())
396         return true;
397     else if (m_remote_platform_sp)
398         return m_remote_platform_sp->IsConnected();
399     return false;
400 }
401 
402 Error
403 PlatformWindows::ConnectRemote (Args& args)
404 {
405     Error error;
406     if (IsHost())
407     {
408         error.SetErrorStringWithFormat ("can't connect to the host platform '%s', always connected", GetPluginName().AsCString() );
409     }
410     else
411     {
412         if (!m_remote_platform_sp)
413             m_remote_platform_sp = Platform::Create ("remote-gdb-server", error);
414 
415         if (m_remote_platform_sp)
416         {
417             if (error.Success())
418             {
419                 if (m_remote_platform_sp)
420                 {
421                     error = m_remote_platform_sp->ConnectRemote (args);
422                 }
423                 else
424                 {
425                     error.SetErrorString ("\"platform connect\" takes a single argument: <connect-url>");
426                 }
427             }
428         }
429         else
430             error.SetErrorString ("failed to create a 'remote-gdb-server' platform");
431 
432         if (error.Fail())
433             m_remote_platform_sp.reset();
434     }
435 
436     return error;
437 }
438 
439 Error
440 PlatformWindows::DisconnectRemote ()
441 {
442     Error error;
443 
444     if (IsHost())
445     {
446         error.SetErrorStringWithFormat ("can't disconnect from the host platform '%s', always connected", GetPluginName().AsCString() );
447     }
448     else
449     {
450         if (m_remote_platform_sp)
451             error = m_remote_platform_sp->DisconnectRemote ();
452         else
453             error.SetErrorString ("the platform is not currently connected");
454     }
455     return error;
456 }
457 
458 bool
459 PlatformWindows::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
460 {
461     bool success = false;
462     if (IsHost())
463     {
464         success = Platform::GetProcessInfo (pid, process_info);
465     }
466     else if (m_remote_platform_sp)
467     {
468         success = m_remote_platform_sp->GetProcessInfo (pid, process_info);
469     }
470     return success;
471 }
472 
473 uint32_t
474 PlatformWindows::FindProcesses (const ProcessInstanceInfoMatch &match_info,
475                                ProcessInstanceInfoList &process_infos)
476 {
477     uint32_t match_count = 0;
478     if (IsHost())
479     {
480         // Let the base class figure out the host details
481         match_count = Platform::FindProcesses (match_info, process_infos);
482     }
483     else
484     {
485         // If we are remote, we can only return results if we are connected
486         if (m_remote_platform_sp)
487             match_count = m_remote_platform_sp->FindProcesses (match_info, process_infos);
488     }
489     return match_count;
490 }
491 
492 Error
493 PlatformWindows::LaunchProcess (ProcessLaunchInfo &launch_info)
494 {
495     Error error;
496     if (IsHost())
497     {
498         error = Platform::LaunchProcess (launch_info);
499     }
500     else
501     {
502         if (m_remote_platform_sp)
503             error = m_remote_platform_sp->LaunchProcess (launch_info);
504         else
505             error.SetErrorString ("the platform is not currently connected");
506     }
507     return error;
508 }
509 
510 lldb::ProcessSP
511 PlatformWindows::Attach(ProcessAttachInfo &attach_info,
512                         Debugger &debugger,
513                         Target *target,
514                         Listener &listener,
515                         Error &error)
516 {
517     lldb::ProcessSP process_sp;
518     if (IsHost())
519     {
520         if (target == NULL)
521         {
522             TargetSP new_target_sp;
523             FileSpec emptyFileSpec;
524             ArchSpec emptyArchSpec;
525 
526             error = debugger.GetTargetList().CreateTarget (debugger,
527                                                            NULL,
528                                                            NULL,
529                                                            false,
530                                                            NULL,
531                                                            new_target_sp);
532             target = new_target_sp.get();
533         }
534         else
535             error.Clear();
536 
537         if (target && error.Success())
538         {
539             debugger.GetTargetList().SetSelectedTarget(target);
540             // The Windows platform always currently uses the GDB remote debugger plug-in
541             // so even when debugging locally we are debugging remotely!
542             // Just like the darwin plugin.
543             process_sp = target->CreateProcess (listener, "gdb-remote", NULL);
544 
545             if (process_sp)
546                 error = process_sp->Attach (attach_info);
547         }
548     }
549     else
550     {
551         if (m_remote_platform_sp)
552             process_sp = m_remote_platform_sp->Attach (attach_info, debugger, target, listener, error);
553         else
554             error.SetErrorString ("the platform is not currently connected");
555     }
556     return process_sp;
557 }
558 
559 const char *
560 PlatformWindows::GetUserName (uint32_t uid)
561 {
562     // Check the cache in Platform in case we have already looked this uid up
563     const char *user_name = Platform::GetUserName(uid);
564     if (user_name)
565         return user_name;
566 
567     if (IsRemote() && m_remote_platform_sp)
568         return m_remote_platform_sp->GetUserName(uid);
569     return NULL;
570 }
571 
572 const char *
573 PlatformWindows::GetGroupName (uint32_t gid)
574 {
575     const char *group_name = Platform::GetGroupName(gid);
576     if (group_name)
577         return group_name;
578 
579     if (IsRemote() && m_remote_platform_sp)
580         return m_remote_platform_sp->GetGroupName(gid);
581     return NULL;
582 }
583 
584 Error
585 PlatformWindows::GetFileWithUUID (const FileSpec &platform_file,
586                                   const UUID *uuid_ptr,
587                                   FileSpec &local_file)
588 {
589     if (IsRemote())
590     {
591         if (m_remote_platform_sp)
592             return m_remote_platform_sp->GetFileWithUUID (platform_file, uuid_ptr, local_file);
593     }
594 
595     // Default to the local case
596     local_file = platform_file;
597     return Error();
598 }
599 
600 Error
601 PlatformWindows::GetSharedModule (const ModuleSpec &module_spec,
602                                   ModuleSP &module_sp,
603                                   const FileSpecList *module_search_paths_ptr,
604                                   ModuleSP *old_module_sp_ptr,
605                                   bool *did_create_ptr)
606 {
607     Error error;
608     module_sp.reset();
609 
610     if (IsRemote())
611     {
612         // If we have a remote platform always, let it try and locate
613         // the shared module first.
614         if (m_remote_platform_sp)
615         {
616             error = m_remote_platform_sp->GetSharedModule (module_spec,
617                                                            module_sp,
618                                                            module_search_paths_ptr,
619                                                            old_module_sp_ptr,
620                                                            did_create_ptr);
621         }
622     }
623 
624     if (!module_sp)
625     {
626         // Fall back to the local platform and find the file locally
627         error = Platform::GetSharedModule (module_spec,
628                                            module_sp,
629                                            module_search_paths_ptr,
630                                            old_module_sp_ptr,
631                                            did_create_ptr);
632     }
633     if (module_sp)
634         module_sp->SetPlatformFileSpec(module_spec.GetFileSpec());
635     return error;
636 }
637 
638 bool
639 PlatformWindows::GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch)
640 {
641     static SupportedArchList architectures;
642 
643     if (idx >= architectures.Count())
644         return false;
645     arch = architectures[idx];
646     return true;
647 }
648 
649 void
650 PlatformWindows::GetStatus (Stream &strm)
651 {
652     Platform::GetStatus(strm);
653 
654 #ifdef _WIN32
655     uint32_t major;
656     uint32_t minor;
657     uint32_t update;
658     if (!Host::GetOSVersion(major, minor, update))
659     {
660         strm << "Windows";
661         return;
662     }
663 
664     strm << "Host: Windows " << major
665          << '.' << minor
666          << " Build: " << update << '\n';
667 #endif
668 }
669