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