blob: 86c788d3b36ab97c7fff4308acda8178b637f5fd [file] [log] [blame]
Mathias Agopian5f549b22017-03-08 22:27:13 -08001/*
2 ** Copyright 2011, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
Mathias Agopian5f549b22017-03-08 22:27:13 -080017//#define LOG_NDEBUG 0
18
Mathias Agopianb7f9a242017-03-08 22:29:31 -080019#include "BlobCache.h"
Mathias Agopian5f549b22017-03-08 22:27:13 -080020
Yiwei Zhang8af03062020-08-12 21:28:15 -070021#include <android-base/properties.h>
Dan Albert9f93afe2017-10-11 12:42:46 -070022#include <errno.h>
Mathias Agopian5f549b22017-03-08 22:27:13 -080023#include <inttypes.h>
Mathias Agopianb7f9a242017-03-08 22:29:31 -080024#include <log/log.h>
Yiwei Zhang8af03062020-08-12 21:28:15 -070025
Mathias Agopianb7f9a242017-03-08 22:29:31 -080026#include <chrono>
Mathias Agopian5f549b22017-03-08 22:27:13 -080027
28namespace android {
29
30// BlobCache::Header::mMagicNumber value
31static const uint32_t blobCacheMagic = ('_' << 24) + ('B' << 16) + ('b' << 8) + '$';
32
33// BlobCache::Header::mBlobCacheVersion value
34static const uint32_t blobCacheVersion = 3;
35
36// BlobCache::Header::mDeviceVersion value
37static const uint32_t blobCacheDeviceVersion = 1;
38
Yiwei Zhang8af03062020-08-12 21:28:15 -070039BlobCache::BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize)
40 : mMaxTotalSize(maxTotalSize),
Mathias Agopian5f549b22017-03-08 22:27:13 -080041 mMaxKeySize(maxKeySize),
42 mMaxValueSize(maxValueSize),
Mathias Agopian5f549b22017-03-08 22:27:13 -080043 mTotalSize(0) {
Mathias Agopianb7f9a242017-03-08 22:29:31 -080044 int64_t now = std::chrono::steady_clock::now().time_since_epoch().count();
Mathias Agopian5f549b22017-03-08 22:27:13 -080045#ifdef _WIN32
46 srand(now);
47#else
48 mRandState[0] = (now >> 0) & 0xFFFF;
49 mRandState[1] = (now >> 16) & 0xFFFF;
50 mRandState[2] = (now >> 32) & 0xFFFF;
51#endif
52 ALOGV("initializing random seed using %lld", (unsigned long long)now);
53}
54
Leon Scroggins III23377962022-05-03 14:53:14 -040055BlobCache::InsertResult BlobCache::set(const void* key, size_t keySize, const void* value,
56 size_t valueSize) {
Mathias Agopian5f549b22017-03-08 22:27:13 -080057 if (mMaxKeySize < keySize) {
Yiwei Zhang8af03062020-08-12 21:28:15 -070058 ALOGV("set: not caching because the key is too large: %zu (limit: %zu)", keySize,
59 mMaxKeySize);
Leon Scroggins III23377962022-05-03 14:53:14 -040060 return InsertResult::kKeyTooBig;
Mathias Agopian5f549b22017-03-08 22:27:13 -080061 }
62 if (mMaxValueSize < valueSize) {
Yiwei Zhang8af03062020-08-12 21:28:15 -070063 ALOGV("set: not caching because the value is too large: %zu (limit: %zu)", valueSize,
64 mMaxValueSize);
Leon Scroggins III23377962022-05-03 14:53:14 -040065 return InsertResult::kValueTooBig;
Mathias Agopian5f549b22017-03-08 22:27:13 -080066 }
67 if (mMaxTotalSize < keySize + valueSize) {
68 ALOGV("set: not caching because the combined key/value size is too "
Yiwei Zhang8af03062020-08-12 21:28:15 -070069 "large: %zu (limit: %zu)",
70 keySize + valueSize, mMaxTotalSize);
Leon Scroggins III23377962022-05-03 14:53:14 -040071 return InsertResult::kCombinedTooBig;
Mathias Agopian5f549b22017-03-08 22:27:13 -080072 }
73 if (keySize == 0) {
74 ALOGW("set: not caching because keySize is 0");
Leon Scroggins III23377962022-05-03 14:53:14 -040075 return InsertResult::kInvalidKeySize;
Mathias Agopian5f549b22017-03-08 22:27:13 -080076 }
Leon Scroggins III23377962022-05-03 14:53:14 -040077 if (valueSize == 0) {
Mathias Agopian5f549b22017-03-08 22:27:13 -080078 ALOGW("set: not caching because valueSize is 0");
Leon Scroggins III23377962022-05-03 14:53:14 -040079 return InsertResult::kInvalidValueSize;
Mathias Agopian5f549b22017-03-08 22:27:13 -080080 }
81
Yiwei Zhang26169cd2020-07-28 15:46:12 -070082 std::shared_ptr<Blob> cacheKey(new Blob(key, keySize, false));
83 CacheEntry cacheEntry(cacheKey, nullptr);
Mathias Agopian5f549b22017-03-08 22:27:13 -080084
Leon Scroggins III23377962022-05-03 14:53:14 -040085 bool didClean = false;
Mathias Agopian5f549b22017-03-08 22:27:13 -080086 while (true) {
Yiwei Zhang26169cd2020-07-28 15:46:12 -070087 auto index = std::lower_bound(mCacheEntries.begin(), mCacheEntries.end(), cacheEntry);
88 if (index == mCacheEntries.end() || cacheEntry < *index) {
Mathias Agopian5f549b22017-03-08 22:27:13 -080089 // Create a new cache entry.
Mathias Agopianb7f9a242017-03-08 22:29:31 -080090 std::shared_ptr<Blob> keyBlob(new Blob(key, keySize, true));
91 std::shared_ptr<Blob> valueBlob(new Blob(value, valueSize, true));
Mathias Agopian5f549b22017-03-08 22:27:13 -080092 size_t newTotalSize = mTotalSize + keySize + valueSize;
93 if (mMaxTotalSize < newTotalSize) {
94 if (isCleanable()) {
95 // Clean the cache and try again.
96 clean();
Leon Scroggins III23377962022-05-03 14:53:14 -040097 didClean = true;
Mathias Agopian5f549b22017-03-08 22:27:13 -080098 continue;
99 } else {
100 ALOGV("set: not caching new key/value pair because the "
Yiwei Zhang8af03062020-08-12 21:28:15 -0700101 "total cache size limit would be exceeded: %zu "
102 "(limit: %zu)",
103 keySize + valueSize, mMaxTotalSize);
Leon Scroggins III23377962022-05-03 14:53:14 -0400104 return InsertResult::kNotEnoughSpace;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800105 }
106 }
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800107 mCacheEntries.insert(index, CacheEntry(keyBlob, valueBlob));
Mathias Agopian5f549b22017-03-08 22:27:13 -0800108 mTotalSize = newTotalSize;
Yiwei Zhang8af03062020-08-12 21:28:15 -0700109 ALOGV("set: created new cache entry with %zu byte key and %zu byte value", keySize,
110 valueSize);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800111 } else {
112 // Update the existing cache entry.
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800113 std::shared_ptr<Blob> valueBlob(new Blob(value, valueSize, true));
114 std::shared_ptr<Blob> oldValueBlob(index->getValue());
Mathias Agopian5f549b22017-03-08 22:27:13 -0800115 size_t newTotalSize = mTotalSize + valueSize - oldValueBlob->getSize();
116 if (mMaxTotalSize < newTotalSize) {
117 if (isCleanable()) {
118 // Clean the cache and try again.
119 clean();
Leon Scroggins III23377962022-05-03 14:53:14 -0400120 didClean = true;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800121 continue;
122 } else {
123 ALOGV("set: not caching new value because the total cache "
Yiwei Zhang8af03062020-08-12 21:28:15 -0700124 "size limit would be exceeded: %zu (limit: %zu)",
125 keySize + valueSize, mMaxTotalSize);
Leon Scroggins III23377962022-05-03 14:53:14 -0400126 return InsertResult::kNotEnoughSpace;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800127 }
128 }
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800129 index->setValue(valueBlob);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800130 mTotalSize = newTotalSize;
131 ALOGV("set: updated existing cache entry with %zu byte key and %zu byte "
Yiwei Zhang8af03062020-08-12 21:28:15 -0700132 "value",
133 keySize, valueSize);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800134 }
Leon Scroggins III23377962022-05-03 14:53:14 -0400135 return didClean ? InsertResult::kDidClean : InsertResult::kInserted;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800136 }
137}
138
Yiwei Zhang8af03062020-08-12 21:28:15 -0700139size_t BlobCache::get(const void* key, size_t keySize, void* value, size_t valueSize) {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800140 if (mMaxKeySize < keySize) {
Yiwei Zhang8af03062020-08-12 21:28:15 -0700141 ALOGV("get: not searching because the key is too large: %zu (limit %zu)", keySize,
142 mMaxKeySize);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800143 return 0;
144 }
Yiwei Zhang26169cd2020-07-28 15:46:12 -0700145 std::shared_ptr<Blob> cacheKey(new Blob(key, keySize, false));
146 CacheEntry cacheEntry(cacheKey, nullptr);
147 auto index = std::lower_bound(mCacheEntries.begin(), mCacheEntries.end(), cacheEntry);
148 if (index == mCacheEntries.end() || cacheEntry < *index) {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800149 ALOGV("get: no cache entry found for key of size %zu", keySize);
150 return 0;
151 }
152
153 // The key was found. Return the value if the caller's buffer is large
154 // enough.
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800155 std::shared_ptr<Blob> valueBlob(index->getValue());
Mathias Agopian5f549b22017-03-08 22:27:13 -0800156 size_t valueBlobSize = valueBlob->getSize();
157 if (valueBlobSize <= valueSize) {
158 ALOGV("get: copying %zu bytes to caller's buffer", valueBlobSize);
159 memcpy(value, valueBlob->getData(), valueBlobSize);
160 } else {
Yiwei Zhang8af03062020-08-12 21:28:15 -0700161 ALOGV("get: caller's buffer is too small for value: %zu (needs %zu)", valueSize,
162 valueBlobSize);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800163 }
164 return valueBlobSize;
165}
166
167static inline size_t align4(size_t size) {
168 return (size + 3) & ~3;
169}
170
171size_t BlobCache::getFlattenedSize() const {
Michael Hoisie4e0f56b2020-04-30 18:40:55 -0400172 auto buildId = base::GetProperty("ro.build.id", "");
173 size_t size = align4(sizeof(Header) + buildId.size());
Yiwei Zhang8af03062020-08-12 21:28:15 -0700174 for (const CacheEntry& e : mCacheEntries) {
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800175 std::shared_ptr<Blob> const& keyBlob = e.getKey();
176 std::shared_ptr<Blob> const& valueBlob = e.getValue();
177 size += align4(sizeof(EntryHeader) + keyBlob->getSize() + valueBlob->getSize());
Mathias Agopian5f549b22017-03-08 22:27:13 -0800178 }
179 return size;
180}
181
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800182int BlobCache::flatten(void* buffer, size_t size) const {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800183 // Write the cache header
184 if (size < sizeof(Header)) {
185 ALOGE("flatten: not enough room for cache header");
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800186 return 0;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800187 }
188 Header* header = reinterpret_cast<Header*>(buffer);
189 header->mMagicNumber = blobCacheMagic;
190 header->mBlobCacheVersion = blobCacheVersion;
191 header->mDeviceVersion = blobCacheDeviceVersion;
192 header->mNumEntries = mCacheEntries.size();
Michael Hoisie4e0f56b2020-04-30 18:40:55 -0400193 auto buildId = base::GetProperty("ro.build.id", "");
194 header->mBuildIdLength = buildId.size();
195 memcpy(header->mBuildId, buildId.c_str(), header->mBuildIdLength);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800196
197 // Write cache entries
198 uint8_t* byteBuffer = reinterpret_cast<uint8_t*>(buffer);
199 off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
Yiwei Zhang8af03062020-08-12 21:28:15 -0700200 for (const CacheEntry& e : mCacheEntries) {
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800201 std::shared_ptr<Blob> const& keyBlob = e.getKey();
202 std::shared_ptr<Blob> const& valueBlob = e.getValue();
Mathias Agopian5f549b22017-03-08 22:27:13 -0800203 size_t keySize = keyBlob->getSize();
204 size_t valueSize = valueBlob->getSize();
205
206 size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
207 size_t totalSize = align4(entrySize);
208 if (byteOffset + totalSize > size) {
209 ALOGE("flatten: not enough room for cache entries");
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800210 return -EINVAL;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800211 }
212
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800213 EntryHeader* eheader = reinterpret_cast<EntryHeader*>(&byteBuffer[byteOffset]);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800214 eheader->mKeySize = keySize;
215 eheader->mValueSize = valueSize;
216
217 memcpy(eheader->mData, keyBlob->getData(), keySize);
218 memcpy(eheader->mData + keySize, valueBlob->getData(), valueSize);
219
220 if (totalSize > entrySize) {
221 // We have padding bytes. Those will get written to storage, and contribute to the CRC,
222 // so make sure we zero-them to have reproducible results.
223 memset(eheader->mData + keySize + valueSize, 0, totalSize - entrySize);
224 }
225
226 byteOffset += totalSize;
227 }
228
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800229 return 0;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800230}
231
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800232int BlobCache::unflatten(void const* buffer, size_t size) {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800233 // All errors should result in the BlobCache being in an empty state.
234 mCacheEntries.clear();
235
236 // Read the cache header
237 if (size < sizeof(Header)) {
238 ALOGE("unflatten: not enough room for cache header");
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800239 return -EINVAL;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800240 }
241 const Header* header = reinterpret_cast<const Header*>(buffer);
242 if (header->mMagicNumber != blobCacheMagic) {
243 ALOGE("unflatten: bad magic number: %" PRIu32, header->mMagicNumber);
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800244 return -EINVAL;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800245 }
Michael Hoisie4e0f56b2020-04-30 18:40:55 -0400246 auto buildId = base::GetProperty("ro.build.id", "");
Mathias Agopian5f549b22017-03-08 22:27:13 -0800247 if (header->mBlobCacheVersion != blobCacheVersion ||
Michael Hoisie4e0f56b2020-04-30 18:40:55 -0400248 header->mDeviceVersion != blobCacheDeviceVersion ||
249 buildId.size() != header->mBuildIdLength ||
250 strncmp(buildId.c_str(), header->mBuildId, buildId.size())) {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800251 // We treat version mismatches as an empty cache.
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800252 return 0;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800253 }
254
255 // Read cache entries
256 const uint8_t* byteBuffer = reinterpret_cast<const uint8_t*>(buffer);
257 off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
258 size_t numEntries = header->mNumEntries;
259 for (size_t i = 0; i < numEntries; i++) {
260 if (byteOffset + sizeof(EntryHeader) > size) {
261 mCacheEntries.clear();
262 ALOGE("unflatten: not enough room for cache entry headers");
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800263 return -EINVAL;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800264 }
265
Yiwei Zhang8af03062020-08-12 21:28:15 -0700266 const EntryHeader* eheader = reinterpret_cast<const EntryHeader*>(&byteBuffer[byteOffset]);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800267 size_t keySize = eheader->mKeySize;
268 size_t valueSize = eheader->mValueSize;
269 size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
270
271 size_t totalSize = align4(entrySize);
272 if (byteOffset + totalSize > size) {
273 mCacheEntries.clear();
274 ALOGE("unflatten: not enough room for cache entry headers");
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800275 return -EINVAL;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800276 }
277
278 const uint8_t* data = eheader->mData;
279 set(data, keySize, data + keySize, valueSize);
280
281 byteOffset += totalSize;
282 }
283
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800284 return 0;
Mathias Agopian5f549b22017-03-08 22:27:13 -0800285}
286
287long int BlobCache::blob_random() {
288#ifdef _WIN32
289 return rand();
290#else
291 return nrand48(mRandState);
292#endif
293}
294
295void BlobCache::clean() {
296 // Remove a random cache entry until the total cache size gets below half
297 // the maximum total cache size.
298 while (mTotalSize > mMaxTotalSize / 2) {
299 size_t i = size_t(blob_random() % (mCacheEntries.size()));
300 const CacheEntry& entry(mCacheEntries[i]);
301 mTotalSize -= entry.getKey()->getSize() + entry.getValue()->getSize();
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800302 mCacheEntries.erase(mCacheEntries.begin() + i);
Mathias Agopian5f549b22017-03-08 22:27:13 -0800303 }
304}
305
306bool BlobCache::isCleanable() const {
307 return mTotalSize > mMaxTotalSize / 2;
308}
309
Yiwei Zhang8af03062020-08-12 21:28:15 -0700310BlobCache::Blob::Blob(const void* data, size_t size, bool copyData)
311 : mData(copyData ? malloc(size) : data), mSize(size), mOwnsData(copyData) {
Yi Kong48a6cd22018-07-18 10:07:09 -0700312 if (data != nullptr && copyData) {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800313 memcpy(const_cast<void*>(mData), data, size);
314 }
315}
316
317BlobCache::Blob::~Blob() {
318 if (mOwnsData) {
319 free(const_cast<void*>(mData));
320 }
321}
322
323bool BlobCache::Blob::operator<(const Blob& rhs) const {
324 if (mSize == rhs.mSize) {
325 return memcmp(mData, rhs.mData, mSize) < 0;
326 } else {
327 return mSize < rhs.mSize;
328 }
329}
330
331const void* BlobCache::Blob::getData() const {
332 return mData;
333}
334
335size_t BlobCache::Blob::getSize() const {
336 return mSize;
337}
338
Yiwei Zhang8af03062020-08-12 21:28:15 -0700339BlobCache::CacheEntry::CacheEntry() {}
Mathias Agopian5f549b22017-03-08 22:27:13 -0800340
Yiwei Zhang8af03062020-08-12 21:28:15 -0700341BlobCache::CacheEntry::CacheEntry(const std::shared_ptr<Blob>& key,
342 const std::shared_ptr<Blob>& value)
343 : mKey(key), mValue(value) {}
Mathias Agopian5f549b22017-03-08 22:27:13 -0800344
Yiwei Zhang8af03062020-08-12 21:28:15 -0700345BlobCache::CacheEntry::CacheEntry(const CacheEntry& ce) : mKey(ce.mKey), mValue(ce.mValue) {}
Mathias Agopian5f549b22017-03-08 22:27:13 -0800346
347bool BlobCache::CacheEntry::operator<(const CacheEntry& rhs) const {
348 return *mKey < *rhs.mKey;
349}
350
351const BlobCache::CacheEntry& BlobCache::CacheEntry::operator=(const CacheEntry& rhs) {
352 mKey = rhs.mKey;
353 mValue = rhs.mValue;
354 return *this;
355}
356
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800357std::shared_ptr<BlobCache::Blob> BlobCache::CacheEntry::getKey() const {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800358 return mKey;
359}
360
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800361std::shared_ptr<BlobCache::Blob> BlobCache::CacheEntry::getValue() const {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800362 return mValue;
363}
364
Mathias Agopianb7f9a242017-03-08 22:29:31 -0800365void BlobCache::CacheEntry::setValue(const std::shared_ptr<Blob>& value) {
Mathias Agopian5f549b22017-03-08 22:27:13 -0800366 mValue = value;
367}
368
369} // namespace android