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