1da816ca0SGreg Clayton //===-- DataFileCache.cpp -------------------------------------------------===//
2da816ca0SGreg Clayton //
3da816ca0SGreg Clayton // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4da816ca0SGreg Clayton // See https://llvm.org/LICENSE.txt for license information.
5da816ca0SGreg Clayton // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6da816ca0SGreg Clayton //
7da816ca0SGreg Clayton //===----------------------------------------------------------------------===//
8da816ca0SGreg Clayton 
9da816ca0SGreg Clayton #include "lldb/Core/DataFileCache.h"
10da816ca0SGreg Clayton #include "lldb/Core/Module.h"
11da816ca0SGreg Clayton #include "lldb/Core/ModuleList.h"
12da816ca0SGreg Clayton #include "lldb/Host/FileSystem.h"
13da816ca0SGreg Clayton #include "lldb/Symbol/ObjectFile.h"
14da816ca0SGreg Clayton #include "lldb/Utility/DataEncoder.h"
15da816ca0SGreg Clayton #include "lldb/Utility/Log.h"
16da816ca0SGreg Clayton #include "lldb/Utility/Logging.h"
17da816ca0SGreg Clayton #include "llvm/Support/CachePruning.h"
18da816ca0SGreg Clayton #include "llvm/Support/MemoryBuffer.h"
19da816ca0SGreg Clayton 
20da816ca0SGreg Clayton using namespace llvm;
21da816ca0SGreg Clayton using namespace lldb_private;
22da816ca0SGreg Clayton 
23da816ca0SGreg Clayton DataFileCache::DataFileCache(StringRef path) {
24da816ca0SGreg Clayton   m_cache_dir.SetPath(path);
25da816ca0SGreg Clayton 
26da816ca0SGreg Clayton   // Prune the cache based off of the LLDB settings each time we create a cache
27da816ca0SGreg Clayton   // object.
28da816ca0SGreg Clayton   ModuleListProperties &properties =
29da816ca0SGreg Clayton       ModuleList::GetGlobalModuleListProperties();
30da816ca0SGreg Clayton   CachePruningPolicy policy;
31da816ca0SGreg Clayton   // Only scan once an hour. If we have lots of debug sessions we don't want
32da816ca0SGreg Clayton   // to scan this directory too often. A timestamp file is written to the
33da816ca0SGreg Clayton   // directory to ensure different processes don't scan the directory too often.
34da816ca0SGreg Clayton   // This setting doesn't mean that a thread will continually scan the cache
35da816ca0SGreg Clayton   // directory within this process.
36da816ca0SGreg Clayton   policy.Interval = std::chrono::hours(1);
37da816ca0SGreg Clayton   // Get the user settings for pruning.
38da816ca0SGreg Clayton   policy.MaxSizeBytes = properties.GetLLDBIndexCacheMaxByteSize();
39da816ca0SGreg Clayton   policy.MaxSizePercentageOfAvailableSpace =
40da816ca0SGreg Clayton       properties.GetLLDBIndexCacheMaxPercent();
41da816ca0SGreg Clayton   policy.Expiration =
42da816ca0SGreg Clayton       std::chrono::hours(properties.GetLLDBIndexCacheExpirationDays() * 24);
43da816ca0SGreg Clayton   pruneCache(path, policy);
44da816ca0SGreg Clayton 
45da816ca0SGreg Clayton   // This lambda will get called when the data is gotten from the cache and
46da816ca0SGreg Clayton   // also after the data was set for a given key. We only need to take
47da816ca0SGreg Clayton   // ownership of the data if we are geting the data, so we use the
48da816ca0SGreg Clayton   // m_take_ownership member variable to indicate if we need to take
49da816ca0SGreg Clayton   // ownership.
50da816ca0SGreg Clayton 
51da816ca0SGreg Clayton   auto add_buffer = [this](unsigned task, std::unique_ptr<llvm::MemoryBuffer> m) {
52da816ca0SGreg Clayton     if (m_take_ownership)
53da816ca0SGreg Clayton       m_mem_buff_up = std::move(m);
54da816ca0SGreg Clayton   };
55da816ca0SGreg Clayton   Expected<FileCache> cache_or_err =
56da816ca0SGreg Clayton       llvm::localCache("LLDBModuleCache", "lldb-module", path, add_buffer);
57da816ca0SGreg Clayton   if (cache_or_err)
58da816ca0SGreg Clayton     m_cache_callback = std::move(*cache_or_err);
59da816ca0SGreg Clayton   else {
60*a007a6d8SPavel Labath     Log *log = GetLog(LLDBLog::Modules);
61da816ca0SGreg Clayton     LLDB_LOG_ERROR(log, cache_or_err.takeError(),
62da816ca0SGreg Clayton                    "failed to create lldb index cache directory: {0}");
63da816ca0SGreg Clayton   }
64da816ca0SGreg Clayton }
65da816ca0SGreg Clayton 
66da816ca0SGreg Clayton std::unique_ptr<llvm::MemoryBuffer>
67da816ca0SGreg Clayton DataFileCache::GetCachedData(StringRef key) {
68da816ca0SGreg Clayton   std::lock_guard<std::mutex> guard(m_mutex);
69da816ca0SGreg Clayton 
70da816ca0SGreg Clayton   const unsigned task = 1;
71da816ca0SGreg Clayton   m_take_ownership = true;
72da816ca0SGreg Clayton   // If we call the "m_cache_callback" function and the data is cached, it will
73da816ca0SGreg Clayton   // call the "add_buffer" lambda function from the constructor which will in
74da816ca0SGreg Clayton   // turn take ownership of the member buffer that is passed to the callback and
75da816ca0SGreg Clayton   // put it into a member variable.
76da816ca0SGreg Clayton   Expected<AddStreamFn> add_stream_or_err = m_cache_callback(task, key);
77da816ca0SGreg Clayton   m_take_ownership = false;
78da816ca0SGreg Clayton   // At this point we either already called the "add_buffer" lambda with
79da816ca0SGreg Clayton   // the data or we haven't. We can tell if we got the cached data by checking
80da816ca0SGreg Clayton   // the add_stream function pointer value below.
81da816ca0SGreg Clayton   if (add_stream_or_err) {
82da816ca0SGreg Clayton     AddStreamFn &add_stream = *add_stream_or_err;
83da816ca0SGreg Clayton     // If the "add_stream" is nullptr, then the data was cached and we already
84da816ca0SGreg Clayton     // called the "add_buffer" lambda. If it is valid, then if we were to call
85da816ca0SGreg Clayton     // the add_stream function it would cause a cache file to get generated
86da816ca0SGreg Clayton     // and we would be expected to fill in the data. In this function we only
87da816ca0SGreg Clayton     // want to check if the data was cached, so we don't want to call
88da816ca0SGreg Clayton     // "add_stream" in this function.
89da816ca0SGreg Clayton     if (!add_stream)
90da816ca0SGreg Clayton       return std::move(m_mem_buff_up);
91da816ca0SGreg Clayton   } else {
92*a007a6d8SPavel Labath     Log *log = GetLog(LLDBLog::Modules);
93da816ca0SGreg Clayton     LLDB_LOG_ERROR(log, add_stream_or_err.takeError(),
94da816ca0SGreg Clayton                    "failed to get the cache add stream callback for key: {0}");
95da816ca0SGreg Clayton   }
96da816ca0SGreg Clayton   // Data was not cached.
97da816ca0SGreg Clayton   return std::unique_ptr<llvm::MemoryBuffer>();
98da816ca0SGreg Clayton }
99da816ca0SGreg Clayton 
100da816ca0SGreg Clayton bool DataFileCache::SetCachedData(StringRef key, llvm::ArrayRef<uint8_t> data) {
101da816ca0SGreg Clayton   std::lock_guard<std::mutex> guard(m_mutex);
102da816ca0SGreg Clayton   const unsigned task = 2;
103da816ca0SGreg Clayton   // If we call this function and the data is cached, it will call the
104da816ca0SGreg Clayton   // add_buffer lambda function from the constructor which will ignore the
105da816ca0SGreg Clayton   // data.
106da816ca0SGreg Clayton   Expected<AddStreamFn> add_stream_or_err = m_cache_callback(task, key);
107da816ca0SGreg Clayton   // If we reach this code then we either already called the callback with
108da816ca0SGreg Clayton   // the data or we haven't. We can tell if we had the cached data by checking
109da816ca0SGreg Clayton   // the CacheAddStream function pointer value below.
110da816ca0SGreg Clayton   if (add_stream_or_err) {
111da816ca0SGreg Clayton     AddStreamFn &add_stream = *add_stream_or_err;
112da816ca0SGreg Clayton     // If the "add_stream" is nullptr, then the data was cached. If it is
113da816ca0SGreg Clayton     // valid, then if we call the add_stream function with a task it will
114da816ca0SGreg Clayton     // cause the file to get generated, but we only want to check if the data
115da816ca0SGreg Clayton     // is cached here, so we don't want to call it here. Note that the
116da816ca0SGreg Clayton     // add_buffer will also get called in this case after the data has been
117da816ca0SGreg Clayton     // provided, but we won't take ownership of the memory buffer as we just
118da816ca0SGreg Clayton     // want to write the data.
119da816ca0SGreg Clayton     if (add_stream) {
120da816ca0SGreg Clayton       Expected<std::unique_ptr<CachedFileStream>> file_or_err =
121da816ca0SGreg Clayton           add_stream(task);
122da816ca0SGreg Clayton       if (file_or_err) {
123da816ca0SGreg Clayton         CachedFileStream *cfs = file_or_err->get();
124da816ca0SGreg Clayton         cfs->OS->write((const char *)data.data(), data.size());
125da816ca0SGreg Clayton         return true;
126da816ca0SGreg Clayton       } else {
127*a007a6d8SPavel Labath         Log *log = GetLog(LLDBLog::Modules);
128da816ca0SGreg Clayton         LLDB_LOG_ERROR(log, file_or_err.takeError(),
129da816ca0SGreg Clayton                        "failed to get the cache file stream for key: {0}");
130da816ca0SGreg Clayton       }
131da816ca0SGreg Clayton     }
132da816ca0SGreg Clayton   } else {
133*a007a6d8SPavel Labath     Log *log = GetLog(LLDBLog::Modules);
134da816ca0SGreg Clayton     LLDB_LOG_ERROR(log, add_stream_or_err.takeError(),
135da816ca0SGreg Clayton                    "failed to get the cache add stream callback for key: {0}");
136da816ca0SGreg Clayton   }
137da816ca0SGreg Clayton   return false;
138da816ca0SGreg Clayton }
139da816ca0SGreg Clayton 
140da816ca0SGreg Clayton FileSpec DataFileCache::GetCacheFilePath(llvm::StringRef key) {
141da816ca0SGreg Clayton   FileSpec cache_file(m_cache_dir);
142da816ca0SGreg Clayton   std::string filename("llvmcache-");
143da816ca0SGreg Clayton   filename += key.str();
144da816ca0SGreg Clayton   cache_file.AppendPathComponent(filename);
145da816ca0SGreg Clayton   return cache_file;
146da816ca0SGreg Clayton }
147da816ca0SGreg Clayton 
148da816ca0SGreg Clayton Status DataFileCache::RemoveCacheFile(llvm::StringRef key) {
149da816ca0SGreg Clayton   FileSpec cache_file = GetCacheFilePath(key);
150da816ca0SGreg Clayton   FileSystem &fs = FileSystem::Instance();
151da816ca0SGreg Clayton   if (!fs.Exists(cache_file))
152da816ca0SGreg Clayton     return Status();
153da816ca0SGreg Clayton   return fs.RemoveFile(cache_file);
154da816ca0SGreg Clayton }
155da816ca0SGreg Clayton 
156da816ca0SGreg Clayton CacheSignature::CacheSignature(lldb_private::Module *module) {
157da816ca0SGreg Clayton   Clear();
158da816ca0SGreg Clayton   UUID uuid = module->GetUUID();
159da816ca0SGreg Clayton   if (uuid.IsValid())
160da816ca0SGreg Clayton     m_uuid = uuid;
161da816ca0SGreg Clayton 
162da816ca0SGreg Clayton   std::time_t mod_time = 0;
163da816ca0SGreg Clayton   mod_time = llvm::sys::toTimeT(module->GetModificationTime());
164da816ca0SGreg Clayton   if (mod_time != 0)
165da816ca0SGreg Clayton     m_mod_time = mod_time;
166da816ca0SGreg Clayton 
167da816ca0SGreg Clayton   mod_time = llvm::sys::toTimeT(module->GetObjectModificationTime());
168da816ca0SGreg Clayton   if (mod_time != 0)
169da816ca0SGreg Clayton     m_obj_mod_time = mod_time;
170da816ca0SGreg Clayton }
171da816ca0SGreg Clayton 
172da816ca0SGreg Clayton CacheSignature::CacheSignature(lldb_private::ObjectFile *objfile) {
173da816ca0SGreg Clayton   Clear();
174da816ca0SGreg Clayton   UUID uuid = objfile->GetUUID();
175da816ca0SGreg Clayton   if (uuid.IsValid())
176da816ca0SGreg Clayton     m_uuid = uuid;
177da816ca0SGreg Clayton 
178da816ca0SGreg Clayton   std::time_t mod_time = 0;
179da816ca0SGreg Clayton   // Grab the modification time of the object file's file. It isn't always the
180da816ca0SGreg Clayton   // same as the module's file when you have a executable file as the main
181da816ca0SGreg Clayton   // executable, and you have a object file for a symbol file.
182da816ca0SGreg Clayton   FileSystem &fs = FileSystem::Instance();
183da816ca0SGreg Clayton   mod_time = llvm::sys::toTimeT(fs.GetModificationTime(objfile->GetFileSpec()));
184da816ca0SGreg Clayton   if (mod_time != 0)
185da816ca0SGreg Clayton     m_mod_time = mod_time;
186da816ca0SGreg Clayton 
187da816ca0SGreg Clayton   mod_time =
188da816ca0SGreg Clayton       llvm::sys::toTimeT(objfile->GetModule()->GetObjectModificationTime());
189da816ca0SGreg Clayton   if (mod_time != 0)
190da816ca0SGreg Clayton     m_obj_mod_time = mod_time;
191da816ca0SGreg Clayton }
192da816ca0SGreg Clayton 
193da816ca0SGreg Clayton enum SignatureEncoding {
194da816ca0SGreg Clayton   eSignatureUUID = 1u,
195da816ca0SGreg Clayton   eSignatureModTime = 2u,
196da816ca0SGreg Clayton   eSignatureObjectModTime = 3u,
197da816ca0SGreg Clayton   eSignatureEnd = 255u,
198da816ca0SGreg Clayton };
199da816ca0SGreg Clayton 
200da816ca0SGreg Clayton bool CacheSignature::Encode(DataEncoder &encoder) {
201da816ca0SGreg Clayton   if (!IsValid())
202da816ca0SGreg Clayton     return false; // Invalid signature, return false!
203da816ca0SGreg Clayton 
204da816ca0SGreg Clayton   if (m_uuid.hasValue()) {
205da816ca0SGreg Clayton     llvm::ArrayRef<uint8_t> uuid_bytes = m_uuid->GetBytes();
206da816ca0SGreg Clayton     encoder.AppendU8(eSignatureUUID);
207da816ca0SGreg Clayton     encoder.AppendU8(uuid_bytes.size());
208da816ca0SGreg Clayton     encoder.AppendData(uuid_bytes);
209da816ca0SGreg Clayton   }
210da816ca0SGreg Clayton   if (m_mod_time.hasValue()) {
211da816ca0SGreg Clayton     encoder.AppendU8(eSignatureModTime);
212da816ca0SGreg Clayton     encoder.AppendU32(*m_mod_time);
213da816ca0SGreg Clayton   }
214da816ca0SGreg Clayton   if (m_obj_mod_time.hasValue()) {
215da816ca0SGreg Clayton     encoder.AppendU8(eSignatureObjectModTime);
216da816ca0SGreg Clayton     encoder.AppendU32(*m_obj_mod_time);
217da816ca0SGreg Clayton   }
218da816ca0SGreg Clayton   encoder.AppendU8(eSignatureEnd);
219da816ca0SGreg Clayton   return true;
220da816ca0SGreg Clayton }
221da816ca0SGreg Clayton 
222da816ca0SGreg Clayton bool CacheSignature::Decode(const DataExtractor &data,
223da816ca0SGreg Clayton                             lldb::offset_t *offset_ptr) {
224da816ca0SGreg Clayton   Clear();
225da816ca0SGreg Clayton   while (uint8_t sig_encoding = data.GetU8(offset_ptr)) {
226da816ca0SGreg Clayton     switch (sig_encoding) {
227da816ca0SGreg Clayton     case eSignatureUUID: {
228da816ca0SGreg Clayton       const uint8_t length = data.GetU8(offset_ptr);
229da816ca0SGreg Clayton       const uint8_t *bytes = (const uint8_t *)data.GetData(offset_ptr, length);
230da816ca0SGreg Clayton       if (bytes != nullptr && length > 0)
231da816ca0SGreg Clayton         m_uuid = UUID::fromData(llvm::ArrayRef<uint8_t>(bytes, length));
232da816ca0SGreg Clayton     } break;
233da816ca0SGreg Clayton     case eSignatureModTime: {
234da816ca0SGreg Clayton       uint32_t mod_time = data.GetU32(offset_ptr);
235da816ca0SGreg Clayton       if (mod_time > 0)
236da816ca0SGreg Clayton         m_mod_time = mod_time;
237da816ca0SGreg Clayton     } break;
238da816ca0SGreg Clayton     case eSignatureObjectModTime: {
239da816ca0SGreg Clayton       uint32_t mod_time = data.GetU32(offset_ptr);
240da816ca0SGreg Clayton       if (mod_time > 0)
241da816ca0SGreg Clayton         m_mod_time = mod_time;
242da816ca0SGreg Clayton     } break;
243da816ca0SGreg Clayton     case eSignatureEnd:
244da816ca0SGreg Clayton       return true;
245da816ca0SGreg Clayton     default:
246da816ca0SGreg Clayton       break;
247da816ca0SGreg Clayton     }
248da816ca0SGreg Clayton   }
249da816ca0SGreg Clayton   return false;
250da816ca0SGreg Clayton }
251da816ca0SGreg Clayton 
252da816ca0SGreg Clayton uint32_t ConstStringTable::Add(ConstString s) {
253da816ca0SGreg Clayton   auto pos = m_string_to_offset.find(s);
254da816ca0SGreg Clayton   if (pos != m_string_to_offset.end())
255da816ca0SGreg Clayton     return pos->second;
256da816ca0SGreg Clayton   const uint32_t offset = m_next_offset;
257da816ca0SGreg Clayton   m_strings.push_back(s);
258da816ca0SGreg Clayton   m_string_to_offset[s] = offset;
259da816ca0SGreg Clayton   m_next_offset += s.GetLength() + 1;
260da816ca0SGreg Clayton   return offset;
261da816ca0SGreg Clayton }
262da816ca0SGreg Clayton 
263da816ca0SGreg Clayton static const llvm::StringRef kStringTableIdentifier("STAB");
264da816ca0SGreg Clayton 
265da816ca0SGreg Clayton bool ConstStringTable::Encode(DataEncoder &encoder) {
266da816ca0SGreg Clayton   // Write an 4 character code into the stream. This will help us when decoding
267da816ca0SGreg Clayton   // to make sure we find this identifier when decoding the string table to make
268da816ca0SGreg Clayton   // sure we have the rigth data. It also helps to identify the string table
269da816ca0SGreg Clayton   // when dumping the hex bytes in a cache file.
270da816ca0SGreg Clayton   encoder.AppendData(kStringTableIdentifier);
271da816ca0SGreg Clayton   size_t length_offset = encoder.GetByteSize();
272da816ca0SGreg Clayton   encoder.AppendU32(0); // Total length of all strings which will be fixed up.
273da816ca0SGreg Clayton   size_t strtab_offset = encoder.GetByteSize();
274da816ca0SGreg Clayton   encoder.AppendU8(0); // Start the string table with with an empty string.
275da816ca0SGreg Clayton   for (auto s: m_strings) {
276da816ca0SGreg Clayton     // Make sure all of the offsets match up with what we handed out!
27712873d1aSBenjamin Kramer     assert(m_string_to_offset.find(s)->second ==
27812873d1aSBenjamin Kramer            encoder.GetByteSize() - strtab_offset);
279da816ca0SGreg Clayton     // Append the C string into the encoder
280da816ca0SGreg Clayton     encoder.AppendCString(s.GetStringRef());
281da816ca0SGreg Clayton   }
282da816ca0SGreg Clayton   // Fixup the string table length.
283da816ca0SGreg Clayton   encoder.PutU32(length_offset, encoder.GetByteSize() - strtab_offset);
284da816ca0SGreg Clayton   return true;
285da816ca0SGreg Clayton }
286da816ca0SGreg Clayton 
287da816ca0SGreg Clayton bool StringTableReader::Decode(const DataExtractor &data,
288da816ca0SGreg Clayton                                lldb::offset_t *offset_ptr) {
289da816ca0SGreg Clayton   llvm::StringRef identifier((const char *)data.GetData(offset_ptr, 4), 4);
290da816ca0SGreg Clayton   if (identifier != kStringTableIdentifier)
291da816ca0SGreg Clayton     return false;
292da816ca0SGreg Clayton   const uint32_t length = data.GetU32(offset_ptr);
293da816ca0SGreg Clayton   // We always have at least one byte for the empty string at offset zero.
294da816ca0SGreg Clayton   if (length == 0)
295da816ca0SGreg Clayton     return false;
296da816ca0SGreg Clayton   const char *bytes = (const char *)data.GetData(offset_ptr, length);
297da816ca0SGreg Clayton   if (bytes == nullptr)
298da816ca0SGreg Clayton     return false;
299da816ca0SGreg Clayton   m_data = StringRef(bytes, length);
300da816ca0SGreg Clayton   return true;
301da816ca0SGreg Clayton }
302da816ca0SGreg Clayton 
303da816ca0SGreg Clayton StringRef StringTableReader::Get(uint32_t offset) const {
304da816ca0SGreg Clayton   if (offset >= m_data.size())
305da816ca0SGreg Clayton     return StringRef();
306da816ca0SGreg Clayton   return StringRef(m_data.data() + offset);
307da816ca0SGreg Clayton }
308