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