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