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