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     PlatformPOSIX::Initialize ();
246 
247     if (g_initialize_count++ == 0)
248     {
249 #if defined(__linux__) && !defined(__ANDROID__)
250         PlatformSP default_platform_sp (new PlatformLinux(true));
251         default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
252         Platform::SetHostPlatform (default_platform_sp);
253 #endif
254         PluginManager::RegisterPlugin(PlatformLinux::GetPluginNameStatic(false),
255                                       PlatformLinux::GetPluginDescriptionStatic(false),
256                                       PlatformLinux::CreateInstance,
257                                       PlatformLinux::DebuggerInitialize);
258     }
259 }
260 
261 void
262 PlatformLinux::Terminate ()
263 {
264     if (g_initialize_count > 0)
265     {
266         if (--g_initialize_count == 0)
267         {
268             PluginManager::UnregisterPlugin (PlatformLinux::CreateInstance);
269         }
270     }
271 
272     PlatformPOSIX::Terminate ();
273 }
274 
275 Error
276 PlatformLinux::ResolveExecutable (const ModuleSpec &ms,
277                                   lldb::ModuleSP &exe_module_sp,
278                                   const FileSpecList *module_search_paths_ptr)
279 {
280     Error error;
281     // Nothing special to do here, just use the actual file and architecture
282 
283     char exe_path[PATH_MAX];
284     ModuleSpec resolved_module_spec (ms);
285 
286     if (IsHost())
287     {
288         // If we have "ls" as the exe_file, resolve the executable location based on
289         // the current path variables
290         if (!resolved_module_spec.GetFileSpec().Exists())
291         {
292             resolved_module_spec.GetFileSpec().GetPath(exe_path, sizeof(exe_path));
293             resolved_module_spec.GetFileSpec().SetFile(exe_path, true);
294         }
295 
296         if (!resolved_module_spec.GetFileSpec().Exists())
297             resolved_module_spec.GetFileSpec().ResolveExecutableLocation ();
298 
299         if (resolved_module_spec.GetFileSpec().Exists())
300             error.Clear();
301         else
302         {
303             error.SetErrorStringWithFormat("unable to find executable for '%s'", resolved_module_spec.GetFileSpec().GetPath().c_str());
304         }
305     }
306     else
307     {
308         if (m_remote_platform_sp)
309         {
310             error = m_remote_platform_sp->ResolveExecutable (ms,
311                                                              exe_module_sp,
312                                                              NULL);
313         }
314         else
315         {
316             // We may connect to a process and use the provided executable (Don't use local $PATH).
317 
318             if (resolved_module_spec.GetFileSpec().Exists())
319                 error.Clear();
320             else
321                 error.SetErrorStringWithFormat("the platform is not currently connected, and '%s' doesn't exist in the system root.", exe_path);
322         }
323     }
324 
325     if (error.Success())
326     {
327         if (resolved_module_spec.GetArchitecture().IsValid())
328         {
329             error = ModuleList::GetSharedModule (resolved_module_spec,
330                                                  exe_module_sp,
331                                                  NULL,
332                                                  NULL,
333                                                  NULL);
334             if (error.Fail())
335             {
336                 // If we failed, it may be because the vendor and os aren't known. If that is the
337                 // case, try setting them to the host architecture and give it another try.
338                 llvm::Triple &module_triple = resolved_module_spec.GetArchitecture().GetTriple();
339                 bool is_vendor_specified = (module_triple.getVendor() != llvm::Triple::UnknownVendor);
340                 bool is_os_specified = (module_triple.getOS() != llvm::Triple::UnknownOS);
341                 if (!is_vendor_specified || !is_os_specified)
342                 {
343                     const llvm::Triple &host_triple = HostInfo::GetArchitecture(HostInfo::eArchKindDefault).GetTriple();
344 
345                     if (!is_vendor_specified)
346                         module_triple.setVendorName (host_triple.getVendorName());
347                     if (!is_os_specified)
348                         module_triple.setOSName (host_triple.getOSName());
349 
350                     error = ModuleList::GetSharedModule (resolved_module_spec,
351                                                          exe_module_sp,
352                                                          NULL,
353                                                          NULL,
354                                                          NULL);
355                 }
356             }
357 
358             // TODO find out why exe_module_sp might be NULL
359             if (!exe_module_sp || exe_module_sp->GetObjectFile() == NULL)
360             {
361                 exe_module_sp.reset();
362                 error.SetErrorStringWithFormat ("'%s' doesn't contain the architecture %s",
363                                                 resolved_module_spec.GetFileSpec().GetPath().c_str(),
364                                                 resolved_module_spec.GetArchitecture().GetArchitectureName());
365             }
366         }
367         else
368         {
369             // No valid architecture was specified, ask the platform for
370             // the architectures that we should be using (in the correct order)
371             // and see if we can find a match that way
372             StreamString arch_names;
373             for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, resolved_module_spec.GetArchitecture()); ++idx)
374             {
375                 error = ModuleList::GetSharedModule (resolved_module_spec,
376                                                      exe_module_sp,
377                                                      NULL,
378                                                      NULL,
379                                                      NULL);
380                 // Did we find an executable using one of the
381                 if (error.Success())
382                 {
383                     if (exe_module_sp && exe_module_sp->GetObjectFile())
384                         break;
385                     else
386                         error.SetErrorToGenericError();
387                 }
388 
389                 if (idx > 0)
390                     arch_names.PutCString (", ");
391                 arch_names.PutCString (resolved_module_spec.GetArchitecture().GetArchitectureName());
392             }
393 
394             if (error.Fail() || !exe_module_sp)
395             {
396                 if (resolved_module_spec.GetFileSpec().Readable())
397                 {
398                     error.SetErrorStringWithFormat ("'%s' doesn't contain any '%s' platform architectures: %s",
399                                                     resolved_module_spec.GetFileSpec().GetPath().c_str(),
400                                                     GetPluginName().GetCString(),
401                                                     arch_names.GetString().c_str());
402                 }
403                 else
404                 {
405                     error.SetErrorStringWithFormat("'%s' is not readable", resolved_module_spec.GetFileSpec().GetPath().c_str());
406                 }
407             }
408         }
409     }
410 
411     return error;
412 }
413 
414 Error
415 PlatformLinux::GetFileWithUUID (const FileSpec &platform_file,
416                                 const UUID *uuid_ptr, FileSpec &local_file)
417 {
418     if (IsRemote())
419     {
420         if (m_remote_platform_sp)
421             return m_remote_platform_sp->GetFileWithUUID (platform_file, uuid_ptr, local_file);
422     }
423 
424     // Default to the local case
425     local_file = platform_file;
426     return Error();
427 }
428 
429 
430 //------------------------------------------------------------------
431 /// Default Constructor
432 //------------------------------------------------------------------
433 PlatformLinux::PlatformLinux (bool is_host) :
434     PlatformPOSIX(is_host)  // This is the local host platform
435 {
436 }
437 
438 //------------------------------------------------------------------
439 /// Destructor.
440 ///
441 /// The destructor is virtual since this class is designed to be
442 /// inherited from by the plug-in instance.
443 //------------------------------------------------------------------
444 PlatformLinux::~PlatformLinux()
445 {
446 }
447 
448 bool
449 PlatformLinux::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
450 {
451     bool success = false;
452     if (IsHost())
453     {
454         success = Platform::GetProcessInfo (pid, process_info);
455     }
456     else
457     {
458         if (m_remote_platform_sp)
459             success = m_remote_platform_sp->GetProcessInfo (pid, process_info);
460     }
461     return success;
462 }
463 
464 uint32_t
465 PlatformLinux::FindProcesses (const ProcessInstanceInfoMatch &match_info,
466                               ProcessInstanceInfoList &process_infos)
467 {
468     uint32_t match_count = 0;
469     if (IsHost())
470     {
471         // Let the base class figure out the host details
472         match_count = Platform::FindProcesses (match_info, process_infos);
473     }
474     else
475     {
476         // If we are remote, we can only return results if we are connected
477         if (m_remote_platform_sp)
478             match_count = m_remote_platform_sp->FindProcesses (match_info, process_infos);
479     }
480     return match_count;
481 }
482 
483 bool
484 PlatformLinux::GetSupportedArchitectureAtIndex (uint32_t idx, ArchSpec &arch)
485 {
486     if (idx == 0)
487     {
488         arch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
489         return arch.IsValid();
490     }
491     else if (idx == 1)
492     {
493         // If the default host architecture is 64-bit, look for a 32-bit variant
494         ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
495         if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit())
496         {
497             arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
498             return arch.IsValid();
499         }
500     }
501     return false;
502 }
503 
504 void
505 PlatformLinux::GetStatus (Stream &strm)
506 {
507     Platform::GetStatus(strm);
508 
509 #ifndef LLDB_DISABLE_POSIX
510     // Display local kernel information only when we are running in host mode.
511     // Otherwise, we would end up printing non-Linux information (when running
512     // on Mac OS for example).
513     if (IsHost())
514     {
515         struct utsname un;
516 
517         if (uname(&un))
518             return;
519 
520         strm.Printf ("    Kernel: %s\n", un.sysname);
521         strm.Printf ("   Release: %s\n", un.release);
522         strm.Printf ("   Version: %s\n", un.version);
523     }
524 #endif
525 }
526 
527 size_t
528 PlatformLinux::GetSoftwareBreakpointTrapOpcode (Target &target,
529                                                 BreakpointSite *bp_site)
530 {
531     ArchSpec arch = target.GetArchitecture();
532     const uint8_t *trap_opcode = NULL;
533     size_t trap_opcode_size = 0;
534 
535     switch (arch.GetMachine())
536     {
537     default:
538         assert(false && "CPU type not supported!");
539         break;
540 
541     case llvm::Triple::aarch64:
542         {
543             static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
544             trap_opcode = g_aarch64_opcode;
545             trap_opcode_size = sizeof(g_aarch64_opcode);
546         }
547         break;
548     case llvm::Triple::x86:
549     case llvm::Triple::x86_64:
550         {
551             static const uint8_t g_i386_breakpoint_opcode[] = { 0xCC };
552             trap_opcode = g_i386_breakpoint_opcode;
553             trap_opcode_size = sizeof(g_i386_breakpoint_opcode);
554         }
555         break;
556     case llvm::Triple::hexagon:
557         {
558             static const uint8_t g_hex_opcode[] = { 0x0c, 0xdb, 0x00, 0x54 };
559             trap_opcode = g_hex_opcode;
560             trap_opcode_size = sizeof(g_hex_opcode);
561         }
562         break;
563     case llvm::Triple::arm:
564         {
565             // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
566             // but the linux kernel does otherwise.
567             static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
568             static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
569 
570             lldb::BreakpointLocationSP bp_loc_sp (bp_site->GetOwnerAtIndex (0));
571             AddressClass addr_class = eAddressClassUnknown;
572 
573             if (bp_loc_sp)
574                 addr_class = bp_loc_sp->GetAddress ().GetAddressClass ();
575 
576             if (addr_class == eAddressClassCodeAlternateISA
577                 || (addr_class == eAddressClassUnknown
578                     && bp_loc_sp->GetAddress().GetOffset() & 1))
579             {
580                 trap_opcode = g_thumb_breakpoint_opcode;
581                 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
582             }
583             else
584             {
585                 trap_opcode = g_arm_breakpoint_opcode;
586                 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
587             }
588         }
589         break;
590     case llvm::Triple::mips64:
591         {
592             static const uint8_t g_hex_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
593             trap_opcode = g_hex_opcode;
594             trap_opcode_size = sizeof(g_hex_opcode);
595         }
596         break;
597     }
598 
599     if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
600         return trap_opcode_size;
601     return 0;
602 }
603 
604 int32_t
605 PlatformLinux::GetResumeCountForLaunchInfo (ProcessLaunchInfo &launch_info)
606 {
607     int32_t resume_count = 0;
608 
609     // Always resume past the initial stop when we use eLaunchFlagDebug
610     if (launch_info.GetFlags ().Test (eLaunchFlagDebug))
611     {
612         // Resume past the stop for the final exec into the true inferior.
613         ++resume_count;
614     }
615 
616     // If we're not launching a shell, we're done.
617     const FileSpec &shell = launch_info.GetShell();
618     if (!shell)
619         return resume_count;
620 
621     std::string shell_string = shell.GetPath();
622     // We're in a shell, so for sure we have to resume past the shell exec.
623     ++resume_count;
624 
625     // Figure out what shell we're planning on using.
626     const char *shell_name = strrchr (shell_string.c_str(), '/');
627     if (shell_name == NULL)
628         shell_name = shell_string.c_str();
629     else
630         shell_name++;
631 
632     if (strcmp (shell_name, "csh") == 0
633              || strcmp (shell_name, "tcsh") == 0
634              || strcmp (shell_name, "zsh") == 0
635              || strcmp (shell_name, "sh") == 0)
636     {
637         // These shells seem to re-exec themselves.  Add another resume.
638         ++resume_count;
639     }
640 
641     return resume_count;
642 }
643 
644 bool
645 PlatformLinux::UseLlgsForLocalDebugging ()
646 {
647     PlatformLinuxPropertiesSP properties_sp = GetGlobalProperties ();
648     assert (properties_sp && "global properties shared pointer is null");
649     return properties_sp ? properties_sp->GetUseLlgsForLocal () : false;
650 }
651 
652 bool
653 PlatformLinux::CanDebugProcess ()
654 {
655     if (IsHost ())
656     {
657         // The platform only does local debugging (i.e. uses llgs) when the setting indicates we do that.
658         // Otherwise, we'll use ProcessLinux/ProcessPOSIX to handle with ProcessMonitor.
659         return UseLlgsForLocalDebugging ();
660     }
661     else
662     {
663         // If we're connected, we can debug.
664         return IsConnected ();
665     }
666 }
667 
668 // For local debugging, Linux will override the debug logic to use llgs-launch rather than
669 // lldb-launch, llgs-attach.  This differs from current lldb-launch, debugserver-attach
670 // approach on MacOSX.
671 lldb::ProcessSP
672 PlatformLinux::DebugProcess (ProcessLaunchInfo &launch_info,
673                              Debugger &debugger,
674                              Target *target,       // Can be NULL, if NULL create a new target, else use existing one
675                              Error &error)
676 {
677     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
678     if (log)
679         log->Printf ("PlatformLinux::%s entered (target %p)", __FUNCTION__, static_cast<void*>(target));
680 
681     // If we're a remote host, use standard behavior from parent class.
682     if (!IsHost ())
683         return PlatformPOSIX::DebugProcess (launch_info, debugger, target, error);
684 
685     //
686     // For local debugging, we'll insist on having ProcessGDBRemote create the process.
687     //
688 
689     ProcessSP process_sp;
690 
691     // Ensure we're using llgs for local debugging.
692     if (!UseLlgsForLocalDebugging ())
693     {
694         assert (false && "we're trying to debug a local process but platform.plugin.linux.use-llgs-for-local is false, should never get here");
695         error.SetErrorString ("attempted to start gdb-remote-based debugging for local process but platform.plugin.linux.use-llgs-for-local is false");
696         return process_sp;
697     }
698 
699     // Make sure we stop at the entry point
700     launch_info.GetFlags ().Set (eLaunchFlagDebug);
701 
702     // We always launch the process we are going to debug in a separate process
703     // group, since then we can handle ^C interrupts ourselves w/o having to worry
704     // about the target getting them as well.
705     launch_info.SetLaunchInSeparateProcessGroup(true);
706 
707     // Ensure we have a target.
708     if (target == nullptr)
709     {
710         if (log)
711             log->Printf ("PlatformLinux::%s creating new target", __FUNCTION__);
712 
713         TargetSP new_target_sp;
714         error = debugger.GetTargetList().CreateTarget (debugger,
715                                                        nullptr,
716                                                        nullptr,
717                                                        false,
718                                                        nullptr,
719                                                        new_target_sp);
720         if (error.Fail ())
721         {
722             if (log)
723                 log->Printf ("PlatformLinux::%s failed to create new target: %s", __FUNCTION__, error.AsCString ());
724             return process_sp;
725         }
726 
727         target = new_target_sp.get();
728         if (!target)
729         {
730             error.SetErrorString ("CreateTarget() returned nullptr");
731             if (log)
732                 log->Printf ("PlatformLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
733             return process_sp;
734         }
735     }
736     else
737     {
738         if (log)
739             log->Printf ("PlatformLinux::%s using provided target", __FUNCTION__);
740     }
741 
742     // Mark target as currently selected target.
743     debugger.GetTargetList().SetSelectedTarget(target);
744 
745     // Now create the gdb-remote process.
746     if (log)
747         log->Printf ("PlatformLinux::%s having target create process with gdb-remote plugin", __FUNCTION__);
748     process_sp = target->CreateProcess (launch_info.GetListenerForProcess(debugger), "gdb-remote", nullptr);
749 
750     if (!process_sp)
751     {
752         error.SetErrorString ("CreateProcess() failed for gdb-remote process");
753         if (log)
754             log->Printf ("PlatformLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
755         return process_sp;
756     }
757     else
758     {
759         if (log)
760             log->Printf ("PlatformLinux::%s successfully created process", __FUNCTION__);
761     }
762 
763     // Set the unix signals properly.
764     process_sp->SetUnixSignals (Host::GetUnixSignals ());
765 
766     // Adjust launch for a hijacker.
767     ListenerSP listener_sp;
768 #if 0
769     if (!launch_info.GetHijackListener ())
770     {
771         if (log)
772             log->Printf ("PlatformLinux::%s setting up hijacker", __FUNCTION__);
773 
774         listener_sp.reset (new Listener("lldb.PlatformLinux.DebugProcess.hijack"));
775         launch_info.SetHijackListener (listener_sp);
776         process_sp->HijackProcessEvents (listener_sp.get ());
777     }
778 #endif
779 
780     // Log file actions.
781     if (log)
782     {
783         log->Printf ("PlatformLinux::%s launching process with the following file actions:", __FUNCTION__);
784 
785         StreamString stream;
786         size_t i = 0;
787         const FileAction *file_action;
788         while ((file_action = launch_info.GetFileActionAtIndex (i++)) != nullptr)
789         {
790             file_action->Dump (stream);
791             log->PutCString (stream.GetString().c_str ());
792             stream.Clear();
793         }
794     }
795 
796     // Do the launch.
797     error = process_sp->Launch(launch_info);
798     if (error.Success ())
799     {
800         // Handle the hijacking of process events.
801         if (listener_sp)
802         {
803             const StateType state = process_sp->WaitForProcessToStop (NULL, NULL, false, listener_sp.get());
804             process_sp->RestoreProcessEvents();
805 
806             if (state == eStateStopped)
807             {
808                 if (log)
809                     log->Printf ("PlatformLinux::%s pid %" PRIu64 " state %s\n",
810                                  __FUNCTION__, process_sp->GetID (), StateAsCString (state));
811             }
812             else
813             {
814                 if (log)
815                     log->Printf ("PlatformLinux::%s pid %" PRIu64 " state is not stopped - %s\n",
816                                  __FUNCTION__, process_sp->GetID (), StateAsCString (state));
817             }
818         }
819 
820         // Hook up process PTY if we have one (which we should for local debugging with llgs).
821         int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
822         if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd)
823         {
824             process_sp->SetSTDIOFileDescriptor(pty_fd);
825             if (log)
826                 log->Printf ("PlatformLinux::%s pid %" PRIu64 " hooked up STDIO pty to process", __FUNCTION__, process_sp->GetID ());
827         }
828         else
829         {
830             if (log)
831                 log->Printf ("PlatformLinux::%s pid %" PRIu64 " not using process STDIO pty", __FUNCTION__, process_sp->GetID ());
832         }
833     }
834     else
835     {
836         if (log)
837             log->Printf ("PlatformLinux::%s process launch failed: %s", __FUNCTION__, error.AsCString ());
838         // FIXME figure out appropriate cleanup here.  Do we delete the target? Do we delete the process?  Does our caller do that?
839     }
840 
841     return process_sp;
842 }
843 
844 void
845 PlatformLinux::CalculateTrapHandlerSymbolNames ()
846 {
847     m_trap_handlers.push_back (ConstString ("_sigtramp"));
848 }
849 
850 Error
851 PlatformLinux::LaunchNativeProcess (
852     ProcessLaunchInfo &launch_info,
853     lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
854     NativeProcessProtocolSP &process_sp)
855 {
856 #if !defined(__linux__)
857     return Error("Only implemented on Linux hosts");
858 #else
859     if (!IsHost ())
860         return Error("PlatformLinux::%s (): cannot launch a debug process when not the host", __FUNCTION__);
861 
862     // Retrieve the exe module.
863     lldb::ModuleSP exe_module_sp;
864     ModuleSpec exe_module_spec(launch_info.GetExecutableFile(), launch_info.GetArchitecture());
865 
866     Error error = ResolveExecutable (
867         exe_module_spec,
868         exe_module_sp,
869         NULL);
870 
871     if (!error.Success ())
872         return error;
873 
874     if (!exe_module_sp)
875         return Error("exe_module_sp could not be resolved for %s", launch_info.GetExecutableFile ().GetPath ().c_str ());
876 
877     // Launch it for debugging
878     error = NativeProcessLinux::LaunchProcess (
879         exe_module_sp.get (),
880         launch_info,
881         native_delegate,
882         process_sp);
883 
884     return error;
885 #endif
886 }
887 
888 Error
889 PlatformLinux::AttachNativeProcess (lldb::pid_t pid,
890                                     lldb_private::NativeProcessProtocol::NativeDelegate &native_delegate,
891                                     NativeProcessProtocolSP &process_sp)
892 {
893 #if !defined(__linux__)
894     return Error("Only implemented on Linux hosts");
895 #else
896     if (!IsHost ())
897         return Error("PlatformLinux::%s (): cannot attach to a debug process when not the host", __FUNCTION__);
898 
899     // Launch it for debugging
900     return NativeProcessLinux::AttachToProcess (pid, native_delegate, process_sp);
901 #endif
902 }
903