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