BlobCache.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  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. //#define LOG_NDEBUG 0
  17. #include "BlobCache.h"
  18. #include <errno.h>
  19. #include <inttypes.h>
  20. #include <cutils/properties.h>
  21. #include <log/log.h>
  22. #include <chrono>
  23. namespace android {
  24. // BlobCache::Header::mMagicNumber value
  25. static const uint32_t blobCacheMagic = ('_' << 24) + ('B' << 16) + ('b' << 8) + '$';
  26. // BlobCache::Header::mBlobCacheVersion value
  27. static const uint32_t blobCacheVersion = 3;
  28. // BlobCache::Header::mDeviceVersion value
  29. static const uint32_t blobCacheDeviceVersion = 1;
  30. BlobCache::BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize):
  31. mMaxTotalSize(maxTotalSize),
  32. mMaxKeySize(maxKeySize),
  33. mMaxValueSize(maxValueSize),
  34. mTotalSize(0) {
  35. int64_t now = std::chrono::steady_clock::now().time_since_epoch().count();
  36. #ifdef _WIN32
  37. srand(now);
  38. #else
  39. mRandState[0] = (now >> 0) & 0xFFFF;
  40. mRandState[1] = (now >> 16) & 0xFFFF;
  41. mRandState[2] = (now >> 32) & 0xFFFF;
  42. #endif
  43. ALOGV("initializing random seed using %lld", (unsigned long long)now);
  44. }
  45. void BlobCache::set(const void* key, size_t keySize, const void* value,
  46. size_t valueSize) {
  47. if (mMaxKeySize < keySize) {
  48. ALOGV("set: not caching because the key is too large: %zu (limit: %zu)",
  49. keySize, mMaxKeySize);
  50. return;
  51. }
  52. if (mMaxValueSize < valueSize) {
  53. ALOGV("set: not caching because the value is too large: %zu (limit: %zu)",
  54. valueSize, mMaxValueSize);
  55. return;
  56. }
  57. if (mMaxTotalSize < keySize + valueSize) {
  58. ALOGV("set: not caching because the combined key/value size is too "
  59. "large: %zu (limit: %zu)", keySize + valueSize, mMaxTotalSize);
  60. return;
  61. }
  62. if (keySize == 0) {
  63. ALOGW("set: not caching because keySize is 0");
  64. return;
  65. }
  66. if (valueSize <= 0) {
  67. ALOGW("set: not caching because valueSize is 0");
  68. return;
  69. }
  70. std::shared_ptr<Blob> dummyKey(new Blob(key, keySize, false));
  71. CacheEntry dummyEntry(dummyKey, nullptr);
  72. while (true) {
  73. auto index = std::lower_bound(mCacheEntries.begin(), mCacheEntries.end(), dummyEntry);
  74. if (index == mCacheEntries.end() || dummyEntry < *index) {
  75. // Create a new cache entry.
  76. std::shared_ptr<Blob> keyBlob(new Blob(key, keySize, true));
  77. std::shared_ptr<Blob> valueBlob(new Blob(value, valueSize, true));
  78. size_t newTotalSize = mTotalSize + keySize + valueSize;
  79. if (mMaxTotalSize < newTotalSize) {
  80. if (isCleanable()) {
  81. // Clean the cache and try again.
  82. clean();
  83. continue;
  84. } else {
  85. ALOGV("set: not caching new key/value pair because the "
  86. "total cache size limit would be exceeded: %zu "
  87. "(limit: %zu)",
  88. keySize + valueSize, mMaxTotalSize);
  89. break;
  90. }
  91. }
  92. mCacheEntries.insert(index, CacheEntry(keyBlob, valueBlob));
  93. mTotalSize = newTotalSize;
  94. ALOGV("set: created new cache entry with %zu byte key and %zu byte value",
  95. keySize, valueSize);
  96. } else {
  97. // Update the existing cache entry.
  98. std::shared_ptr<Blob> valueBlob(new Blob(value, valueSize, true));
  99. std::shared_ptr<Blob> oldValueBlob(index->getValue());
  100. size_t newTotalSize = mTotalSize + valueSize - oldValueBlob->getSize();
  101. if (mMaxTotalSize < newTotalSize) {
  102. if (isCleanable()) {
  103. // Clean the cache and try again.
  104. clean();
  105. continue;
  106. } else {
  107. ALOGV("set: not caching new value because the total cache "
  108. "size limit would be exceeded: %zu (limit: %zu)",
  109. keySize + valueSize, mMaxTotalSize);
  110. break;
  111. }
  112. }
  113. index->setValue(valueBlob);
  114. mTotalSize = newTotalSize;
  115. ALOGV("set: updated existing cache entry with %zu byte key and %zu byte "
  116. "value", keySize, valueSize);
  117. }
  118. break;
  119. }
  120. }
  121. size_t BlobCache::get(const void* key, size_t keySize, void* value,
  122. size_t valueSize) {
  123. if (mMaxKeySize < keySize) {
  124. ALOGV("get: not searching because the key is too large: %zu (limit %zu)",
  125. keySize, mMaxKeySize);
  126. return 0;
  127. }
  128. std::shared_ptr<Blob> dummyKey(new Blob(key, keySize, false));
  129. CacheEntry dummyEntry(dummyKey, nullptr);
  130. auto index = std::lower_bound(mCacheEntries.begin(), mCacheEntries.end(), dummyEntry);
  131. if (index == mCacheEntries.end() || dummyEntry < *index) {
  132. ALOGV("get: no cache entry found for key of size %zu", keySize);
  133. return 0;
  134. }
  135. // The key was found. Return the value if the caller's buffer is large
  136. // enough.
  137. std::shared_ptr<Blob> valueBlob(index->getValue());
  138. size_t valueBlobSize = valueBlob->getSize();
  139. if (valueBlobSize <= valueSize) {
  140. ALOGV("get: copying %zu bytes to caller's buffer", valueBlobSize);
  141. memcpy(value, valueBlob->getData(), valueBlobSize);
  142. } else {
  143. ALOGV("get: caller's buffer is too small for value: %zu (needs %zu)",
  144. valueSize, valueBlobSize);
  145. }
  146. return valueBlobSize;
  147. }
  148. static inline size_t align4(size_t size) {
  149. return (size + 3) & ~3;
  150. }
  151. size_t BlobCache::getFlattenedSize() const {
  152. size_t size = align4(sizeof(Header) + PROPERTY_VALUE_MAX);
  153. for (const CacheEntry& e : mCacheEntries) {
  154. std::shared_ptr<Blob> const& keyBlob = e.getKey();
  155. std::shared_ptr<Blob> const& valueBlob = e.getValue();
  156. size += align4(sizeof(EntryHeader) + keyBlob->getSize() + valueBlob->getSize());
  157. }
  158. return size;
  159. }
  160. int BlobCache::flatten(void* buffer, size_t size) const {
  161. // Write the cache header
  162. if (size < sizeof(Header)) {
  163. ALOGE("flatten: not enough room for cache header");
  164. return 0;
  165. }
  166. Header* header = reinterpret_cast<Header*>(buffer);
  167. header->mMagicNumber = blobCacheMagic;
  168. header->mBlobCacheVersion = blobCacheVersion;
  169. header->mDeviceVersion = blobCacheDeviceVersion;
  170. header->mNumEntries = mCacheEntries.size();
  171. char buildId[PROPERTY_VALUE_MAX];
  172. header->mBuildIdLength = property_get("ro.build.id", buildId, "");
  173. memcpy(header->mBuildId, buildId, header->mBuildIdLength);
  174. // Write cache entries
  175. uint8_t* byteBuffer = reinterpret_cast<uint8_t*>(buffer);
  176. off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
  177. for (const CacheEntry& e : mCacheEntries) {
  178. std::shared_ptr<Blob> const& keyBlob = e.getKey();
  179. std::shared_ptr<Blob> const& valueBlob = e.getValue();
  180. size_t keySize = keyBlob->getSize();
  181. size_t valueSize = valueBlob->getSize();
  182. size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
  183. size_t totalSize = align4(entrySize);
  184. if (byteOffset + totalSize > size) {
  185. ALOGE("flatten: not enough room for cache entries");
  186. return -EINVAL;
  187. }
  188. EntryHeader* eheader = reinterpret_cast<EntryHeader*>(&byteBuffer[byteOffset]);
  189. eheader->mKeySize = keySize;
  190. eheader->mValueSize = valueSize;
  191. memcpy(eheader->mData, keyBlob->getData(), keySize);
  192. memcpy(eheader->mData + keySize, valueBlob->getData(), valueSize);
  193. if (totalSize > entrySize) {
  194. // We have padding bytes. Those will get written to storage, and contribute to the CRC,
  195. // so make sure we zero-them to have reproducible results.
  196. memset(eheader->mData + keySize + valueSize, 0, totalSize - entrySize);
  197. }
  198. byteOffset += totalSize;
  199. }
  200. return 0;
  201. }
  202. int BlobCache::unflatten(void const* buffer, size_t size) {
  203. // All errors should result in the BlobCache being in an empty state.
  204. mCacheEntries.clear();
  205. // Read the cache header
  206. if (size < sizeof(Header)) {
  207. ALOGE("unflatten: not enough room for cache header");
  208. return -EINVAL;
  209. }
  210. const Header* header = reinterpret_cast<const Header*>(buffer);
  211. if (header->mMagicNumber != blobCacheMagic) {
  212. ALOGE("unflatten: bad magic number: %" PRIu32, header->mMagicNumber);
  213. return -EINVAL;
  214. }
  215. char buildId[PROPERTY_VALUE_MAX];
  216. int len = property_get("ro.build.id", buildId, "");
  217. if (header->mBlobCacheVersion != blobCacheVersion ||
  218. header->mDeviceVersion != blobCacheDeviceVersion ||
  219. len != header->mBuildIdLength ||
  220. strncmp(buildId, header->mBuildId, len)) {
  221. // We treat version mismatches as an empty cache.
  222. return 0;
  223. }
  224. // Read cache entries
  225. const uint8_t* byteBuffer = reinterpret_cast<const uint8_t*>(buffer);
  226. off_t byteOffset = align4(sizeof(Header) + header->mBuildIdLength);
  227. size_t numEntries = header->mNumEntries;
  228. for (size_t i = 0; i < numEntries; i++) {
  229. if (byteOffset + sizeof(EntryHeader) > size) {
  230. mCacheEntries.clear();
  231. ALOGE("unflatten: not enough room for cache entry headers");
  232. return -EINVAL;
  233. }
  234. const EntryHeader* eheader = reinterpret_cast<const EntryHeader*>(
  235. &byteBuffer[byteOffset]);
  236. size_t keySize = eheader->mKeySize;
  237. size_t valueSize = eheader->mValueSize;
  238. size_t entrySize = sizeof(EntryHeader) + keySize + valueSize;
  239. size_t totalSize = align4(entrySize);
  240. if (byteOffset + totalSize > size) {
  241. mCacheEntries.clear();
  242. ALOGE("unflatten: not enough room for cache entry headers");
  243. return -EINVAL;
  244. }
  245. const uint8_t* data = eheader->mData;
  246. set(data, keySize, data + keySize, valueSize);
  247. byteOffset += totalSize;
  248. }
  249. return 0;
  250. }
  251. long int BlobCache::blob_random() {
  252. #ifdef _WIN32
  253. return rand();
  254. #else
  255. return nrand48(mRandState);
  256. #endif
  257. }
  258. void BlobCache::clean() {
  259. // Remove a random cache entry until the total cache size gets below half
  260. // the maximum total cache size.
  261. while (mTotalSize > mMaxTotalSize / 2) {
  262. size_t i = size_t(blob_random() % (mCacheEntries.size()));
  263. const CacheEntry& entry(mCacheEntries[i]);
  264. mTotalSize -= entry.getKey()->getSize() + entry.getValue()->getSize();
  265. mCacheEntries.erase(mCacheEntries.begin() + i);
  266. }
  267. }
  268. bool BlobCache::isCleanable() const {
  269. return mTotalSize > mMaxTotalSize / 2;
  270. }
  271. BlobCache::Blob::Blob(const void* data, size_t size, bool copyData) :
  272. mData(copyData ? malloc(size) : data),
  273. mSize(size),
  274. mOwnsData(copyData) {
  275. if (data != nullptr && copyData) {
  276. memcpy(const_cast<void*>(mData), data, size);
  277. }
  278. }
  279. BlobCache::Blob::~Blob() {
  280. if (mOwnsData) {
  281. free(const_cast<void*>(mData));
  282. }
  283. }
  284. bool BlobCache::Blob::operator<(const Blob& rhs) const {
  285. if (mSize == rhs.mSize) {
  286. return memcmp(mData, rhs.mData, mSize) < 0;
  287. } else {
  288. return mSize < rhs.mSize;
  289. }
  290. }
  291. const void* BlobCache::Blob::getData() const {
  292. return mData;
  293. }
  294. size_t BlobCache::Blob::getSize() const {
  295. return mSize;
  296. }
  297. BlobCache::CacheEntry::CacheEntry() {
  298. }
  299. BlobCache::CacheEntry::CacheEntry(
  300. const std::shared_ptr<Blob>& key, const std::shared_ptr<Blob>& value):
  301. mKey(key),
  302. mValue(value) {
  303. }
  304. BlobCache::CacheEntry::CacheEntry(const CacheEntry& ce):
  305. mKey(ce.mKey),
  306. mValue(ce.mValue) {
  307. }
  308. bool BlobCache::CacheEntry::operator<(const CacheEntry& rhs) const {
  309. return *mKey < *rhs.mKey;
  310. }
  311. const BlobCache::CacheEntry& BlobCache::CacheEntry::operator=(const CacheEntry& rhs) {
  312. mKey = rhs.mKey;
  313. mValue = rhs.mValue;
  314. return *this;
  315. }
  316. std::shared_ptr<BlobCache::Blob> BlobCache::CacheEntry::getKey() const {
  317. return mKey;
  318. }
  319. std::shared_ptr<BlobCache::Blob> BlobCache::CacheEntry::getValue() const {
  320. return mValue;
  321. }
  322. void BlobCache::CacheEntry::setValue(const std::shared_ptr<Blob>& value) {
  323. mValue = value;
  324. }
  325. } // namespace android