xref: /llvm-project/lldb/source/Target/ModuleCache.cpp (revision d82067f83a732749ffdcfa3d3f6abb6e817a5951)
1 //===--------------------- ModuleCache.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Target/ModuleCache.h"
11 
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ModuleList.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Host/File.h"
16 #include "lldb/Host/FileSystem.h"
17 #include "lldb/Host/LockFile.h"
18 #include "lldb/Utility/Log.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/FileUtilities.h"
21 
22 #include <assert.h>
23 
24 #include <cstdio>
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 namespace {
30 
31 const char *kModulesSubdir = ".cache";
32 const char *kLockDirName = ".lock";
33 const char *kTempFileName = ".temp";
34 const char *kTempSymFileName = ".symtemp";
35 const char *kSymFileExtension = ".sym";
36 const char *kFSIllegalChars = "\\/:*?\"<>|";
37 
38 std::string GetEscapedHostname(const char *hostname) {
39   if (hostname == nullptr)
40     hostname = "unknown";
41   std::string result(hostname);
42   size_t size = result.size();
43   for (size_t i = 0; i < size; ++i) {
44     if ((result[i] >= 1 && result[i] <= 31) ||
45         strchr(kFSIllegalChars, result[i]) != nullptr)
46       result[i] = '_';
47   }
48   return result;
49 }
50 
51 class ModuleLock {
52 private:
53   File m_file;
54   std::unique_ptr<lldb_private::LockFile> m_lock;
55   FileSpec m_file_spec;
56 
57 public:
58   ModuleLock(const FileSpec &root_dir_spec, const UUID &uuid, Error &error);
59   void Delete();
60 };
61 
62 static FileSpec JoinPath(const FileSpec &path1, const char *path2) {
63   FileSpec result_spec(path1);
64   result_spec.AppendPathComponent(path2);
65   return result_spec;
66 }
67 
68 static Error MakeDirectory(const FileSpec &dir_path) {
69   namespace fs = llvm::sys::fs;
70 
71   return fs::create_directories(dir_path.GetPath(), true, fs::perms::owner_all);
72 }
73 
74 FileSpec GetModuleDirectory(const FileSpec &root_dir_spec, const UUID &uuid) {
75   const auto modules_dir_spec = JoinPath(root_dir_spec, kModulesSubdir);
76   return JoinPath(modules_dir_spec, uuid.GetAsString().c_str());
77 }
78 
79 FileSpec GetSymbolFileSpec(const FileSpec &module_file_spec) {
80   return FileSpec(module_file_spec.GetPath() + kSymFileExtension, false);
81 }
82 
83 void DeleteExistingModule(const FileSpec &root_dir_spec,
84                           const FileSpec &sysroot_module_path_spec) {
85   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
86   UUID module_uuid;
87   {
88     auto module_sp =
89         std::make_shared<Module>(ModuleSpec(sysroot_module_path_spec));
90     module_uuid = module_sp->GetUUID();
91   }
92 
93   if (!module_uuid.IsValid())
94     return;
95 
96   Error error;
97   ModuleLock lock(root_dir_spec, module_uuid, error);
98   if (error.Fail()) {
99     if (log)
100       log->Printf("Failed to lock module %s: %s",
101                   module_uuid.GetAsString().c_str(), error.AsCString());
102   }
103 
104   auto link_count = FileSystem::GetHardlinkCount(sysroot_module_path_spec);
105   if (link_count == -1)
106     return;
107 
108   if (link_count > 2) // module is referred by other hosts.
109     return;
110 
111   const auto module_spec_dir = GetModuleDirectory(root_dir_spec, module_uuid);
112   llvm::sys::fs::remove_directories(module_spec_dir.GetPath());
113   lock.Delete();
114 }
115 
116 void DecrementRefExistingModule(const FileSpec &root_dir_spec,
117                                 const FileSpec &sysroot_module_path_spec) {
118   // Remove $platform/.cache/$uuid folder if nobody else references it.
119   DeleteExistingModule(root_dir_spec, sysroot_module_path_spec);
120 
121   // Remove sysroot link.
122   FileSystem::Unlink(sysroot_module_path_spec);
123 
124   FileSpec symfile_spec = GetSymbolFileSpec(sysroot_module_path_spec);
125   if (symfile_spec.Exists()) // delete module's symbol file if exists.
126     FileSystem::Unlink(symfile_spec);
127 }
128 
129 Error CreateHostSysRootModuleLink(const FileSpec &root_dir_spec,
130                                   const char *hostname,
131                                   const FileSpec &platform_module_spec,
132                                   const FileSpec &local_module_spec,
133                                   bool delete_existing) {
134   const auto sysroot_module_path_spec =
135       JoinPath(JoinPath(root_dir_spec, hostname),
136                platform_module_spec.GetPath().c_str());
137   if (sysroot_module_path_spec.Exists()) {
138     if (!delete_existing)
139       return Error();
140 
141     DecrementRefExistingModule(root_dir_spec, sysroot_module_path_spec);
142   }
143 
144   const auto error = MakeDirectory(
145       FileSpec(sysroot_module_path_spec.GetDirectory().AsCString(), false));
146   if (error.Fail())
147     return error;
148 
149   return FileSystem::Hardlink(sysroot_module_path_spec, local_module_spec);
150 }
151 
152 } // namespace
153 
154 ModuleLock::ModuleLock(const FileSpec &root_dir_spec, const UUID &uuid,
155                        Error &error) {
156   const auto lock_dir_spec = JoinPath(root_dir_spec, kLockDirName);
157   error = MakeDirectory(lock_dir_spec);
158   if (error.Fail())
159     return;
160 
161   m_file_spec = JoinPath(lock_dir_spec, uuid.GetAsString().c_str());
162   m_file.Open(m_file_spec.GetCString(), File::eOpenOptionWrite |
163                                             File::eOpenOptionCanCreate |
164                                             File::eOpenOptionCloseOnExec);
165   if (!m_file) {
166     error.SetErrorToErrno();
167     return;
168   }
169 
170   m_lock.reset(new lldb_private::LockFile(m_file.GetDescriptor()));
171   error = m_lock->WriteLock(0, 1);
172   if (error.Fail())
173     error.SetErrorStringWithFormat("Failed to lock file: %s",
174                                    error.AsCString());
175 }
176 
177 void ModuleLock::Delete() {
178   if (!m_file)
179     return;
180 
181   m_file.Close();
182   FileSystem::Unlink(m_file_spec);
183 }
184 
185 /////////////////////////////////////////////////////////////////////////
186 
187 Error ModuleCache::Put(const FileSpec &root_dir_spec, const char *hostname,
188                        const ModuleSpec &module_spec, const FileSpec &tmp_file,
189                        const FileSpec &target_file) {
190   const auto module_spec_dir =
191       GetModuleDirectory(root_dir_spec, module_spec.GetUUID());
192   const auto module_file_path =
193       JoinPath(module_spec_dir, target_file.GetFilename().AsCString());
194 
195   const auto tmp_file_path = tmp_file.GetPath();
196   const auto err_code =
197       llvm::sys::fs::rename(tmp_file_path, module_file_path.GetPath());
198   if (err_code)
199     return Error("Failed to rename file %s to %s: %s", tmp_file_path.c_str(),
200                  module_file_path.GetPath().c_str(),
201                  err_code.message().c_str());
202 
203   const auto error = CreateHostSysRootModuleLink(
204       root_dir_spec, hostname, target_file, module_file_path, true);
205   if (error.Fail())
206     return Error("Failed to create link to %s: %s",
207                  module_file_path.GetPath().c_str(), error.AsCString());
208   return Error();
209 }
210 
211 Error ModuleCache::Get(const FileSpec &root_dir_spec, const char *hostname,
212                        const ModuleSpec &module_spec,
213                        ModuleSP &cached_module_sp, bool *did_create_ptr) {
214   const auto find_it =
215       m_loaded_modules.find(module_spec.GetUUID().GetAsString());
216   if (find_it != m_loaded_modules.end()) {
217     cached_module_sp = (*find_it).second.lock();
218     if (cached_module_sp)
219       return Error();
220     m_loaded_modules.erase(find_it);
221   }
222 
223   const auto module_spec_dir =
224       GetModuleDirectory(root_dir_spec, module_spec.GetUUID());
225   const auto module_file_path = JoinPath(
226       module_spec_dir, module_spec.GetFileSpec().GetFilename().AsCString());
227 
228   if (!module_file_path.Exists())
229     return Error("Module %s not found", module_file_path.GetPath().c_str());
230   if (module_file_path.GetByteSize() != module_spec.GetObjectSize())
231     return Error("Module %s has invalid file size",
232                  module_file_path.GetPath().c_str());
233 
234   // We may have already cached module but downloaded from an another host - in
235   // this case let's create a link to it.
236   auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname,
237                                            module_spec.GetFileSpec(),
238                                            module_file_path, false);
239   if (error.Fail())
240     return Error("Failed to create link to %s: %s",
241                  module_file_path.GetPath().c_str(), error.AsCString());
242 
243   auto cached_module_spec(module_spec);
244   cached_module_spec.GetUUID().Clear(); // Clear UUID since it may contain md5
245                                         // content hash instead of real UUID.
246   cached_module_spec.GetFileSpec() = module_file_path;
247   cached_module_spec.GetPlatformFileSpec() = module_spec.GetFileSpec();
248 
249   error = ModuleList::GetSharedModule(cached_module_spec, cached_module_sp,
250                                       nullptr, nullptr, did_create_ptr, false);
251   if (error.Fail())
252     return error;
253 
254   FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec());
255   if (symfile_spec.Exists())
256     cached_module_sp->SetSymbolFileFileSpec(symfile_spec);
257 
258   m_loaded_modules.insert(
259       std::make_pair(module_spec.GetUUID().GetAsString(), cached_module_sp));
260 
261   return Error();
262 }
263 
264 Error ModuleCache::GetAndPut(const FileSpec &root_dir_spec,
265                              const char *hostname,
266                              const ModuleSpec &module_spec,
267                              const ModuleDownloader &module_downloader,
268                              const SymfileDownloader &symfile_downloader,
269                              lldb::ModuleSP &cached_module_sp,
270                              bool *did_create_ptr) {
271   const auto module_spec_dir =
272       GetModuleDirectory(root_dir_spec, module_spec.GetUUID());
273   auto error = MakeDirectory(module_spec_dir);
274   if (error.Fail())
275     return error;
276 
277   ModuleLock lock(root_dir_spec, module_spec.GetUUID(), error);
278   if (error.Fail())
279     return Error("Failed to lock module %s: %s",
280                  module_spec.GetUUID().GetAsString().c_str(),
281                  error.AsCString());
282 
283   const auto escaped_hostname(GetEscapedHostname(hostname));
284   // Check local cache for a module.
285   error = Get(root_dir_spec, escaped_hostname.c_str(), module_spec,
286               cached_module_sp, did_create_ptr);
287   if (error.Success())
288     return error;
289 
290   const auto tmp_download_file_spec = JoinPath(module_spec_dir, kTempFileName);
291   error = module_downloader(module_spec, tmp_download_file_spec);
292   llvm::FileRemover tmp_file_remover(tmp_download_file_spec.GetPath());
293   if (error.Fail())
294     return Error("Failed to download module: %s", error.AsCString());
295 
296   // Put downloaded file into local module cache.
297   error = Put(root_dir_spec, escaped_hostname.c_str(), module_spec,
298               tmp_download_file_spec, module_spec.GetFileSpec());
299   if (error.Fail())
300     return Error("Failed to put module into cache: %s", error.AsCString());
301 
302   tmp_file_remover.releaseFile();
303   error = Get(root_dir_spec, escaped_hostname.c_str(), module_spec,
304               cached_module_sp, did_create_ptr);
305   if (error.Fail())
306     return error;
307 
308   // Fetching a symbol file for the module
309   const auto tmp_download_sym_file_spec =
310       JoinPath(module_spec_dir, kTempSymFileName);
311   error = symfile_downloader(cached_module_sp, tmp_download_sym_file_spec);
312   llvm::FileRemover tmp_symfile_remover(tmp_download_sym_file_spec.GetPath());
313   if (error.Fail())
314     // Failed to download a symfile but fetching the module was successful. The
315     // module might
316     // contain the necessary symbols and the debugging is also possible without
317     // a symfile.
318     return Error();
319 
320   error = Put(root_dir_spec, escaped_hostname.c_str(), module_spec,
321               tmp_download_sym_file_spec,
322               GetSymbolFileSpec(module_spec.GetFileSpec()));
323   if (error.Fail())
324     return Error("Failed to put symbol file into cache: %s", error.AsCString());
325 
326   tmp_symfile_remover.releaseFile();
327 
328   FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec());
329   cached_module_sp->SetSymbolFileFileSpec(symfile_spec);
330   return Error();
331 }
332