1 //===-- HostInfoLinux.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 "lldb/Host/linux/HostInfoLinux.h"
10 #include "lldb/Host/Config.h"
11 #include "lldb/Host/FileSystem.h"
12 #include "lldb/Utility/Log.h"
13 
14 #include "llvm/Support/Threading.h"
15 
16 #include <climits>
17 #include <cstdio>
18 #include <cstring>
19 #include <sys/utsname.h>
20 #include <unistd.h>
21 
22 #include <algorithm>
23 #include <mutex>
24 
25 using namespace lldb_private;
26 
27 namespace {
28 struct HostInfoLinuxFields {
29   llvm::once_flag m_distribution_once_flag;
30   std::string m_distribution_id;
31   llvm::once_flag m_os_version_once_flag;
32   llvm::VersionTuple m_os_version;
33 };
34 
35 HostInfoLinuxFields *g_fields = nullptr;
36 }
37 
38 void HostInfoLinux::Initialize(SharedLibraryDirectoryHelper *helper) {
39   HostInfoPosix::Initialize(helper);
40 
41   g_fields = new HostInfoLinuxFields();
42 }
43 
44 void HostInfoLinux::Terminate() {
45   assert(g_fields && "Missing call to Initialize?");
46   delete g_fields;
47   g_fields = nullptr;
48   HostInfoBase::Terminate();
49 }
50 
51 llvm::VersionTuple HostInfoLinux::GetOSVersion() {
52   assert(g_fields && "Missing call to Initialize?");
53   llvm::call_once(g_fields->m_os_version_once_flag, []() {
54     struct utsname un;
55     if (uname(&un) != 0)
56       return;
57 
58     llvm::StringRef release = un.release;
59     // The kernel release string can include a lot of stuff (e.g.
60     // 4.9.0-6-amd64). We're only interested in the numbered prefix.
61     release = release.substr(0, release.find_first_not_of("0123456789."));
62     g_fields->m_os_version.tryParse(release);
63   });
64 
65   return g_fields->m_os_version;
66 }
67 
68 bool HostInfoLinux::GetOSBuildString(std::string &s) {
69   struct utsname un;
70   ::memset(&un, 0, sizeof(utsname));
71   s.clear();
72 
73   if (uname(&un) < 0)
74     return false;
75 
76   s.assign(un.release);
77   return true;
78 }
79 
80 bool HostInfoLinux::GetOSKernelDescription(std::string &s) {
81   struct utsname un;
82 
83   ::memset(&un, 0, sizeof(utsname));
84   s.clear();
85 
86   if (uname(&un) < 0)
87     return false;
88 
89   s.assign(un.version);
90   return true;
91 }
92 
93 llvm::StringRef HostInfoLinux::GetDistributionId() {
94   assert(g_fields && "Missing call to Initialize?");
95   // Try to run 'lbs_release -i', and use that response for the distribution
96   // id.
97   llvm::call_once(g_fields->m_distribution_once_flag, []() {
98 
99     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST));
100     LLDB_LOGF(log, "attempting to determine Linux distribution...");
101 
102     // check if the lsb_release command exists at one of the following paths
103     const char *const exe_paths[] = {"/bin/lsb_release",
104                                      "/usr/bin/lsb_release"};
105 
106     for (size_t exe_index = 0;
107          exe_index < sizeof(exe_paths) / sizeof(exe_paths[0]); ++exe_index) {
108       const char *const get_distribution_info_exe = exe_paths[exe_index];
109       if (access(get_distribution_info_exe, F_OK)) {
110         // this exe doesn't exist, move on to next exe
111         LLDB_LOGF(log, "executable doesn't exist: %s",
112                   get_distribution_info_exe);
113         continue;
114       }
115 
116       // execute the distribution-retrieval command, read output
117       std::string get_distribution_id_command(get_distribution_info_exe);
118       get_distribution_id_command += " -i";
119 
120       FILE *file = popen(get_distribution_id_command.c_str(), "r");
121       if (!file) {
122         LLDB_LOGF(log,
123                   "failed to run command: \"%s\", cannot retrieve "
124                   "platform information",
125                   get_distribution_id_command.c_str());
126         break;
127       }
128 
129       // retrieve the distribution id string.
130       char distribution_id[256] = {'\0'};
131       if (fgets(distribution_id, sizeof(distribution_id) - 1, file) !=
132           nullptr) {
133         LLDB_LOGF(log, "distribution id command returned \"%s\"",
134                   distribution_id);
135 
136         const char *const distributor_id_key = "Distributor ID:\t";
137         if (strstr(distribution_id, distributor_id_key)) {
138           // strip newlines
139           std::string id_string(distribution_id + strlen(distributor_id_key));
140           id_string.erase(std::remove(id_string.begin(), id_string.end(), '\n'),
141                           id_string.end());
142 
143           // lower case it and convert whitespace to underscores
144           std::transform(
145               id_string.begin(), id_string.end(), id_string.begin(),
146               [](char ch) { return tolower(isspace(ch) ? '_' : ch); });
147 
148           g_fields->m_distribution_id = id_string;
149           LLDB_LOGF(log, "distribution id set to \"%s\"",
150                     g_fields->m_distribution_id.c_str());
151         } else {
152           LLDB_LOGF(log, "failed to find \"%s\" field in \"%s\"",
153                     distributor_id_key, distribution_id);
154         }
155       } else {
156         LLDB_LOGF(log,
157                   "failed to retrieve distribution id, \"%s\" returned no"
158                   " lines",
159                   get_distribution_id_command.c_str());
160       }
161 
162       // clean up the file
163       pclose(file);
164     }
165   });
166 
167   return g_fields->m_distribution_id;
168 }
169 
170 FileSpec HostInfoLinux::GetProgramFileSpec() {
171   static FileSpec g_program_filespec;
172 
173   if (!g_program_filespec) {
174     char exe_path[PATH_MAX];
175     ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
176     if (len > 0) {
177       exe_path[len] = 0;
178       g_program_filespec.SetFile(exe_path, FileSpec::Style::native);
179     }
180   }
181 
182   return g_program_filespec;
183 }
184 
185 bool HostInfoLinux::ComputeSupportExeDirectory(FileSpec &file_spec) {
186   if (HostInfoPosix::ComputeSupportExeDirectory(file_spec) &&
187       file_spec.IsAbsolute() && FileSystem::Instance().Exists(file_spec))
188     return true;
189   file_spec.GetDirectory() = GetProgramFileSpec().GetDirectory();
190   return !file_spec.GetDirectory().IsEmpty();
191 }
192 
193 bool HostInfoLinux::ComputeSystemPluginsDirectory(FileSpec &file_spec) {
194   FileSpec temp_file("/usr/lib" LLDB_LIBDIR_SUFFIX "/lldb/plugins");
195   FileSystem::Instance().Resolve(temp_file);
196   file_spec.GetDirectory().SetCString(temp_file.GetPath().c_str());
197   return true;
198 }
199 
200 bool HostInfoLinux::ComputeUserPluginsDirectory(FileSpec &file_spec) {
201   // XDG Base Directory Specification
202   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html If
203   // XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
204   const char *xdg_data_home = getenv("XDG_DATA_HOME");
205   if (xdg_data_home && xdg_data_home[0]) {
206     std::string user_plugin_dir(xdg_data_home);
207     user_plugin_dir += "/lldb";
208     file_spec.GetDirectory().SetCString(user_plugin_dir.c_str());
209   } else
210     file_spec.GetDirectory().SetCString("~/.local/share/lldb");
211   return true;
212 }
213 
214 void HostInfoLinux::ComputeHostArchitectureSupport(ArchSpec &arch_32,
215                                                    ArchSpec &arch_64) {
216   HostInfoPosix::ComputeHostArchitectureSupport(arch_32, arch_64);
217 
218   const char *distribution_id = GetDistributionId().data();
219 
220   // On Linux, "unknown" in the vendor slot isn't what we want for the default
221   // triple.  It's probably an artifact of config.guess.
222   if (arch_32.IsValid()) {
223     arch_32.SetDistributionId(distribution_id);
224     if (arch_32.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
225       arch_32.GetTriple().setVendorName(llvm::StringRef());
226   }
227   if (arch_64.IsValid()) {
228     arch_64.SetDistributionId(distribution_id);
229     if (arch_64.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
230       arch_64.GetTriple().setVendorName(llvm::StringRef());
231   }
232 }
233