1 //===-- CppModuleConfiguration.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 "CppModuleConfiguration.h"
10 
11 #include "ClangHost.h"
12 #include "lldb/Host/FileSystem.h"
13 #include "llvm/TargetParser/Triple.h"
14 #include <optional>
15 
16 using namespace lldb_private;
17 
18 bool CppModuleConfiguration::SetOncePath::TrySet(llvm::StringRef path) {
19   // Setting for the first time always works.
20   if (m_first) {
21     m_path = path.str();
22     m_valid = true;
23     m_first = false;
24     return true;
25   }
26   // Changing the path to the same value is fine.
27   if (m_path == path)
28     return true;
29 
30   // Changing the path after it was already set is not allowed.
31   m_valid = false;
32   return false;
33 }
34 
35 static llvm::SmallVector<std::string, 2>
36 getTargetIncludePaths(const llvm::Triple &triple) {
37   llvm::SmallVector<std::string, 2> paths;
38   if (!triple.str().empty()) {
39     paths.push_back("/usr/include/" + triple.str());
40     if (!triple.getArchName().empty() ||
41         triple.getOSAndEnvironmentName().empty())
42       paths.push_back(("/usr/include/" + triple.getArchName() + "-" +
43                        triple.getOSAndEnvironmentName())
44                           .str());
45   }
46   return paths;
47 }
48 
49 /// Returns the include path matching the given pattern for the given file
50 /// path (or std::nullopt if the path doesn't match the pattern).
51 static std::optional<llvm::StringRef>
52 guessIncludePath(llvm::StringRef path_to_file, llvm::StringRef pattern) {
53   if (pattern.empty())
54     return std::nullopt;
55   size_t pos = path_to_file.find(pattern);
56   if (pos == llvm::StringRef::npos)
57     return std::nullopt;
58 
59   return path_to_file.substr(0, pos + pattern.size());
60 }
61 
62 bool CppModuleConfiguration::analyzeFile(const FileSpec &f,
63                                          const llvm::Triple &triple) {
64   using namespace llvm::sys::path;
65   // Convert to slashes to make following operations simpler.
66   std::string dir_buffer = convert_to_slash(f.GetDirectory().GetStringRef());
67   llvm::StringRef posix_dir(dir_buffer);
68 
69   // Check for /c++/vX/ that is used by libc++.
70   static llvm::Regex libcpp_regex(R"regex(/c[+][+]/v[0-9]/)regex");
71   // If the path is in the libc++ include directory use it as the found libc++
72   // path. Ignore subdirectories such as /c++/v1/experimental as those don't
73   // need to be specified in the header search.
74   if (libcpp_regex.match(f.GetPath()) &&
75       parent_path(posix_dir, Style::posix).endswith("c++")) {
76     if (!m_std_inc.TrySet(posix_dir))
77       return false;
78     if (triple.str().empty())
79       return true;
80 
81     posix_dir.consume_back("c++/v1");
82     // Check if this is a target-specific libc++ include directory.
83     return m_std_target_inc.TrySet(
84         (posix_dir + triple.str() + "/c++/v1").str());
85   }
86 
87   std::optional<llvm::StringRef> inc_path;
88   // Target specific paths contains /usr/include, so we check them first
89   for (auto &path : getTargetIncludePaths(triple)) {
90     if ((inc_path = guessIncludePath(posix_dir, path)))
91       return m_c_target_inc.TrySet(*inc_path);
92   }
93   if ((inc_path = guessIncludePath(posix_dir, "/usr/include")))
94     return m_c_inc.TrySet(*inc_path);
95 
96   // File wasn't interesting, continue analyzing.
97   return true;
98 }
99 
100 /// Utility function for just appending two paths.
101 static std::string MakePath(llvm::StringRef lhs, llvm::StringRef rhs) {
102   llvm::SmallString<256> result(lhs);
103   llvm::sys::path::append(result, rhs);
104   return std::string(result);
105 }
106 
107 bool CppModuleConfiguration::hasValidConfig() {
108   // We need to have a C and C++ include dir for a valid configuration.
109   if (!m_c_inc.Valid() || !m_std_inc.Valid())
110     return false;
111 
112   // Do some basic sanity checks on the directories that we don't activate
113   // the module when it's clear that it's not usable.
114   const std::vector<std::string> files_to_check = {
115       // * Check that the C library contains at least one random C standard
116       //   library header.
117       MakePath(m_c_inc.Get(), "stdio.h"),
118       // * Without a libc++ modulemap file we can't have a 'std' module that
119       //   could be imported.
120       MakePath(m_std_inc.Get(), "module.modulemap"),
121       // * Check for a random libc++ header (vector in this case) that has to
122       //   exist in a working libc++ setup.
123       MakePath(m_std_inc.Get(), "vector"),
124   };
125 
126   for (llvm::StringRef file_to_check : files_to_check) {
127     if (!FileSystem::Instance().Exists(file_to_check))
128       return false;
129   }
130 
131   return true;
132 }
133 
134 CppModuleConfiguration::CppModuleConfiguration(
135     const FileSpecList &support_files, const llvm::Triple &triple) {
136   // Analyze all files we were given to build the configuration.
137   bool error = !llvm::all_of(support_files,
138                              std::bind(&CppModuleConfiguration::analyzeFile,
139                                        this, std::placeholders::_1, triple));
140   // If we have a valid configuration at this point, set the
141   // include directories and module list that should be used.
142   if (!error && hasValidConfig()) {
143     // Calculate the resource directory for LLDB.
144     llvm::SmallString<256> resource_dir;
145     llvm::sys::path::append(resource_dir, GetClangResourceDir().GetPath(),
146                             "include");
147     m_resource_inc = std::string(resource_dir.str());
148 
149     // This order matches the way Clang orders these directories.
150     m_include_dirs = {m_std_inc.Get().str(), m_resource_inc,
151                       m_c_inc.Get().str()};
152     if (m_c_target_inc.Valid())
153       m_include_dirs.push_back(m_c_target_inc.Get().str());
154     if (m_std_target_inc.Valid())
155       m_include_dirs.push_back(m_std_target_inc.Get().str());
156     m_imported_modules = {"std"};
157   }
158 }
159