1 //===-- PlatformFreeBSD.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PlatformFreeBSD.h"
10 #include "lldb/Host/Config.h"
11 
12 #include <stdio.h>
13 #if LLDB_ENABLE_POSIX
14 #include <sys/utsname.h>
15 #endif
16 
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 #include "lldb/Breakpoint/BreakpointSite.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Host/HostInfo.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Utility/FileSpec.h"
25 #include "lldb/Utility/Log.h"
26 #include "lldb/Utility/State.h"
27 #include "lldb/Utility/Status.h"
28 #include "lldb/Utility/StreamString.h"
29 
30 // Define these constants from FreeBSD mman.h for use when targeting remote
31 // FreeBSD systems even when host has different values.
32 #define MAP_PRIVATE 0x0002
33 #define MAP_ANON 0x1000
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 using namespace lldb_private::platform_freebsd;
38 
39 LLDB_PLUGIN_DEFINE(PlatformFreeBSD)
40 
41 static uint32_t g_initialize_count = 0;
42 
43 
44 PlatformSP PlatformFreeBSD::CreateInstance(bool force, const ArchSpec *arch) {
45   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
46   LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force,
47            arch ? arch->GetArchitectureName() : "<null>",
48            arch ? arch->GetTriple().getTriple() : "<null>");
49 
50   bool create = force;
51   if (!create && arch && arch->IsValid()) {
52     const llvm::Triple &triple = arch->GetTriple();
53     switch (triple.getOS()) {
54     case llvm::Triple::FreeBSD:
55       create = true;
56       break;
57 
58 #if defined(__FreeBSD__)
59     // Only accept "unknown" for the OS if the host is BSD and it "unknown"
60     // wasn't specified (it was just returned because it was NOT specified)
61     case llvm::Triple::OSType::UnknownOS:
62       create = !arch->TripleOSWasSpecified();
63       break;
64 #endif
65     default:
66       break;
67     }
68   }
69   LLDB_LOG(log, "create = {0}", create);
70   if (create) {
71     return PlatformSP(new PlatformFreeBSD(false));
72   }
73   return PlatformSP();
74 }
75 
76 ConstString PlatformFreeBSD::GetPluginNameStatic(bool is_host) {
77   if (is_host) {
78     static ConstString g_host_name(Platform::GetHostPlatformName());
79     return g_host_name;
80   } else {
81     static ConstString g_remote_name("remote-freebsd");
82     return g_remote_name;
83   }
84 }
85 
86 const char *PlatformFreeBSD::GetPluginDescriptionStatic(bool is_host) {
87   if (is_host)
88     return "Local FreeBSD user platform plug-in.";
89   else
90     return "Remote FreeBSD user platform plug-in.";
91 }
92 
93 ConstString PlatformFreeBSD::GetPluginName() {
94   return GetPluginNameStatic(IsHost());
95 }
96 
97 void PlatformFreeBSD::Initialize() {
98   Platform::Initialize();
99 
100   if (g_initialize_count++ == 0) {
101 #if defined(__FreeBSD__)
102     PlatformSP default_platform_sp(new PlatformFreeBSD(true));
103     default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
104     Platform::SetHostPlatform(default_platform_sp);
105 #endif
106     PluginManager::RegisterPlugin(
107         PlatformFreeBSD::GetPluginNameStatic(false),
108         PlatformFreeBSD::GetPluginDescriptionStatic(false),
109         PlatformFreeBSD::CreateInstance, nullptr);
110   }
111 }
112 
113 void PlatformFreeBSD::Terminate() {
114   if (g_initialize_count > 0) {
115     if (--g_initialize_count == 0) {
116       PluginManager::UnregisterPlugin(PlatformFreeBSD::CreateInstance);
117     }
118   }
119 
120   PlatformPOSIX::Terminate();
121 }
122 
123 /// Default Constructor
124 PlatformFreeBSD::PlatformFreeBSD(bool is_host)
125     : PlatformPOSIX(is_host) // This is the local host platform
126 {}
127 
128 PlatformFreeBSD::~PlatformFreeBSD() = default;
129 
130 bool PlatformFreeBSD::GetSupportedArchitectureAtIndex(uint32_t idx,
131                                                       ArchSpec &arch) {
132   if (IsHost()) {
133     ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
134     if (hostArch.GetTriple().isOSFreeBSD()) {
135       if (idx == 0) {
136         arch = hostArch;
137         return arch.IsValid();
138       } else if (idx == 1) {
139         // If the default host architecture is 64-bit, look for a 32-bit
140         // variant
141         if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit()) {
142           arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
143           return arch.IsValid();
144         }
145       }
146     }
147   } else {
148     if (m_remote_platform_sp)
149       return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch);
150 
151     llvm::Triple triple;
152     // Set the OS to FreeBSD
153     triple.setOS(llvm::Triple::FreeBSD);
154     // Set the architecture
155     switch (idx) {
156     case 0:
157       triple.setArchName("x86_64");
158       break;
159     case 1:
160       triple.setArchName("i386");
161       break;
162     case 2:
163       triple.setArchName("aarch64");
164       break;
165     case 3:
166       triple.setArchName("arm");
167       break;
168     case 4:
169       triple.setArchName("mips64");
170       break;
171     case 5:
172       triple.setArchName("mips");
173       break;
174     case 6:
175       triple.setArchName("ppc64");
176       break;
177     case 7:
178       triple.setArchName("ppc");
179       break;
180     default:
181       return false;
182     }
183     // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the
184     // vendor by calling triple.SetVendorName("unknown") so that it is a
185     // "unspecified unknown". This means when someone calls
186     // triple.GetVendorName() it will return an empty string which indicates
187     // that the vendor can be set when two architectures are merged
188 
189     // Now set the triple into "arch" and return true
190     arch.SetTriple(triple);
191     return true;
192   }
193   return false;
194 }
195 
196 void PlatformFreeBSD::GetStatus(Stream &strm) {
197   Platform::GetStatus(strm);
198 
199 #if LLDB_ENABLE_POSIX
200   // Display local kernel information only when we are running in host mode.
201   // Otherwise, we would end up printing non-FreeBSD information (when running
202   // on Mac OS for example).
203   if (IsHost()) {
204     struct utsname un;
205 
206     if (uname(&un))
207       return;
208 
209     strm.Printf("    Kernel: %s\n", un.sysname);
210     strm.Printf("   Release: %s\n", un.release);
211     strm.Printf("   Version: %s\n", un.version);
212   }
213 #endif
214 }
215 
216 size_t
217 PlatformFreeBSD::GetSoftwareBreakpointTrapOpcode(Target &target,
218                                                  BreakpointSite *bp_site) {
219   switch (target.GetArchitecture().GetMachine()) {
220   case llvm::Triple::arm: {
221     lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
222     AddressClass addr_class = AddressClass::eUnknown;
223 
224     if (bp_loc_sp) {
225       addr_class = bp_loc_sp->GetAddress().GetAddressClass();
226       if (addr_class == AddressClass::eUnknown &&
227           (bp_loc_sp->GetAddress().GetFileAddress() & 1))
228         addr_class = AddressClass::eCodeAlternateISA;
229     }
230 
231     if (addr_class == AddressClass::eCodeAlternateISA) {
232       // TODO: Enable when FreeBSD supports thumb breakpoints.
233       // FreeBSD kernel as of 10.x, does not support thumb breakpoints
234       return 0;
235     }
236 
237     static const uint8_t g_arm_breakpoint_opcode[] = {0xFE, 0xDE, 0xFF, 0xE7};
238     size_t trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
239     assert(bp_site);
240     if (bp_site->SetTrapOpcode(g_arm_breakpoint_opcode, trap_opcode_size))
241       return trap_opcode_size;
242   }
243     LLVM_FALLTHROUGH;
244   default:
245     return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
246   }
247 }
248 
249 Status PlatformFreeBSD::LaunchProcess(ProcessLaunchInfo &launch_info) {
250   Status error;
251   if (IsHost()) {
252     error = Platform::LaunchProcess(launch_info);
253   } else {
254     if (m_remote_platform_sp)
255       error = m_remote_platform_sp->LaunchProcess(launch_info);
256     else
257       error.SetErrorString("the platform is not currently connected");
258   }
259   return error;
260 }
261 
262 lldb::ProcessSP PlatformFreeBSD::Attach(ProcessAttachInfo &attach_info,
263                                         Debugger &debugger, Target *target,
264                                         Status &error) {
265   lldb::ProcessSP process_sp;
266   if (IsHost()) {
267     if (target == nullptr) {
268       TargetSP new_target_sp;
269       ArchSpec emptyArchSpec;
270 
271       error = debugger.GetTargetList().CreateTarget(
272           debugger, "", emptyArchSpec, eLoadDependentsNo, m_remote_platform_sp,
273           new_target_sp);
274       target = new_target_sp.get();
275     } else
276       error.Clear();
277 
278     if (target && error.Success()) {
279       debugger.GetTargetList().SetSelectedTarget(target);
280       // The freebsd always currently uses the GDB remote debugger plug-in so
281       // even when debugging locally we are debugging remotely! Just like the
282       // darwin plugin.
283       process_sp = target->CreateProcess(
284           attach_info.GetListenerForProcess(debugger), "gdb-remote", nullptr);
285 
286       if (process_sp)
287         error = process_sp->Attach(attach_info);
288     }
289   } else {
290     if (m_remote_platform_sp)
291       process_sp =
292           m_remote_platform_sp->Attach(attach_info, debugger, target, error);
293     else
294       error.SetErrorString("the platform is not currently connected");
295   }
296   return process_sp;
297 }
298 
299 // FreeBSD processes cannot yet be launched by spawning and attaching.
300 bool PlatformFreeBSD::CanDebugProcess() {
301   return false;
302 }
303 
304 void PlatformFreeBSD::CalculateTrapHandlerSymbolNames() {
305   m_trap_handlers.push_back(ConstString("_sigtramp"));
306 }
307 
308 MmapArgList PlatformFreeBSD::GetMmapArgumentList(const ArchSpec &arch,
309                                                  addr_t addr, addr_t length,
310                                                  unsigned prot, unsigned flags,
311                                                  addr_t fd, addr_t offset) {
312   uint64_t flags_platform = 0;
313 
314   if (flags & eMmapFlagsPrivate)
315     flags_platform |= MAP_PRIVATE;
316   if (flags & eMmapFlagsAnon)
317     flags_platform |= MAP_ANON;
318 
319   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
320   if (arch.GetTriple().getArch() == llvm::Triple::x86)
321     args.push_back(0);
322   return args;
323 }
324