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