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