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(const 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(const ConstString &path,
66                              const 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(const ConstString &path,
85                              const 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(const ConstString &path,
100                               const 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(const 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     char orig_path[PATH_MAX];
206     const size_t orig_path_len =
207         orig_spec.GetPath(orig_path, sizeof(orig_path));
208     if (orig_path_len > 0) {
209       const_iterator pos, end = m_pairs.end();
210       for (pos = m_pairs.begin(); pos != end; ++pos) {
211         const size_t prefix_len = pos->first.GetLength();
212 
213         if (orig_path_len >= prefix_len) {
214           if (::strncmp(pos->first.GetCString(), orig_path, prefix_len) == 0) {
215             new_spec.SetFile(pos->second.GetCString(), FileSpec::Style::native);
216             new_spec.AppendPathComponent(orig_path + prefix_len);
217             if (FileSystem::Instance().Exists(new_spec))
218               return true;
219           }
220         }
221       }
222     }
223   }
224   new_spec.Clear();
225   return false;
226 }
227 
228 bool PathMappingList::Replace(const ConstString &path,
229                               const ConstString &new_path, bool notify) {
230   uint32_t idx = FindIndexForPath(path);
231   if (idx < m_pairs.size()) {
232     ++m_mod_id;
233     m_pairs[idx].second = new_path;
234     if (notify && m_callback)
235       m_callback(*this, m_callback_baton);
236     return true;
237   }
238   return false;
239 }
240 
241 bool PathMappingList::Remove(const ConstString &path, bool notify) {
242   iterator pos = FindIteratorForPath(path);
243   if (pos != m_pairs.end()) {
244     ++m_mod_id;
245     m_pairs.erase(pos);
246     if (notify && m_callback)
247       m_callback(*this, m_callback_baton);
248     return true;
249   }
250   return false;
251 }
252 
253 PathMappingList::const_iterator
254 PathMappingList::FindIteratorForPath(const ConstString &path) const {
255   const_iterator pos;
256   const_iterator begin = m_pairs.begin();
257   const_iterator end = m_pairs.end();
258 
259   for (pos = begin; pos != end; ++pos) {
260     if (pos->first == path)
261       break;
262   }
263   return pos;
264 }
265 
266 PathMappingList::iterator
267 PathMappingList::FindIteratorForPath(const ConstString &path) {
268   iterator pos;
269   iterator begin = m_pairs.begin();
270   iterator end = m_pairs.end();
271 
272   for (pos = begin; pos != end; ++pos) {
273     if (pos->first == path)
274       break;
275   }
276   return pos;
277 }
278 
279 bool PathMappingList::GetPathsAtIndex(uint32_t idx, ConstString &path,
280                                       ConstString &new_path) const {
281   if (idx < m_pairs.size()) {
282     path = m_pairs[idx].first;
283     new_path = m_pairs[idx].second;
284     return true;
285   }
286   return false;
287 }
288 
289 uint32_t PathMappingList::FindIndexForPath(const ConstString &orig_path) const {
290   const ConstString path = NormalizePath(orig_path);
291   const_iterator pos;
292   const_iterator begin = m_pairs.begin();
293   const_iterator end = m_pairs.end();
294 
295   for (pos = begin; pos != end; ++pos) {
296     if (pos->first == path)
297       return std::distance(begin, pos);
298   }
299   return UINT32_MAX;
300 }
301