1 //===-- PlatformLinux.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 "lldb/lldb-python.h"
11 
12 #include "PlatformLinux.h"
13 #include "lldb/Host/Config.h"
14 
15 // C Includes
16 #include <stdio.h>
17 #ifndef LLDB_DISABLE_POSIX
18 #include <sys/utsname.h>
19 #endif
20 
21 // C++ Includes
22 // Other libraries and framework includes
23 // Project includes
24 #include "lldb/Breakpoint/BreakpointLocation.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Core/Error.h"
27 #include "lldb/Core/Log.h"
28 #include "lldb/Core/Module.h"
29 #include "lldb/Core/ModuleList.h"
30 #include "lldb/Core/ModuleSpec.h"
31 #include "lldb/Core/PluginManager.h"
32 #include "lldb/Core/State.h"
33 #include "lldb/Core/StreamString.h"
34 #include "lldb/Host/FileSpec.h"
35 #include "lldb/Host/HostInfo.h"
36 #include "lldb/Interpreter/OptionValueProperties.h"
37 #include "lldb/Interpreter/Property.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/Process.h"
40 
41 #if defined(__linux__)
42 #include "../../Process/Linux/NativeProcessLinux.h"
43 #endif
44 
45 using namespace lldb;
46 using namespace lldb_private;
47 
48 static uint32_t g_initialize_count = 0;
49 
50 //------------------------------------------------------------------
51 /// Code to handle the PlatformLinux settings
52 //------------------------------------------------------------------
53 
54 namespace
55 {
56     enum
57     {
58         ePropertyUseLlgsForLocal = 0,
59     };
60 
61     const PropertyDefinition*
62     GetStaticPropertyDefinitions ()
63     {
64         static PropertyDefinition
65         g_properties[] =
66         {
67             { "use-llgs-for-local" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "Control whether the platform uses llgs for local debug sessions." },
68             {  NULL        , OptionValue::eTypeInvalid, false, 0  , NULL, NULL, NULL  }
69         };
70 
71         // Allow environment variable to force using llgs-local.
72         if (getenv("PLATFORM_LINUX_FORCE_LLGS_LOCAL"))
73             g_properties[ePropertyUseLlgsForLocal].default_uint_value = true;
74 
75         return g_properties;
76     }
77 }
78 
79 class PlatformLinuxProperties : public Properties
80 {
81 public:
82 
83     static ConstString &
84     GetSettingName ()
85     {
86         static ConstString g_setting_name("linux");
87         return g_setting_name;
88     }
89 
90     PlatformLinuxProperties() :
91     Properties ()
92     {
93         m_collection_sp.reset (new OptionValueProperties(GetSettingName ()));
94         m_collection_sp->Initialize (GetStaticPropertyDefinitions ());
95     }
96 
97     virtual
98     ~PlatformLinuxProperties()
99     {
100     }
101 
102     bool
103     GetUseLlgsForLocal() const
104     {
105         const uint32_t idx = ePropertyUseLlgsForLocal;
106         return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, GetStaticPropertyDefinitions()[idx].default_uint_value != 0);
107     }
108 };
109 
110 typedef std::shared_ptr<PlatformLinuxProperties> PlatformLinuxPropertiesSP;
111 
112 static const PlatformLinuxPropertiesSP &
113 GetGlobalProperties()
114 {
115     static PlatformLinuxPropertiesSP g_settings_sp;
116     if (!g_settings_sp)
117         g_settings_sp.reset (new PlatformLinuxProperties ());
118     return g_settings_sp;
119 }
120 
121 void
122 PlatformLinux::DebuggerInitialize (lldb_private::Debugger &debugger)
123 {
124     if (!PluginManager::GetSettingForPlatformPlugin (debugger, PlatformLinuxProperties::GetSettingName()))
125     {
126         const bool is_global_setting = true;
127         PluginManager::CreateSettingForPlatformPlugin (debugger,
128                                                        GetGlobalProperties()->GetValueProperties(),
129                                                        ConstString ("Properties for the PlatformLinux plug-in."),
130                                                        is_global_setting);
131     }
132 }
133 
134 
135 //------------------------------------------------------------------
136 
137 PlatformSP
138 PlatformLinux::CreateInstance (bool force, const ArchSpec *arch)
139 {
140     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
141     if (log)
142     {
143         const char *arch_name;
144         if (arch && arch->GetArchitectureName ())
145             arch_name = arch->GetArchitectureName ();
146         else
147             arch_name = "<null>";
148 
149         const char *triple_cstr = arch ? arch->GetTriple ().getTriple ().c_str() : "<null>";
150 
151         log->Printf ("PlatformLinux::%s(force=%s, arch={%s,%s})", __FUNCTION__, force ? "true" : "false", arch_name, triple_cstr);
152     }
153 
154     bool create = force;
155     if (create == false && arch && arch->IsValid())
156     {
157         const llvm::Triple &triple = arch->GetTriple();
158         switch (triple.getVendor())
159         {
160             case llvm::Triple::PC:
161                 create = true;
162                 break;
163 
164 #if defined(__linux__)
165             // Only accept "unknown" for the vendor if the host is linux and
166             // it "unknown" wasn't specified (it was just returned because it
167             // was NOT specified_
168             case llvm::Triple::VendorType::UnknownVendor:
169                 create = !arch->TripleVendorWasSpecified();
170                 break;
171 #endif
172             default:
173                 break;
174         }
175 
176         if (create)
177         {
178             switch (triple.getOS())
179             {
180                 case llvm::Triple::Linux:
181                     break;
182 
183 #if defined(__linux__)
184                 // Only accept "unknown" for the OS if the host is linux and
185                 // it "unknown" wasn't specified (it was just returned because it
186                 // was NOT specified)
187                 case llvm::Triple::OSType::UnknownOS:
188                     create = !arch->TripleOSWasSpecified();
189                     break;
190 #endif
191                 default:
192                     create = false;
193                     break;
194             }
195         }
196     }
197 
198     if (create)
199     {
200         if (log)
201             log->Printf ("PlatformLinux::%s() creating remote-linux platform", __FUNCTION__);
202         return PlatformSP(new PlatformLinux(false));
203     }
204 
205     if (log)
206         log->Printf ("PlatformLinux::%s() aborting creation of remote-linux platform", __FUNCTION__);
207 
208     return PlatformSP();
209 }
210 
211 
212 lldb_private::ConstString
213 PlatformLinux::GetPluginNameStatic (bool is_host)
214 {
215     if (is_host)
216     {
217         static ConstString g_host_name(Platform::GetHostPlatformName ());
218         return g_host_name;
219     }
220     else
221     {
222         static ConstString g_remote_name("remote-linux");
223         return g_remote_name;
224     }
225 }
226 
227 const char *
228 PlatformLinux::GetPluginDescriptionStatic (bool is_host)
229 {
230     if (is_host)
231         return "Local Linux user platform plug-in.";
232     else
233         return "Remote Linux user platform plug-in.";
234 }
235 
236 lldb_private::ConstString
237 PlatformLinux::GetPluginName()
238 {
239     return GetPluginNameStatic(IsHost());
240 }
241 
242 void
243 PlatformLinux::Initialize ()
244 {
245     if (g_initialize_count++ == 0)
246     {
247 #if defined(__linux__)
248         PlatformSP default_platform_sp (new PlatformLinux(true));
249         default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
250         Platform::SetHostPlatform (default_platform_sp);
251 #endif
252         PluginManager::RegisterPlugin(PlatformLinux::GetPluginNameStatic(false),
253                                       PlatformLinux::GetPluginDescriptionStatic(false),
254                                       PlatformLinux::CreateInstance,
255                                       PlatformLinux::DebuggerInitialize);
256     }
257 }
258 
259 void
260 PlatformLinux::Terminate ()
261 {
262     if (g_initialize_count > 0)
263     {
264         if (--g_initialize_count == 0)
265         {
266             PluginManager::UnregisterPlugin (PlatformLinux::CreateInstance);
267         }
268     }
269 }
270 
271 Error
272 PlatformLinux::ResolveExecutable (const ModuleSpec &ms,
273                                   lldb::ModuleSP &exe_module_sp,
274                                   const FileSpecList *module_search_paths_ptr)
275 {
276     Error error;
277     // Nothing special to do here, just use the actual file and architecture
278 
279     char exe_path[PATH_MAX];
280     ModuleSpec resolved_module_spec (ms);
281 
282     if (IsHost())
283     {
284         // If we have "ls" as the exe_file, resolve the executable location based on
285         // the current path variables
286         if (!resolved_module_spec.GetFileSpec().Exists())
287         {
288             resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
289             resolved_module_spec.GetFileSpec().SetFile(exe_path, true);
290         }
291 
292         if (!resolved_module_spec.GetFileSpec().Exists())
293             resolved_module_spec.GetFileSpec().ResolveExecutableLocation ();
294 
295         if (resolved_module_spec.GetFileSpec().Exists())
296             error.Clear();
297         else
298         {
299             error.SetErrorStringWithFormat("unable to find executable for '%s'", resolved_module_spec.GetFileSpec().GetPath().c_str());
300         }
301     }
302     else
303     {
304         if (m_remote_platform_sp)
305         {
306             error = m_remote_platform_sp->ResolveExecutable (ms,
307                                                              exe_module_sp,
308                                                              NULL);
309         }
310         else
311         {
312             // We may connect to a process and use the provided executable (Don't use local $PATH).
313 
314             if (resolved_module_spec.GetFileSpec().Exists())
315                 error.Clear();
316             else
317                 error.SetErrorStringWithFormat("the platform is not currently connected, and '%s' doesn't exist in the system root.", exe_path);
318         }
319     }
320 
321     if (error.Success())
322     {
323         if (resolved_module_spec.GetArchitecture().IsValid())
324         {
325             error = ModuleList::GetSharedModule (resolved_module_spec,
326                                                  exe_module_sp,
327                                                  NULL,
328                                                  NULL,
329                                                  NULL);
330             if (error.Fail())
331             {
332                 // If we failed, it may be because the vendor and os aren't known. If that is the
333                 // case, try setting them to the host architecture and give it another try.
334                 llvm::Triple &module_triple = resolved_module_spec.GetArchitecture().GetTriple();
335                 bool is_vendor_specified = (module_triple.getVendor() != llvm::Triple::UnknownVendor);
336                 bool is_os_specified = (module_triple.getOS() != llvm::Triple::UnknownOS);
337                 if (!is_vendor_specified || !is_os_specified)
338                 {
339                     const llvm::Triple &host_triple = HostInfo::GetArchitecture(HostInfo::eArchKindDefault).GetTriple();
340 
341                     if (!is_vendor_specified)
342                         module_triple.setVendorName (host_triple.getVendorName());
343                     if (!is_os_specified)
344                         module_triple.setOSName (host_triple.getOSName());
345 
346                     error = ModuleList::GetSharedModule (resolved_module_spec,
347                                                          exe_module_sp,
348                                                          NULL,
349                                                          NULL,
350                                                          NULL);
351                 }
352             }
353 
354             // TODO find out why exe_module_sp might be NULL
355             if (!exe_module_sp || exe_module_sp->GetObjectFile() == NULL)
356             {
357                 exe_module_sp.reset();
358                 error.SetErrorStringWithFormat ("'%s' doesn't contain the architecture %s",
359                                                 resolved_module_spec.GetFileSpec().GetPath().c_str(),
360                                                 resolved_module_spec.GetArchitecture().GetArchitectureName());
361             }
362         }
363         else
364         {
365             // No valid architecture was specified, ask the platform for
366             // the architectures that we should be using (in the correct order)
367             // and see if we can find a match that way
368             StreamString arch_names;
369             for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, resolved_module_spec.GetArchitecture()); ++idx)
370             {
371                 error = ModuleList::GetSharedModule (resolved_module_spec,
372                                                      exe_module_sp,
373                                                      NULL,
374                                                      NULL,
375                                                      NULL);
376                 // Did we find an executable using one of the
377                 if (error.Success())
378                 {
379                     if (exe_module_sp && exe_module_sp->GetObjectFile())
380                         break;
381                     else
382                         error.SetErrorToGenericError();
383                 }
384 
385                 if (idx > 0)
386                     arch_names.PutCString (", ");
387                 arch_names.PutCString (resolved_module_spec.GetArchitecture().GetArchitectureName());
388             }
389 
390             if (error.Fail() || !exe_module_sp)
391             {
392                 if (resolved_module_spec.GetFileSpec().Readable())
393                 {
394                     error.SetErrorStringWithFormat ("'%s' doesn't contain any '%s' platform architectures: %s",
395                                                     resolved_module_spec.GetFileSpec().GetPath().c_str(),
396                                                     GetPluginName().GetCString(),
397                                                     arch_names.GetString().c_str());
398                 }
399                 else
400                 {
401                     error.SetErrorStringWithFormat("'%s' is not readable", resolved_module_spec.GetFileSpec().GetPath().c_str());
402                 }
403             }
404         }
405     }
406 
407     return error;
408 }
409 
410 Error
411 PlatformLinux::GetFileWithUUID (const FileSpec &platform_file,
412                                 const UUID *uuid_ptr, FileSpec &local_file)
413 {
414     if (IsRemote())
415     {
416         if (m_remote_platform_sp)
417             return m_remote_platform_sp->GetFileWithUUID (platform_file, uuid_ptr, local_file);
418     }
419 
420     // Default to the local case
421     local_file = platform_file;
422     return Error();
423 }
424 
425 
426 //------------------------------------------------------------------
427 /// Default Constructor
428 //------------------------------------------------------------------
429 PlatformLinux::PlatformLinux (bool is_host) :
430     PlatformPOSIX(is_host)  // This is the local host platform
431 {
432 }
433 
434 //------------------------------------------------------------------
435 /// Destructor.
436 ///
437 /// The destructor is virtual since this class is designed to be
438 /// inherited from by the plug-in instance.
439 //------------------------------------------------------------------
440 PlatformLinux::~PlatformLinux()
441 {
442 }
443 
444 bool
445 PlatformLinux::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
446 {
447     bool success = false;
448     if (IsHost())
449     {
450         success = Platform::GetProcessInfo (pid, process_info);
451     }
452     else
453     {
454         if (m_remote_platform_sp)
455             success = m_remote_platform_sp->GetProcessInfo (pid, process_info);
456     }
457     return success;
458 }
459 
460 uint32_t
461 PlatformLinux::FindProcesses (const ProcessInstanceInfoMatch &match_info,
462                               ProcessInstanceInfoList &process_infos)
463 {
464     uint32_t match_count = 0;
465     if (IsHost())
466     {
467         // Let the base class figure out the host details
468         match_count = Platform::FindProcesses (match_info, process_infos);
469     }
470     else
471     {
472         // If we are remote, we can only return results if we are connected
473         if (m_remote_platform_sp)
474             match_count = m_remote_platform_sp->FindProcesses (match_info, process_infos);
475     }
476     return match_count;
477 }
478 
479 bool
480 PlatformLinux::GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch)
481 {
482     if (idx == 0)
483     {
484         arch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
485         return arch.IsValid();
486     }
487     else if (idx == 1)
488     {
489         // If the default host architecture is 64-bit, look for a 32-bit variant
490         ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
491         if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit())
492         {
493             arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
494             return arch.IsValid();
495         }
496     }
497     return false;
498 }
499 
500 void
501 PlatformLinux::GetStatus (Stream &strm)
502 {
503     Platform::GetStatus(strm);
504 
505 #ifndef LLDB_DISABLE_POSIX
506     // Display local kernel information only when we are running in host mode.
507     // Otherwise, we would end up printing non-Linux information (when running
508     // on Mac OS for example).
509     if (IsHost())
510     {
511         struct utsname un;
512 
513         if (uname(&un))
514             return;
515 
516         strm.Printf ("    Kernel: %s\n", un.sysname);
517         strm.Printf ("   Release: %s\n", un.release);
518         strm.Printf ("   Version: %s\n", un.version);
519     }
520 #endif
521 }
522 
523 size_t
524 PlatformLinux::GetSoftwareBreakpointTrapOpcode (Target &target,
525                                                 BreakpointSite *bp_site)
526 {
527     ArchSpec arch = target.GetArchitecture();
528     const uint8_t *trap_opcode = NULL;
529     size_t trap_opcode_size = 0;
530 
531     switch (arch.GetMachine())
532     {
533     default:
534         assert(false && "CPU type not supported!");
535         break;
536 
537     case llvm::Triple::aarch64:
538         {
539             static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
540             trap_opcode = g_aarch64_opcode;
541             trap_opcode_size = sizeof(g_aarch64_opcode);
542         }
543         break;
544     case llvm::Triple::x86:
545     case llvm::Triple::x86_64:
546         {
547             static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
548             trap_opcode = g_i386_breakpoint_opcode;
549             trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
550         }
551         break;
552     case llvm::Triple::hexagon:
553         {
554             static const uint8_t g_hex_opcode[] = { 0x0c, 0xdb, 0x00, 0x54 };
555             trap_opcode = g_hex_opcode;
556             trap_opcode_size = sizeof(g_hex_opcode);
557         }
558         break;
559     case llvm::Triple::arm:
560         {
561             // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
562             // but the linux kernel does otherwise.
563             static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
564             static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
565 
566             lldb::BreakpointLocationSP bp_loc_sp (bp_site->GetOwnerAtIndex (0));
567             AddressClass addr_class = eAddressClassUnknown;
568 
569             if (bp_loc_sp)
570                 addr_class = bp_loc_sp->GetAddress ().GetAddressClass ();
571 
572             if (addr_class == eAddressClassCodeAlternateISA
573                 || (addr_class == eAddressClassUnknown
574                     && bp_loc_sp->GetAddress().GetOffset() & 1))
575             {
576                 trap_opcode = g_thumb_breakpoint_opcode;
577                 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
578             }
579             else
580             {
581                 trap_opcode = g_arm_breakpoint_opcode;
582                 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
583             }
584         }
585         break;
586     case llvm::Triple::mips64:
587         {
588             static const uint8_t g_hex_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
589             trap_opcode = g_hex_opcode;
590             trap_opcode_size = sizeof(g_hex_opcode);
591         }
592         break;
593     }
594 
595     if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
596         return trap_opcode_size;
597     return 0;
598 }
599 
600 int32_t
601 PlatformLinux::GetResumeCountForLaunchInfo (ProcessLaunchInfo &launch_info)
602 {
603     int32_t resume_count = 0;
604 
605     // Always resume past the initial stop when we use eLaunchFlagDebug
606     if (launch_info.GetFlags ().Test (eLaunchFlagDebug))
607     {
608         // Resume past the stop for the final exec into the true inferior.
609         ++resume_count;
610     }
611 
612     // If we're not launching a shell, we're done.
613     const FileSpec &shell = launch_info.GetShell();
614     if (!shell)
615         return resume_count;
616 
617     std::string shell_string = shell.GetPath();
618     // We're in a shell, so for sure we have to resume past the shell exec.
619     ++resume_count;
620 
621     // Figure out what shell we're planning on using.
622     const char *shell_name = strrchr (shell_string.c_str(), '/');
623     if (shell_name == NULL)
624         shell_name = shell_string.c_str();
625     else
626         shell_name++;
627 
628     if (strcmp (shell_name, "csh") == 0
629              || strcmp (shell_name, "tcsh") == 0
630              || strcmp (shell_name, "zsh") == 0
631              || strcmp (shell_name, "sh") == 0)
632     {
633         // These shells seem to re-exec themselves.  Add another resume.
634         ++resume_count;
635     }
636 
637     return resume_count;
638 }
639 
640 bool
641 PlatformLinux::UseLlgsForLocalDebugging ()
642 {
643     PlatformLinuxPropertiesSP properties_sp = GetGlobalProperties ();
644     assert (properties_sp && "global properties shared pointer is null");
645     return properties_sp ? properties_sp->GetUseLlgsForLocal () : false;
646 }
647 
648 bool
649 PlatformLinux::CanDebugProcess ()
650 {
651     if (IsHost ())
652     {
653         // The platform only does local debugging (i.e. uses llgs) when the setting indicates we do that.
654         // Otherwise, we'll use ProcessLinux/ProcessPOSIX to handle with ProcessMonitor.
655         return UseLlgsForLocalDebugging ();
656     }
657     else
658     {
659         // If we're connected, we can debug.
660         return IsConnected ();
661     }
662 }
663 
664 // For local debugging, Linux will override the debug logic to use llgs-launch rather than
665 // lldb-launch, llgs-attach.  This differs from current lldb-launch, debugserver-attach
666 // approach on MacOSX.
667 lldb::ProcessSP
668 PlatformLinux::DebugProcess (ProcessLaunchInfo &launch_info,
669                              Debugger &debugger,
670                              Target *target,       // Can be NULL, if NULL create a new target, else use existing one
671                              Error &error)
672 {
673     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
674     if (log)
675         log->Printf ("PlatformLinux::%s entered (target %p)", __FUNCTION__, static_cast<void*>(target));
676 
677     // If we're a remote host, use standard behavior from parent class.
678     if (!IsHost ())
679         return PlatformPOSIX::DebugProcess (launch_info, debugger, target, error);
680 
681     //
682     // For local debugging, we'll insist on having ProcessGDBRemote create the process.
683     //
684 
685     ProcessSP process_sp;
686 
687     // Ensure we're using llgs for local debugging.
688     if (!UseLlgsForLocalDebugging ())
689     {
690         assert (false && "we're trying to debug a local process but platform.plugin.linux.use-llgs-for-local is false, should never get here");
691         error.SetErrorString ("attempted to start gdb-remote-based debugging for local process but platform.plugin.linux.use-llgs-for-local is false");
692         return process_sp;
693     }
694 
695     // Make sure we stop at the entry point
696     launch_info.GetFlags ().Set (eLaunchFlagDebug);
697 
698     // We always launch the process we are going to debug in a separate process
699     // group, since then we can handle ^C interrupts ourselves w/o having to worry
700     // about the target getting them as well.
701     launch_info.SetLaunchInSeparateProcessGroup(true);
702 
703     // Ensure we have a target.
704     if (target == nullptr)
705     {
706         if (log)
707             log->Printf ("PlatformLinux::%s creating new target", __FUNCTION__);
708 
709         TargetSP new_target_sp;
710         error = debugger.GetTargetList().CreateTarget (debugger,
711                                                        nullptr,
712                                                        nullptr,
713                                                        false,
714                                                        nullptr,
715                                                        new_target_sp);
716         if (error.Fail ())
717         {
718             if (log)
719                 log->Printf ("PlatformLinux::%s failed to create new target: %s", __FUNCTION__, error.AsCString ());
720             return process_sp;
721         }
722 
723         target = new_target_sp.get();
724         if (!target)
725         {
726             error.SetErrorString ("CreateTarget() returned nullptr");
727             if (log)
728                 log->Printf ("PlatformLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
729             return process_sp;
730         }
731     }
732     else
733     {
734         if (log)
735             log->Printf ("PlatformLinux::%s using provided target", __FUNCTION__);
736     }
737 
738     // Mark target as currently selected target.
739     debugger.GetTargetList().SetSelectedTarget(target);
740 
741     // Now create the gdb-remote process.
742     if (log)
743         log->Printf ("PlatformLinux::%s having target create process with gdb-remote plugin", __FUNCTION__);
744     process_sp = target->CreateProcess (launch_info.GetListenerForProcess(debugger), "gdb-remote", nullptr);
745 
746     if (!process_sp)
747     {
748         error.SetErrorString ("CreateProcess() failed for gdb-remote process");
749         if (log)
750             log->Printf ("PlatformLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
751         return process_sp;
752     }
753     else
754     {
755         if (log)
756             log->Printf ("PlatformLinux::%s successfully created process", __FUNCTION__);
757     }
758 
759     // Set the unix signals properly.
760     process_sp->SetUnixSignals (Host::GetUnixSignals ());
761 
762     // Adjust launch for a hijacker.
763     ListenerSP listener_sp;
764     if (!launch_info.GetHijackListener ())
765     {
766         if (log)
767             log->Printf ("PlatformLinux::%s setting up hijacker", __FUNCTION__);
768 
769         listener_sp.reset (new Listener("lldb.PlatformLinux.DebugProcess.hijack"));
770         launch_info.SetHijackListener (listener_sp);
771         process_sp->HijackProcessEvents (listener_sp.get ());
772     }
773 
774     // Log file actions.
775     if (log)
776     {
777         log->Printf ("PlatformLinux::%s launching process with the following file actions:", __FUNCTION__);
778 
779         StreamString stream;
780         size_t i = 0;
781         const FileAction *file_action;
782         while ((file_action = launch_info.GetFileActionAtIndex (i++)) != nullptr)
783         {
784             file_action->Dump (stream);
785             log->PutCString (stream.GetString().c_str ());
786             stream.Clear();
787         }
788     }
789 
790     // Do the launch.
791     error = process_sp->Launch(launch_info);
792     if (error.Success ())
793     {
794         // Handle the hijacking of process events.
795         if (listener_sp)
796         {
797             const StateType state = process_sp->WaitForProcessToStop (NULL, NULL, false, listener_sp.get());
798             process_sp->RestoreProcessEvents();
799 
800             if (state == eStateStopped)
801             {
802                 if (log)
803                     log->Printf ("PlatformLinux::%s pid %" PRIu64 " state %s\n",
804                                  __FUNCTION__, process_sp->GetID (), StateAsCString (state));
805             }
806             else
807             {
808                 if (log)
809                     log->Printf ("PlatformLinux::%s pid %" PRIu64 " state is not stopped - %s\n",
810                                  __FUNCTION__, process_sp->GetID (), StateAsCString (state));
811             }
812         }
813 
814         // Hook up process PTY if we have one (which we should for local debugging with llgs).
815         int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
816         if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd)
817         {
818             process_sp->SetSTDIOFileDescriptor(pty_fd);
819             if (log)
820                 log->Printf ("PlatformLinux::%s pid %" PRIu64 " hooked up STDIO pty to process", __FUNCTION__, process_sp->GetID ());
821         }
822         else
823         {
824             if (log)
825                 log->Printf ("PlatformLinux::%s pid %" PRIu64 " not using process STDIO pty", __FUNCTION__, process_sp->GetID ());
826         }
827     }
828     else
829     {
830         if (log)
831             log->Printf ("PlatformLinux::%s process launch failed: %s", __FUNCTION__, error.AsCString ());
832         // FIXME figure out appropriate cleanup here.  Do we delete the target? Do we delete the process?  Does our caller do that?
833     }
834 
835     return process_sp;
836 }
837 
838 void
839 PlatformLinux::CalculateTrapHandlerSymbolNames ()
840 {
841     m_trap_handlers.push_back (ConstString ("_sigtramp"));
842 }
843 
844 Error
845 PlatformLinux::LaunchNativeProcess (
846     ProcessLaunchInfo &launch_info,
847     lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
848     NativeProcessProtocolSP &process_sp)
849 {
850 #if !defined(__linux__) || defined(__ANDROID_NDK__)
851     return Error("only implemented on Linux hosts");
852 #else
853     if (!IsHost ())
854         return Error("PlatformLinux::%s (): cannot launch a debug process when not the host", __FUNCTION__);
855 
856     // Retrieve the exe module.
857     lldb::ModuleSP exe_module_sp;
858     ModuleSpec exe_module_spec(launch_info.GetExecutableFile(), launch_info.GetArchitecture());
859 
860     Error error = ResolveExecutable (
861         exe_module_spec,
862         exe_module_sp,
863         NULL);
864 
865     if (!error.Success ())
866         return error;
867 
868     if (!exe_module_sp)
869         return Error("exe_module_sp could not be resolved for %s", launch_info.GetExecutableFile ().GetPath ().c_str ());
870 
871     // Launch it for debugging
872     error = NativeProcessLinux::LaunchProcess (
873         exe_module_sp.get (),
874         launch_info,
875         native_delegate,
876         process_sp);
877 
878     return error;
879 #endif
880 }
881 
882 Error
883 PlatformLinux::AttachNativeProcess (lldb::pid_t pid,
884                                     lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
885                                     NativeProcessProtocolSP &process_sp)
886 {
887 #if !defined(__linux__) || defined(__ANDROID_NDK__)
888     return Error("only implemented on Linux hosts");
889 #else
890     if (!IsHost ())
891         return Error("PlatformLinux::%s (): cannot attach to a debug process when not the host", __FUNCTION__);
892 
893     // Launch it for debugging
894     return NativeProcessLinux::AttachToProcess (pid, native_delegate, process_sp);
895 #endif
896 }
897