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