1 //===-- PathMappingList.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 <climits>
10 #include <cstring>
11 #include <optional>
12 
13 #include "lldb/Host/FileSystem.h"
14 #include "lldb/Host/PosixApi.h"
15 #include "lldb/Target/PathMappingList.h"
16 #include "lldb/Utility/FileSpec.h"
17 #include "lldb/Utility/Status.h"
18 #include "lldb/Utility/Stream.h"
19 #include "lldb/lldb-private-enumerations.h"
20 
21 using namespace lldb;
22 using namespace lldb_private;
23 
24 namespace {
25   // We must normalize our path pairs that we store because if we don't then
26   // things won't always work. We found a case where if we did:
27   // (lldb) settings set target.source-map . /tmp
28   // We would store a path pairs of "." and "/tmp" as raw strings. If the debug
29   // info contains "./foo/bar.c", the path will get normalized to "foo/bar.c".
30   // When PathMappingList::RemapPath() is called, it expects the path to start
31   // with the raw path pair, which doesn't work anymore because the paths have
32   // been normalized when the debug info was loaded. So we need to store
33   // nomalized path pairs to ensure things match up.
34 std::string NormalizePath(llvm::StringRef path) {
35   // If we use "path" to construct a FileSpec, it will normalize the path for
36   // us. We then grab the string.
37   return FileSpec(path).GetPath();
38 }
39 }
40 // PathMappingList constructor
41 PathMappingList::PathMappingList() : m_pairs() {}
42 
43 PathMappingList::PathMappingList(ChangedCallback callback, void *callback_baton)
44     : m_pairs(), m_callback(callback), m_callback_baton(callback_baton) {}
45 
46 PathMappingList::PathMappingList(const PathMappingList &rhs)
47     : m_pairs(rhs.m_pairs) {}
48 
49 const PathMappingList &PathMappingList::operator=(const PathMappingList &rhs) {
50   if (this != &rhs) {
51     m_pairs = rhs.m_pairs;
52     m_callback = nullptr;
53     m_callback_baton = nullptr;
54     m_mod_id = rhs.m_mod_id;
55   }
56   return *this;
57 }
58 
59 PathMappingList::~PathMappingList() = default;
60 
61 void PathMappingList::Append(llvm::StringRef path, llvm::StringRef replacement,
62                              bool notify) {
63   ++m_mod_id;
64   m_pairs.emplace_back(pair(NormalizePath(path), NormalizePath(replacement)));
65   if (notify && m_callback)
66     m_callback(*this, m_callback_baton);
67 }
68 
69 void PathMappingList::Append(const PathMappingList &rhs, bool notify) {
70   ++m_mod_id;
71   if (!rhs.m_pairs.empty()) {
72     const_iterator pos, end = rhs.m_pairs.end();
73     for (pos = rhs.m_pairs.begin(); pos != end; ++pos)
74       m_pairs.push_back(*pos);
75     if (notify && m_callback)
76       m_callback(*this, m_callback_baton);
77   }
78 }
79 
80 bool PathMappingList::AppendUnique(llvm::StringRef path,
81                                    llvm::StringRef replacement, bool notify) {
82   auto normalized_path = NormalizePath(path);
83   auto normalized_replacement = NormalizePath(replacement);
84   for (const auto &pair : m_pairs) {
85     if (pair.first.GetStringRef().equals(normalized_path) &&
86         pair.second.GetStringRef().equals(normalized_replacement))
87       return false;
88   }
89   Append(path, replacement, notify);
90   return true;
91 }
92 
93 void PathMappingList::Insert(llvm::StringRef path, llvm::StringRef replacement,
94                              uint32_t index, bool notify) {
95   ++m_mod_id;
96   iterator insert_iter;
97   if (index >= m_pairs.size())
98     insert_iter = m_pairs.end();
99   else
100     insert_iter = m_pairs.begin() + index;
101   m_pairs.emplace(insert_iter, pair(NormalizePath(path),
102                                     NormalizePath(replacement)));
103   if (notify && m_callback)
104     m_callback(*this, m_callback_baton);
105 }
106 
107 bool PathMappingList::Replace(llvm::StringRef path, llvm::StringRef replacement,
108                               uint32_t index, bool notify) {
109   if (index >= m_pairs.size())
110     return false;
111   ++m_mod_id;
112   m_pairs[index] = pair(NormalizePath(path), NormalizePath(replacement));
113   if (notify && m_callback)
114     m_callback(*this, m_callback_baton);
115   return true;
116 }
117 
118 bool PathMappingList::Remove(size_t index, bool notify) {
119   if (index >= m_pairs.size())
120     return false;
121 
122   ++m_mod_id;
123   iterator iter = m_pairs.begin() + index;
124   m_pairs.erase(iter);
125   if (notify && m_callback)
126     m_callback(*this, m_callback_baton);
127   return true;
128 }
129 
130 // For clients which do not need the pair index dumped, pass a pair_index >= 0
131 // to only dump the indicated pair.
132 void PathMappingList::Dump(Stream *s, int pair_index) {
133   unsigned int numPairs = m_pairs.size();
134 
135   if (pair_index < 0) {
136     unsigned int index;
137     for (index = 0; index < numPairs; ++index)
138       s->Printf("[%d] \"%s\" -> \"%s\"\n", index,
139                 m_pairs[index].first.GetCString(),
140                 m_pairs[index].second.GetCString());
141   } else {
142     if (static_cast<unsigned int>(pair_index) < numPairs)
143       s->Printf("%s -> %s", m_pairs[pair_index].first.GetCString(),
144                 m_pairs[pair_index].second.GetCString());
145   }
146 }
147 
148 llvm::json::Value PathMappingList::ToJSON() {
149   llvm::json::Array entries;
150   for (const auto &pair : m_pairs) {
151     llvm::json::Array entry{pair.first.GetStringRef().str(),
152                             pair.second.GetStringRef().str()};
153     entries.emplace_back(std::move(entry));
154   }
155   return entries;
156 }
157 
158 void PathMappingList::Clear(bool notify) {
159   if (!m_pairs.empty())
160     ++m_mod_id;
161   m_pairs.clear();
162   if (notify && m_callback)
163     m_callback(*this, m_callback_baton);
164 }
165 
166 bool PathMappingList::RemapPath(ConstString path,
167                                 ConstString &new_path) const {
168   if (std::optional<FileSpec> remapped = RemapPath(path.GetStringRef())) {
169     new_path.SetString(remapped->GetPath());
170     return true;
171   }
172   return false;
173 }
174 
175 /// Append components to path, applying style.
176 static void AppendPathComponents(FileSpec &path, llvm::StringRef components,
177                                  llvm::sys::path::Style style) {
178   auto component = llvm::sys::path::begin(components, style);
179   auto e = llvm::sys::path::end(components);
180   while (component != e &&
181          llvm::sys::path::is_separator(*component->data(), style))
182     ++component;
183   for (; component != e; ++component)
184     path.AppendPathComponent(*component);
185 }
186 
187 std::optional<FileSpec> PathMappingList::RemapPath(llvm::StringRef mapping_path,
188                                                    bool only_if_exists) const {
189   if (m_pairs.empty() || mapping_path.empty())
190     return {};
191   LazyBool path_is_relative = eLazyBoolCalculate;
192 
193   for (const auto &it : m_pairs) {
194     llvm::StringRef prefix = it.first.GetStringRef();
195     // We create a copy of mapping_path because StringRef::consume_from
196     // effectively modifies the instance itself.
197     llvm::StringRef path = mapping_path;
198     if (!path.consume_front(prefix)) {
199       // Relative paths won't have a leading "./" in them unless "." is the
200       // only thing in the relative path so we need to work around "."
201       // carefully.
202       if (prefix != ".")
203         continue;
204       // We need to figure out if the "path" argument is relative. If it is,
205       // then we should remap, else skip this entry.
206       if (path_is_relative == eLazyBoolCalculate) {
207         path_is_relative =
208             FileSpec(path).IsRelative() ? eLazyBoolYes : eLazyBoolNo;
209       }
210       if (!path_is_relative)
211         continue;
212     }
213     FileSpec remapped(it.second.GetStringRef());
214     auto orig_style = FileSpec::GuessPathStyle(prefix).value_or(
215         llvm::sys::path::Style::native);
216     AppendPathComponents(remapped, path, orig_style);
217     if (!only_if_exists || FileSystem::Instance().Exists(remapped))
218       return remapped;
219   }
220   return {};
221 }
222 
223 std::optional<llvm::StringRef>
224 PathMappingList::ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const {
225   std::string path = file.GetPath();
226   llvm::StringRef path_ref(path);
227   for (const auto &it : m_pairs) {
228     llvm::StringRef removed_prefix = it.second.GetStringRef();
229     if (!path_ref.consume_front(it.second.GetStringRef()))
230       continue;
231     auto orig_file = it.first.GetStringRef();
232     auto orig_style = FileSpec::GuessPathStyle(orig_file).value_or(
233         llvm::sys::path::Style::native);
234     fixed.SetFile(orig_file, orig_style);
235     AppendPathComponents(fixed, path_ref, orig_style);
236     return removed_prefix;
237   }
238   return std::nullopt;
239 }
240 
241 std::optional<FileSpec>
242 PathMappingList::FindFile(const FileSpec &orig_spec) const {
243   // We must normalize the orig_spec again using the host's path style,
244   // otherwise there will be mismatch between the host and remote platform
245   // if they use different path styles.
246   if (auto remapped = RemapPath(NormalizePath(orig_spec.GetPath()),
247                                 /*only_if_exists=*/true))
248     return remapped;
249 
250   return {};
251 }
252 
253 bool PathMappingList::Replace(llvm::StringRef path, llvm::StringRef new_path,
254                               bool notify) {
255   uint32_t idx = FindIndexForPath(path);
256   if (idx < m_pairs.size()) {
257     ++m_mod_id;
258     m_pairs[idx].second = ConstString(new_path);
259     if (notify && m_callback)
260       m_callback(*this, m_callback_baton);
261     return true;
262   }
263   return false;
264 }
265 
266 bool PathMappingList::Remove(ConstString path, bool notify) {
267   iterator pos = FindIteratorForPath(path);
268   if (pos != m_pairs.end()) {
269     ++m_mod_id;
270     m_pairs.erase(pos);
271     if (notify && m_callback)
272       m_callback(*this, m_callback_baton);
273     return true;
274   }
275   return false;
276 }
277 
278 PathMappingList::const_iterator
279 PathMappingList::FindIteratorForPath(ConstString path) const {
280   const_iterator pos;
281   const_iterator begin = m_pairs.begin();
282   const_iterator end = m_pairs.end();
283 
284   for (pos = begin; pos != end; ++pos) {
285     if (pos->first == path)
286       break;
287   }
288   return pos;
289 }
290 
291 PathMappingList::iterator
292 PathMappingList::FindIteratorForPath(ConstString path) {
293   iterator pos;
294   iterator begin = m_pairs.begin();
295   iterator end = m_pairs.end();
296 
297   for (pos = begin; pos != end; ++pos) {
298     if (pos->first == path)
299       break;
300   }
301   return pos;
302 }
303 
304 bool PathMappingList::GetPathsAtIndex(uint32_t idx, ConstString &path,
305                                       ConstString &new_path) const {
306   if (idx < m_pairs.size()) {
307     path = m_pairs[idx].first;
308     new_path = m_pairs[idx].second;
309     return true;
310   }
311   return false;
312 }
313 
314 uint32_t PathMappingList::FindIndexForPath(llvm::StringRef orig_path) const {
315   const ConstString path = ConstString(NormalizePath(orig_path));
316   const_iterator pos;
317   const_iterator begin = m_pairs.begin();
318   const_iterator end = m_pairs.end();
319 
320   for (pos = begin; pos != end; ++pos) {
321     if (pos->first == path)
322       return std::distance(begin, pos);
323   }
324   return UINT32_MAX;
325 }
326