MMKV.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  1. /*
  2. * Tencent is pleased to support the open source community by making
  3. * MMKV available.
  4. *
  5. * Copyright (C) 2018 THL A29 Limited, a Tencent company.
  6. * All rights reserved.
  7. *
  8. * Licensed under the BSD 3-Clause License (the "License"); you may not use
  9. * this file except in compliance with the License. You may obtain a copy of
  10. * the License at
  11. *
  12. * https://opensource.org/licenses/BSD-3-Clause
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #include "CodedInputData.h"
  21. #include "CodedOutputData.h"
  22. #include "InterProcessLock.h"
  23. #include "KeyValueHolder.h"
  24. #include "MMBuffer.h"
  25. #include "MMKVLog.h"
  26. #include "MMKVMetaInfo.hpp"
  27. #include "MMKV_IO.h"
  28. #include "MMKV_OSX.h"
  29. #include "MemoryFile.h"
  30. #include "MiniPBCoder.h"
  31. #include "PBUtility.h"
  32. #include "ScopedLock.hpp"
  33. #include "ThreadLock.h"
  34. #include "aes/AESCrypt.h"
  35. #include "aes/openssl/openssl_aes.h"
  36. #include "aes/openssl/openssl_md5.h"
  37. #include "crc32/Checksum.h"
  38. #include <algorithm>
  39. #include <cstdio>
  40. #include <cstring>
  41. #include <unordered_set>
  42. #include <cassert>
  43. #if defined(__aarch64__) && defined(__linux__) && !defined (MMKV_OHOS)
  44. # include <asm/hwcap.h>
  45. # include <sys/auxv.h>
  46. #endif
  47. #ifdef MMKV_APPLE
  48. # if __has_feature(objc_arc)
  49. # error This file must be compiled with MRC. Use -fno-objc-arc flag.
  50. # endif
  51. # include "MMKV_OSX.h"
  52. #endif // MMKV_APPLE
  53. using namespace std;
  54. using namespace mmkv;
  55. unordered_map<string, MMKV *> *g_instanceDic;
  56. ThreadLock *g_instanceLock;
  57. MMKVPath_t g_rootDir;
  58. MMKVPath_t g_realRootDir;
  59. static ThreadLock *g_namespaceLock;
  60. static unordered_map<MMKVPath_t, MMKVPath_t> g_realRootMap;
  61. static mmkv::ErrorHandler g_errorHandler;
  62. size_t mmkv::DEFAULT_MMAP_SIZE;
  63. #ifndef MMKV_WIN32
  64. constexpr auto SPECIAL_CHARACTER_DIRECTORY_NAME = "specialCharacter";
  65. constexpr auto CRC_SUFFIX = ".crc";
  66. #else
  67. constexpr auto SPECIAL_CHARACTER_DIRECTORY_NAME = L"specialCharacter";
  68. constexpr auto CRC_SUFFIX = L".crc";
  69. #endif
  70. MMKV_NAMESPACE_BEGIN
  71. static MMKVPath_t encodeFilePath(const string &mmapID, const MMKVPath_t &rootDir);
  72. bool endsWith(const MMKVPath_t &str, const MMKVPath_t &suffix);
  73. MMKVPath_t filename(const MMKVPath_t &path);
  74. #ifndef MMKV_ANDROID
  75. MMKV::MMKV(const string &mmapID, MMKVMode mode, const string *cryptKey, const MMKVPath_t *rootPath, size_t expectedCapacity)
  76. : m_mmapID(mmapID)
  77. , m_mode(mode)
  78. , m_path(mappedKVPathWithID(m_mmapID, rootPath))
  79. , m_crcPath(crcPathWithPath(m_path))
  80. , m_dic(nullptr)
  81. , m_dicCrypt(nullptr)
  82. , m_expectedCapacity(std::max<size_t>(DEFAULT_MMAP_SIZE, roundUp<size_t>(expectedCapacity, DEFAULT_MMAP_SIZE)))
  83. , m_file(new MemoryFile(m_path, m_expectedCapacity, isReadOnly(), true))
  84. , m_metaFile(new MemoryFile(m_crcPath, 0, isReadOnly(), !isMultiProcess()))
  85. , m_metaInfo(new MMKVMetaInfo())
  86. , m_crypter(nullptr)
  87. , m_lock(new ThreadLock())
  88. , m_fileLock(new FileLock(isMultiProcess() ? m_metaFile->getFd() : MMKVFileHandleInvalidValue))
  89. , m_sharedProcessLock(new InterProcessLock(m_fileLock, SharedLockType))
  90. , m_exclusiveProcessLock(new InterProcessLock(m_fileLock, ExclusiveLockType))
  91. {
  92. m_actualSize = 0;
  93. m_output = nullptr;
  94. # ifndef MMKV_DISABLE_CRYPT
  95. if (cryptKey && !cryptKey->empty()) {
  96. m_dicCrypt = new MMKVMapCrypt();
  97. m_crypter = new AESCrypt(cryptKey->data(), cryptKey->length());
  98. } else {
  99. m_dic = new MMKVMap();
  100. }
  101. # else
  102. m_dic = new MMKVMap();
  103. # endif
  104. m_needLoadFromFile = true;
  105. m_hasFullWriteback = false;
  106. m_crcDigest = 0;
  107. m_lock->initialize();
  108. m_sharedProcessLock->m_enable = isMultiProcess();
  109. m_exclusiveProcessLock->m_enable = isMultiProcess();
  110. // sensitive zone
  111. /*{
  112. SCOPED_LOCK(m_sharedProcessLock);
  113. loadFromFile();
  114. }*/
  115. }
  116. #endif
  117. MMKV::~MMKV() {
  118. clearMemoryCache();
  119. delete m_dic;
  120. #ifndef MMKV_DISABLE_CRYPT
  121. delete m_dicCrypt;
  122. delete m_crypter;
  123. #endif
  124. delete m_metaInfo;
  125. delete m_lock;
  126. delete m_fileLock;
  127. delete m_sharedProcessLock;
  128. delete m_exclusiveProcessLock;
  129. #ifdef MMKV_ANDROID
  130. #ifndef MMKV_OHOS
  131. delete m_sharedProcessModeLock;
  132. delete m_exclusiveProcessModeLock;
  133. delete m_fileModeLock;
  134. #endif // !MMKV_OHOS
  135. delete m_sharedMigrationLock;
  136. delete m_fileMigrationLock;
  137. #endif // MMKV_ANDROID
  138. delete m_metaFile;
  139. delete m_file;
  140. MMKVInfo("destruct [%s]", m_mmapID.c_str());
  141. }
  142. MMKV *MMKV::defaultMMKV(MMKVMode mode, const string *cryptKey) {
  143. #ifndef MMKV_ANDROID
  144. return mmkvWithID(DEFAULT_MMAP_ID, mode, cryptKey);
  145. #else
  146. return mmkvWithID(DEFAULT_MMAP_ID, DEFAULT_MMAP_SIZE, mode, cryptKey);
  147. #endif
  148. }
  149. static void initialize() {
  150. g_instanceDic = new unordered_map<string, MMKV *>;
  151. g_instanceLock = new ThreadLock();
  152. g_instanceLock->initialize();
  153. mmkv::DEFAULT_MMAP_SIZE = mmkv::getPageSize();
  154. MMKVInfo("version %s, page size %d, arch %s", MMKV_VERSION, DEFAULT_MMAP_SIZE, MMKV_ABI);
  155. // get CPU status of ARMv8 extensions (CRC32, AES)
  156. #if defined(__aarch64__) && defined(__linux__) && !defined (MMKV_OHOS)
  157. auto hwcaps = getauxval(AT_HWCAP);
  158. # ifndef MMKV_DISABLE_CRYPT
  159. if (hwcaps & HWCAP_AES) {
  160. openssl::AES_set_encrypt_key = openssl_aes_arm_set_encrypt_key;
  161. openssl::AES_set_decrypt_key = openssl_aes_arm_set_decrypt_key;
  162. openssl::AES_encrypt = openssl_aes_arm_encrypt;
  163. openssl::AES_decrypt = openssl_aes_arm_decrypt;
  164. MMKVInfo("armv8 AES instructions is supported");
  165. } else {
  166. MMKVInfo("armv8 AES instructions is not supported");
  167. }
  168. # endif // MMKV_DISABLE_CRYPT
  169. # ifdef MMKV_USE_ARMV8_CRC32
  170. if (hwcaps & HWCAP_CRC32) {
  171. CRC32 = mmkv::armv8_crc32;
  172. MMKVInfo("armv8 CRC32 instructions is supported");
  173. } else {
  174. MMKVInfo("armv8 CRC32 instructions is not supported");
  175. }
  176. # endif // MMKV_USE_ARMV8_CRC32
  177. #endif // __aarch64__ && defined(__linux__) && !defined (MMKV_OHOS)
  178. #if defined(MMKV_DEBUG) && !defined(MMKV_DISABLE_CRYPT)
  179. // AESCrypt::testAESCrypt();
  180. // KeyValueHolderCrypt::testAESToMMBuffer();
  181. #endif
  182. }
  183. static void ensureMinimalInitialize() {
  184. static ThreadOnceToken_t once_control = ThreadOnceUninitialized;
  185. ThreadLock::ThreadOnce(&once_control, initialize);
  186. }
  187. void MMKV::initializeMMKV(const MMKVPath_t &rootDir, MMKVLogLevel logLevel, mmkv::LogHandler handler) {
  188. g_currentLogLevel = logLevel;
  189. g_logHandler = handler;
  190. ensureMinimalInitialize();
  191. #ifdef MMKV_APPLE
  192. // crc32 instruction requires A10 chip, aka iPhone 7 or iPad 6th generation
  193. int device = 0, version = 0;
  194. GetAppleMachineInfo(device, version);
  195. MMKVInfo("Apple Device: %d, version: %d", device, version);
  196. #endif
  197. if (g_rootDir.empty()) {
  198. g_rootDir = rootDir;
  199. // avoid operating g_realRootMap directly
  200. g_realRootDir = nameSpace(rootDir).getRootDir();
  201. mkPath(g_realRootDir);
  202. }
  203. MMKVInfo("root dir: " MMKV_PATH_FORMAT, g_realRootDir.c_str());
  204. }
  205. const MMKVPath_t &MMKV::getRootDir() {
  206. // for backword consistency we can't return g_realRootDir
  207. return g_rootDir;
  208. }
  209. #ifndef MMKV_ANDROID
  210. MMKV *MMKV::mmkvWithID(const string &mmapID, MMKVMode mode, const string *cryptKey, const MMKVPath_t *rootPath, size_t expectedCapacity) {
  211. if (mmapID.empty() || !g_instanceLock) {
  212. return nullptr;
  213. }
  214. SCOPED_LOCK(g_instanceLock);
  215. auto mmapKey = mmapedKVKey(mmapID, rootPath);
  216. auto itr = g_instanceDic->find(mmapKey);
  217. if (itr != g_instanceDic->end()) {
  218. MMKV *kv = itr->second;
  219. return kv;
  220. }
  221. if (rootPath && !(mode & MMKV_READ_ONLY)) {
  222. MMKVPath_t specialPath = (*rootPath) + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  223. if (!isFileExist(specialPath)) {
  224. mkPath(specialPath);
  225. }
  226. }
  227. auto theRootDir = rootPath ? rootPath : &g_realRootDir;
  228. #ifdef MMKV_WIN32
  229. MMKVInfo("prepare to load %s (id %s) from rootPath %ls", mmapID.c_str(), mmapKey.c_str(), theRootDir->c_str());
  230. #else
  231. MMKVInfo("prepare to load %s (id %s) from rootPath %s", mmapID.c_str(), mmapKey.c_str(), theRootDir->c_str());
  232. #endif
  233. auto kv = new MMKV(mmapID, mode, cryptKey, rootPath, expectedCapacity);
  234. kv->m_mmapKey = mmapKey;
  235. (*g_instanceDic)[mmapKey] = kv;
  236. return kv;
  237. }
  238. #endif
  239. void MMKV::onExit() {
  240. if (!g_instanceLock) {
  241. return;
  242. }
  243. SCOPED_LOCK(g_instanceLock);
  244. for (auto &pair : *g_instanceDic) {
  245. MMKV *kv = pair.second;
  246. kv->sync();
  247. kv->clearMemoryCache();
  248. delete kv;
  249. pair.second = nullptr;
  250. }
  251. delete g_instanceDic;
  252. g_instanceDic = nullptr;
  253. }
  254. const string &MMKV::mmapID() const {
  255. return m_mmapID;
  256. }
  257. mmkv::ContentChangeHandler g_contentChangeHandler = nullptr;
  258. void MMKV::notifyContentChanged() {
  259. if (g_contentChangeHandler) {
  260. g_contentChangeHandler(m_mmapID);
  261. }
  262. }
  263. void MMKV::checkContentChanged() {
  264. SCOPED_LOCK(m_lock);
  265. checkLoadData();
  266. }
  267. void MMKV::registerContentChangeHandler(mmkv::ContentChangeHandler handler) {
  268. g_contentChangeHandler = handler;
  269. }
  270. void MMKV::unRegisterContentChangeHandler() {
  271. g_contentChangeHandler = nullptr;
  272. }
  273. void MMKV::clearMemoryCache(bool keepSpace) {
  274. SCOPED_LOCK(m_lock);
  275. if (m_needLoadFromFile) {
  276. return;
  277. }
  278. MMKVInfo("clearMemoryCache [%s]", m_mmapID.c_str());
  279. m_needLoadFromFile = true;
  280. m_hasFullWriteback = false;
  281. clearDictionary(m_dic);
  282. #ifndef MMKV_DISABLE_CRYPT
  283. clearDictionary(m_dicCrypt);
  284. if (m_crypter) {
  285. if (m_metaInfo->m_version >= MMKVVersionRandomIV) {
  286. m_crypter->resetIV(m_metaInfo->m_vector, sizeof(m_metaInfo->m_vector));
  287. } else {
  288. m_crypter->resetIV();
  289. }
  290. }
  291. #endif
  292. delete m_output;
  293. m_output = nullptr;
  294. if (!keepSpace) {
  295. m_file->clearMemoryCache();
  296. }
  297. // inter-process lock rely on MetaFile's fd, never close it
  298. // m_metaFile->clearMemoryCache();
  299. m_actualSize = 0;
  300. m_metaInfo->m_crcDigest = 0;
  301. }
  302. void MMKV::close() {
  303. MMKVInfo("close [%s]", m_mmapID.c_str());
  304. SCOPED_LOCK(g_instanceLock);
  305. m_lock->lock();
  306. auto itr = g_instanceDic->find(m_mmapKey);
  307. if (itr != g_instanceDic->end()) {
  308. g_instanceDic->erase(itr);
  309. }
  310. delete this;
  311. }
  312. #ifndef MMKV_DISABLE_CRYPT
  313. string MMKV::cryptKey() const {
  314. SCOPED_LOCK(m_lock);
  315. if (m_crypter) {
  316. char key[AES_KEY_LEN];
  317. m_crypter->getKey(key);
  318. return {key, strnlen(key, AES_KEY_LEN)};
  319. }
  320. return "";
  321. }
  322. void MMKV::checkReSetCryptKey(const string *cryptKey) {
  323. SCOPED_LOCK(m_lock);
  324. if (m_crypter) {
  325. if (cryptKey && !cryptKey->empty()) {
  326. string oldKey = this->cryptKey();
  327. if (oldKey != *cryptKey) {
  328. MMKVInfo("setting new aes key");
  329. delete m_crypter;
  330. auto ptr = cryptKey->data();
  331. m_crypter = new AESCrypt(ptr, cryptKey->length());
  332. checkLoadData();
  333. } else {
  334. // nothing to do
  335. }
  336. } else {
  337. MMKVInfo("reset aes key");
  338. delete m_crypter;
  339. m_crypter = nullptr;
  340. checkLoadData();
  341. }
  342. } else {
  343. if (cryptKey && !cryptKey->empty()) {
  344. MMKVInfo("setting new aes key");
  345. auto ptr = cryptKey->data();
  346. m_crypter = new AESCrypt(ptr, cryptKey->length());
  347. checkLoadData();
  348. } else {
  349. // nothing to do
  350. }
  351. }
  352. }
  353. #endif // MMKV_DISABLE_CRYPT
  354. bool MMKV::isFileValid() {
  355. return m_file->isFileValid();
  356. }
  357. // crc
  358. // assuming m_file is valid
  359. bool MMKV::checkFileCRCValid(size_t actualSize, uint32_t crcDigest) {
  360. auto ptr = (uint8_t *) m_file->getMemory();
  361. if (ptr) {
  362. m_crcDigest = (uint32_t) CRC32(0, (const uint8_t *) ptr + Fixed32Size, (uint32_t) actualSize);
  363. if (m_crcDigest == crcDigest) {
  364. return true;
  365. }
  366. MMKVError("check crc [%s] fail, crc32:%u, m_crcDigest:%u", m_mmapID.c_str(), crcDigest, m_crcDigest);
  367. }
  368. return false;
  369. }
  370. void MMKV::recalculateCRCDigestWithIV(const void *iv) {
  371. auto ptr = (const uint8_t *) m_file->getMemory();
  372. if (ptr) {
  373. m_crcDigest = 0;
  374. m_crcDigest = (uint32_t) CRC32(0, ptr + Fixed32Size, (uint32_t) m_actualSize);
  375. writeActualSize(m_actualSize, m_crcDigest, iv, IncreaseSequence);
  376. }
  377. }
  378. void MMKV::recalculateCRCDigestOnly() {
  379. auto ptr = (const uint8_t *) m_file->getMemory();
  380. if (ptr) {
  381. m_crcDigest = 0;
  382. m_crcDigest = (uint32_t) CRC32(0, ptr + Fixed32Size, (uint32_t) m_actualSize);
  383. writeActualSize(m_actualSize, m_crcDigest, nullptr, KeepSequence);
  384. }
  385. }
  386. void MMKV::updateCRCDigest(const uint8_t *ptr, size_t length) {
  387. if (ptr == nullptr) {
  388. return;
  389. }
  390. m_crcDigest = (uint32_t) CRC32(m_crcDigest, ptr, (uint32_t) length);
  391. writeActualSize(m_actualSize, m_crcDigest, nullptr, KeepSequence);
  392. }
  393. // set & get
  394. bool MMKV::set(bool value, MMKVKey_t key) {
  395. return set(value, key, m_expiredInSeconds);
  396. }
  397. bool MMKV::set(bool value, MMKVKey_t key, uint32_t expireDuration) {
  398. if (isKeyEmpty(key)) {
  399. return false;
  400. }
  401. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbBoolSize() : pbBoolSize();
  402. MMBuffer data(size);
  403. CodedOutputData output(data.getPtr(), size);
  404. output.writeBool(value);
  405. if (mmkv_unlikely(m_enableKeyExpire)) {
  406. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  407. output.writeRawLittleEndian32(UInt32ToInt32(time));
  408. } else {
  409. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  410. }
  411. return setDataForKey(std::move(data), key);
  412. }
  413. bool MMKV::set(int32_t value, MMKVKey_t key) {
  414. return set(value, key, m_expiredInSeconds);
  415. }
  416. bool MMKV::set(int32_t value, MMKVKey_t key, uint32_t expireDuration) {
  417. if (isKeyEmpty(key)) {
  418. return false;
  419. }
  420. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbInt32Size(value) : pbInt32Size(value);
  421. MMBuffer data(size);
  422. CodedOutputData output(data.getPtr(), size);
  423. output.writeInt32(value);
  424. if (mmkv_unlikely(m_enableKeyExpire)) {
  425. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  426. output.writeRawLittleEndian32(UInt32ToInt32(time));
  427. } else {
  428. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  429. }
  430. return setDataForKey(std::move(data), key);
  431. }
  432. bool MMKV::set(uint32_t value, MMKVKey_t key) {
  433. return set(value, key, m_expiredInSeconds);
  434. }
  435. bool MMKV::set(uint32_t value, MMKVKey_t key, uint32_t expireDuration) {
  436. if (isKeyEmpty(key)) {
  437. return false;
  438. }
  439. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbUInt32Size(value) : pbUInt32Size(value);
  440. MMBuffer data(size);
  441. CodedOutputData output(data.getPtr(), size);
  442. output.writeUInt32(value);
  443. if (mmkv_unlikely(m_enableKeyExpire)) {
  444. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  445. output.writeRawLittleEndian32(UInt32ToInt32(time));
  446. } else {
  447. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  448. }
  449. return setDataForKey(std::move(data), key);
  450. }
  451. bool MMKV::set(int64_t value, MMKVKey_t key) {
  452. return set(value, key, m_expiredInSeconds);
  453. }
  454. bool MMKV::set(int64_t value, MMKVKey_t key, uint32_t expireDuration) {
  455. if (isKeyEmpty(key)) {
  456. return false;
  457. }
  458. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbInt64Size(value) : pbInt64Size(value);
  459. MMBuffer data(size);
  460. CodedOutputData output(data.getPtr(), size);
  461. output.writeInt64(value);
  462. if (mmkv_unlikely(m_enableKeyExpire)) {
  463. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  464. output.writeRawLittleEndian32(UInt32ToInt32(time));
  465. } else {
  466. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  467. }
  468. return setDataForKey(std::move(data), key);
  469. }
  470. bool MMKV::set(uint64_t value, MMKVKey_t key) {
  471. return set(value, key, m_expiredInSeconds);
  472. }
  473. bool MMKV::set(uint64_t value, MMKVKey_t key, uint32_t expireDuration) {
  474. if (isKeyEmpty(key)) {
  475. return false;
  476. }
  477. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbUInt64Size(value) : pbUInt64Size(value);
  478. MMBuffer data(size);
  479. CodedOutputData output(data.getPtr(), size);
  480. output.writeUInt64(value);
  481. if (mmkv_unlikely(m_enableKeyExpire)) {
  482. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  483. output.writeRawLittleEndian32(UInt32ToInt32(time));
  484. } else {
  485. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  486. }
  487. return setDataForKey(std::move(data), key);
  488. }
  489. bool MMKV::set(float value, MMKVKey_t key) {
  490. return set(value, key, m_expiredInSeconds);
  491. }
  492. bool MMKV::set(float value, MMKVKey_t key, uint32_t expireDuration) {
  493. if (isKeyEmpty(key)) {
  494. return false;
  495. }
  496. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbFloatSize() : pbFloatSize();
  497. MMBuffer data(size);
  498. CodedOutputData output(data.getPtr(), size);
  499. output.writeFloat(value);
  500. if (mmkv_unlikely(m_enableKeyExpire)) {
  501. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  502. output.writeRawLittleEndian32(UInt32ToInt32(time));
  503. } else {
  504. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  505. }
  506. return setDataForKey(std::move(data), key);
  507. }
  508. bool MMKV::set(double value, MMKVKey_t key) {
  509. return set(value, key, m_expiredInSeconds);
  510. }
  511. bool MMKV::set(double value, MMKVKey_t key, uint32_t expireDuration) {
  512. if (isKeyEmpty(key)) {
  513. return false;
  514. }
  515. size_t size = mmkv_unlikely(m_enableKeyExpire) ? Fixed32Size + pbDoubleSize() : pbDoubleSize();
  516. MMBuffer data(size);
  517. CodedOutputData output(data.getPtr(), size);
  518. output.writeDouble(value);
  519. if (mmkv_unlikely(m_enableKeyExpire)) {
  520. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  521. output.writeRawLittleEndian32(UInt32ToInt32(time));
  522. } else {
  523. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  524. }
  525. return setDataForKey(std::move(data), key);
  526. }
  527. bool MMKV::setDataForKey(mmkv::MMBuffer &&data, MMKV::MMKVKey_t key, uint32_t expireDuration) {
  528. if (mmkv_likely(!m_enableKeyExpire)) {
  529. assert(expireDuration == ExpireNever && "setting expire duration without calling enableAutoKeyExpire() first");
  530. return setDataForKey(std::move(data), key, true);
  531. } else {
  532. auto tmp = MMBuffer(pbMMBufferSize(data) + Fixed32Size);
  533. CodedOutputData output(tmp.getPtr(), tmp.length());
  534. output.writeData(data);
  535. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  536. output.writeRawLittleEndian32(UInt32ToInt32(time));
  537. return setDataForKey(std::move(tmp), key);
  538. }
  539. }
  540. bool MMKV::set(const char *value, MMKVKey_t key) {
  541. return set(value, key, m_expiredInSeconds);
  542. }
  543. bool MMKV::set(const char *value, MMKVKey_t key, uint32_t expireDuration) {
  544. if (!value) {
  545. removeValueForKey(key);
  546. return true;
  547. }
  548. return setDataForKey(MMBuffer((void *) value, strlen(value), MMBufferNoCopy), key, expireDuration);
  549. }
  550. bool MMKV::set(const string &value, MMKVKey_t key) {
  551. return set(value, key, m_expiredInSeconds);
  552. }
  553. bool MMKV::set(const string &value, MMKVKey_t key, uint32_t expireDuration) {
  554. if (isKeyEmpty(key)) {
  555. return false;
  556. }
  557. return setDataForKey(MMBuffer((void *) value.data(), value.length(), MMBufferNoCopy), key, expireDuration);
  558. }
  559. bool MMKV::set(string_view value, MMKVKey_t key) {
  560. return set(value, key, m_expiredInSeconds);
  561. }
  562. bool MMKV::set(string_view value, MMKVKey_t key, uint32_t expireDuration) {
  563. if (isKeyEmpty(key)) {
  564. return false;
  565. }
  566. return setDataForKey(MMBuffer((void *) value.data(), value.length(), MMBufferNoCopy), key, expireDuration);
  567. }
  568. bool MMKV::set(const MMBuffer &value, MMKVKey_t key) {
  569. return set(value, key, m_expiredInSeconds);
  570. }
  571. bool MMKV::set(const MMBuffer &value, MMKVKey_t key, uint32_t expireDuration) {
  572. if (isKeyEmpty(key)) {
  573. return false;
  574. }
  575. return setDataForKey(MMBuffer(value.getPtr(), value.length(), MMBufferNoCopy), key, expireDuration);
  576. }
  577. bool MMKV::set(const vector<string> &value, MMKVKey_t key) {
  578. return set(value, key, m_expiredInSeconds);
  579. }
  580. bool MMKV::set(const vector<string> &v, MMKVKey_t key, uint32_t expireDuration) {
  581. if (isKeyEmpty(key)) {
  582. return false;
  583. }
  584. #ifdef MMKV_HAS_CPP20
  585. auto data = MiniPBCoder::encodeDataWithObject(std::span(v));
  586. #else
  587. auto data = MiniPBCoder::encodeDataWithObject(v);
  588. #endif
  589. if (mmkv_unlikely(m_enableKeyExpire) && data.length() > 0) {
  590. auto tmp = MMBuffer(data.length() + Fixed32Size);
  591. auto ptr = (uint8_t *) tmp.getPtr();
  592. memcpy(ptr, data.getPtr(), data.length());
  593. auto time = (expireDuration != ExpireNever) ? getCurrentTimeInSecond() + expireDuration : ExpireNever;
  594. memcpy(ptr + data.length(), &time, Fixed32Size);
  595. data = std::move(tmp);
  596. }
  597. return setDataForKey(std::move(data), key);
  598. }
  599. bool MMKV::getString(MMKVKey_t key, string &result, bool inplaceModification) {
  600. if (isKeyEmpty(key)) {
  601. return false;
  602. }
  603. SCOPED_LOCK(m_lock);
  604. SCOPED_LOCK(m_sharedProcessLock);
  605. auto data = getDataForKey(key);
  606. if (data.length() > 0) {
  607. try {
  608. CodedInputData input(data.getPtr(), data.length());
  609. if (inplaceModification) {
  610. input.readString(result);
  611. } else {
  612. result = input.readString();
  613. }
  614. return true;
  615. } catch (std::exception &exception) {
  616. MMKVError("%s", exception.what());
  617. } catch (...) {
  618. MMKVError("decode fail");
  619. }
  620. }
  621. return false;
  622. }
  623. bool MMKV::getBytes(MMKVKey_t key, mmkv::MMBuffer &result) {
  624. if (isKeyEmpty(key)) {
  625. return false;
  626. }
  627. SCOPED_LOCK(m_lock);
  628. SCOPED_LOCK(m_sharedProcessLock);
  629. auto data = getDataForKey(key);
  630. if (data.length() > 0) {
  631. try {
  632. CodedInputData input(data.getPtr(), data.length());
  633. result = input.readData();
  634. return true;
  635. } catch (std::exception &exception) {
  636. MMKVError("%s", exception.what());
  637. } catch (...) {
  638. MMKVError("decode fail");
  639. }
  640. }
  641. return false;
  642. }
  643. MMBuffer MMKV::getBytes(MMKVKey_t key) {
  644. if (isKeyEmpty(key)) {
  645. return MMBuffer();
  646. }
  647. SCOPED_LOCK(m_lock);
  648. SCOPED_LOCK(m_sharedProcessLock);
  649. auto data = getDataForKey(key);
  650. if (data.length() > 0) {
  651. try {
  652. CodedInputData input(data.getPtr(), data.length());
  653. return input.readData();
  654. } catch (std::exception &exception) {
  655. MMKVError("%s", exception.what());
  656. } catch (...) {
  657. MMKVError("decode fail");
  658. }
  659. }
  660. return MMBuffer();
  661. }
  662. bool MMKV::getVector(MMKVKey_t key, vector<string> &result) {
  663. if (isKeyEmpty(key)) {
  664. return false;
  665. }
  666. SCOPED_LOCK(m_lock);
  667. SCOPED_LOCK(m_sharedProcessLock);
  668. auto data = getDataForKey(key);
  669. if (data.length() > 0) {
  670. try {
  671. result = MiniPBCoder::decodeVector(data);
  672. return true;
  673. } catch (std::exception &exception) {
  674. MMKVError("%s", exception.what());
  675. } catch (...) {
  676. MMKVError("decode fail");
  677. }
  678. }
  679. return false;
  680. }
  681. void MMKV::shared_lock() {
  682. m_lock->lock();
  683. m_sharedProcessLock->lock();
  684. }
  685. void MMKV::shared_unlock() {
  686. m_sharedProcessLock->unlock();
  687. m_lock->unlock();
  688. }
  689. bool MMKV::getBool(MMKVKey_t key, bool defaultValue, bool *hasValue) {
  690. if (isKeyEmpty(key)) {
  691. if (hasValue != nullptr) {
  692. *hasValue = false;
  693. }
  694. return defaultValue;
  695. }
  696. SCOPED_LOCK(m_lock);
  697. SCOPED_LOCK(m_sharedProcessLock);
  698. auto data = getDataForKey(key);
  699. if (data.length() > 0) {
  700. try {
  701. CodedInputData input(data.getPtr(), data.length());
  702. if (hasValue != nullptr) {
  703. *hasValue = true;
  704. }
  705. return input.readBool();
  706. } catch (std::exception &exception) {
  707. MMKVError("%s", exception.what());
  708. } catch (...) {
  709. MMKVError("decode fail");
  710. }
  711. }
  712. if (hasValue != nullptr) {
  713. *hasValue = false;
  714. }
  715. return defaultValue;
  716. }
  717. int32_t MMKV::getInt32(MMKVKey_t key, int32_t defaultValue, bool *hasValue) {
  718. if (isKeyEmpty(key)) {
  719. if (hasValue != nullptr) {
  720. *hasValue = false;
  721. }
  722. return defaultValue;
  723. }
  724. SCOPED_LOCK(m_lock);
  725. SCOPED_LOCK(m_sharedProcessLock);
  726. auto data = getDataForKey(key);
  727. if (data.length() > 0) {
  728. try {
  729. CodedInputData input(data.getPtr(), data.length());
  730. if (hasValue != nullptr) {
  731. *hasValue = true;
  732. }
  733. return input.readInt32();
  734. } catch (std::exception &exception) {
  735. MMKVError("%s", exception.what());
  736. } catch (...) {
  737. MMKVError("decode fail");
  738. }
  739. }
  740. if (hasValue != nullptr) {
  741. *hasValue = false;
  742. }
  743. return defaultValue;
  744. }
  745. uint32_t MMKV::getUInt32(MMKVKey_t key, uint32_t defaultValue, bool *hasValue) {
  746. if (isKeyEmpty(key)) {
  747. if (hasValue != nullptr) {
  748. *hasValue = false;
  749. }
  750. return defaultValue;
  751. }
  752. SCOPED_LOCK(m_lock);
  753. SCOPED_LOCK(m_sharedProcessLock);
  754. auto data = getDataForKey(key);
  755. if (data.length() > 0) {
  756. try {
  757. CodedInputData input(data.getPtr(), data.length());
  758. if (hasValue != nullptr) {
  759. *hasValue = true;
  760. }
  761. return input.readUInt32();
  762. } catch (std::exception &exception) {
  763. MMKVError("%s", exception.what());
  764. } catch (...) {
  765. MMKVError("decode fail");
  766. }
  767. }
  768. if (hasValue != nullptr) {
  769. *hasValue = false;
  770. }
  771. return defaultValue;
  772. }
  773. int64_t MMKV::getInt64(MMKVKey_t key, int64_t defaultValue, bool *hasValue) {
  774. if (isKeyEmpty(key)) {
  775. if (hasValue != nullptr) {
  776. *hasValue = false;
  777. }
  778. return defaultValue;
  779. }
  780. SCOPED_LOCK(m_lock);
  781. SCOPED_LOCK(m_sharedProcessLock);
  782. auto data = getDataForKey(key);
  783. if (data.length() > 0) {
  784. try {
  785. CodedInputData input(data.getPtr(), data.length());
  786. if (hasValue != nullptr) {
  787. *hasValue = true;
  788. }
  789. return input.readInt64();
  790. } catch (std::exception &exception) {
  791. MMKVError("%s", exception.what());
  792. } catch (...) {
  793. MMKVError("decode fail");
  794. }
  795. }
  796. if (hasValue != nullptr) {
  797. *hasValue = false;
  798. }
  799. return defaultValue;
  800. }
  801. uint64_t MMKV::getUInt64(MMKVKey_t key, uint64_t defaultValue, bool *hasValue) {
  802. if (isKeyEmpty(key)) {
  803. if (hasValue != nullptr) {
  804. *hasValue = false;
  805. }
  806. return defaultValue;
  807. }
  808. SCOPED_LOCK(m_lock);
  809. SCOPED_LOCK(m_sharedProcessLock);
  810. auto data = getDataForKey(key);
  811. if (data.length() > 0) {
  812. try {
  813. CodedInputData input(data.getPtr(), data.length());
  814. if (hasValue != nullptr) {
  815. *hasValue = true;
  816. }
  817. return input.readUInt64();
  818. } catch (std::exception &exception) {
  819. MMKVError("%s", exception.what());
  820. } catch (...) {
  821. MMKVError("decode fail");
  822. }
  823. }
  824. if (hasValue != nullptr) {
  825. *hasValue = false;
  826. }
  827. return defaultValue;
  828. }
  829. float MMKV::getFloat(MMKVKey_t key, float defaultValue, bool *hasValue) {
  830. if (isKeyEmpty(key)) {
  831. if (hasValue != nullptr) {
  832. *hasValue = false;
  833. }
  834. return defaultValue;
  835. }
  836. SCOPED_LOCK(m_lock);
  837. SCOPED_LOCK(m_sharedProcessLock);
  838. auto data = getDataForKey(key);
  839. if (data.length() > 0) {
  840. try {
  841. CodedInputData input(data.getPtr(), data.length());
  842. if (hasValue != nullptr) {
  843. *hasValue = true;
  844. }
  845. return input.readFloat();
  846. } catch (std::exception &exception) {
  847. MMKVError("%s", exception.what());
  848. } catch (...) {
  849. MMKVError("decode fail");
  850. }
  851. }
  852. if (hasValue != nullptr) {
  853. *hasValue = false;
  854. }
  855. return defaultValue;
  856. }
  857. double MMKV::getDouble(MMKVKey_t key, double defaultValue, bool *hasValue) {
  858. if (isKeyEmpty(key)) {
  859. if (hasValue != nullptr) {
  860. *hasValue = false;
  861. }
  862. return defaultValue;
  863. }
  864. SCOPED_LOCK(m_lock);
  865. SCOPED_LOCK(m_sharedProcessLock);
  866. auto data = getDataForKey(key);
  867. if (data.length() > 0) {
  868. try {
  869. CodedInputData input(data.getPtr(), data.length());
  870. if (hasValue != nullptr) {
  871. *hasValue = true;
  872. }
  873. return input.readDouble();
  874. } catch (std::exception &exception) {
  875. MMKVError("%s", exception.what());
  876. } catch (...) {
  877. MMKVError("decode fail");
  878. }
  879. }
  880. if (hasValue != nullptr) {
  881. *hasValue = false;
  882. }
  883. return defaultValue;
  884. }
  885. size_t MMKV::getValueSize(MMKVKey_t key, bool actualSize) {
  886. if (isKeyEmpty(key)) {
  887. return 0;
  888. }
  889. SCOPED_LOCK(m_lock);
  890. SCOPED_LOCK(m_sharedProcessLock);
  891. auto data = getDataForKey(key);
  892. if (actualSize) {
  893. try {
  894. CodedInputData input(data.getPtr(), data.length());
  895. auto length = input.readInt32();
  896. if (length >= 0) {
  897. auto s_length = static_cast<size_t>(length);
  898. if (pbRawVarint32Size(length) + s_length == data.length()) {
  899. return s_length;
  900. }
  901. }
  902. } catch (std::exception &exception) {
  903. MMKVError("%s", exception.what());
  904. } catch (...) {
  905. MMKVError("decode fail");
  906. }
  907. }
  908. return data.length();
  909. }
  910. int32_t MMKV::writeValueToBuffer(MMKVKey_t key, void *ptr, int32_t size) {
  911. if (isKeyEmpty(key) || size < 0) {
  912. return -1;
  913. }
  914. auto s_size = static_cast<size_t>(size);
  915. SCOPED_LOCK(m_lock);
  916. SCOPED_LOCK(m_sharedProcessLock);
  917. auto data = getDataForKey(key);
  918. try {
  919. CodedInputData input(data.getPtr(), data.length());
  920. auto length = input.readInt32();
  921. auto offset = pbRawVarint32Size(length);
  922. if (length >= 0) {
  923. auto s_length = static_cast<size_t>(length);
  924. if (offset + s_length == data.length()) {
  925. if (s_length <= s_size) {
  926. memcpy(ptr, (uint8_t *) data.getPtr() + offset, s_length);
  927. return length;
  928. }
  929. } else {
  930. if (data.length() <= s_size) {
  931. memcpy(ptr, data.getPtr(), data.length());
  932. return static_cast<int32_t>(data.length());
  933. }
  934. }
  935. }
  936. } catch (std::exception &exception) {
  937. MMKVError("%s", exception.what());
  938. } catch (...) {
  939. MMKVError("encode fail");
  940. }
  941. return -1;
  942. }
  943. // enumerate
  944. bool MMKV::containsKey(MMKVKey_t key) {
  945. SCOPED_LOCK(m_lock);
  946. checkLoadData();
  947. if (mmkv_likely(!m_enableKeyExpire)) {
  948. if (m_crypter) {
  949. return m_dicCrypt->find(key) != m_dicCrypt->end();
  950. } else {
  951. return m_dic->find(key) != m_dic->end();
  952. }
  953. }
  954. auto raw = getDataWithoutMTimeForKey(key);
  955. return raw.length() != 0;
  956. }
  957. size_t MMKV::count(bool filterExpire) {
  958. SCOPED_LOCK(m_lock);
  959. checkLoadData();
  960. if (mmkv_unlikely(filterExpire && m_enableKeyExpire)) {
  961. SCOPED_LOCK(m_exclusiveProcessLock);
  962. fullWriteback(nullptr, true);
  963. }
  964. if (m_crypter) {
  965. return m_dicCrypt->size();
  966. } else {
  967. return m_dic->size();
  968. }
  969. }
  970. size_t MMKV::totalSize() {
  971. SCOPED_LOCK(m_lock);
  972. checkLoadData();
  973. return m_file->getFileSize();
  974. }
  975. size_t MMKV::actualSize() {
  976. SCOPED_LOCK(m_lock);
  977. checkLoadData();
  978. return m_actualSize;
  979. }
  980. bool MMKV::removeValueForKey(MMKVKey_t key) {
  981. if (isKeyEmpty(key)) {
  982. return false;
  983. }
  984. if (isReadOnly()) {
  985. MMKVWarning("[%s] file readonly", m_mmapID.c_str());
  986. return false;
  987. }
  988. SCOPED_LOCK(m_lock);
  989. SCOPED_LOCK(m_exclusiveProcessLock);
  990. checkLoadData();
  991. return removeDataForKey(key);
  992. }
  993. #ifndef MMKV_APPLE
  994. vector<string> MMKV::allKeys(bool filterExpire) {
  995. SCOPED_LOCK(m_lock);
  996. checkLoadData();
  997. if (mmkv_unlikely(filterExpire && m_enableKeyExpire)) {
  998. SCOPED_LOCK(m_exclusiveProcessLock);
  999. fullWriteback(nullptr, true);
  1000. }
  1001. vector<string> keys;
  1002. if (m_crypter) {
  1003. for (const auto &itr : *m_dicCrypt) {
  1004. keys.push_back(itr.first);
  1005. }
  1006. } else {
  1007. for (const auto &itr : *m_dic) {
  1008. keys.push_back(itr.first);
  1009. }
  1010. }
  1011. return keys;
  1012. }
  1013. bool MMKV::removeValuesForKeys(const vector<string> &arrKeys) {
  1014. if (isReadOnly()) {
  1015. MMKVWarning("[%s] file readonly", m_mmapID.c_str());
  1016. return false;
  1017. }
  1018. if (arrKeys.empty()) {
  1019. return true;
  1020. }
  1021. if (arrKeys.size() == 1) {
  1022. return removeValueForKey(arrKeys[0]);
  1023. }
  1024. SCOPED_LOCK(m_lock);
  1025. SCOPED_LOCK(m_exclusiveProcessLock);
  1026. checkLoadData();
  1027. size_t deleteCount = 0;
  1028. if (m_crypter) {
  1029. for (const auto &key : arrKeys) {
  1030. auto itr = m_dicCrypt->find(key);
  1031. if (itr != m_dicCrypt->end()) {
  1032. m_dicCrypt->erase(itr);
  1033. deleteCount++;
  1034. }
  1035. }
  1036. } else {
  1037. for (const auto &key : arrKeys) {
  1038. auto itr = m_dic->find(key);
  1039. if (itr != m_dic->end()) {
  1040. m_dic->erase(itr);
  1041. deleteCount++;
  1042. }
  1043. }
  1044. }
  1045. if (deleteCount > 0) {
  1046. m_hasFullWriteback = false;
  1047. return fullWriteback();
  1048. }
  1049. return true;
  1050. }
  1051. #endif // MMKV_APPLE
  1052. // file
  1053. void MMKV::sync(SyncFlag flag) {
  1054. MMKVInfo("MMKV::sync, SyncFlag = %d", flag);
  1055. SCOPED_LOCK(m_lock);
  1056. if (m_needLoadFromFile || !isFileValid()) {
  1057. return;
  1058. }
  1059. SCOPED_LOCK(m_exclusiveProcessLock);
  1060. m_file->msync(flag);
  1061. m_metaFile->msync(flag);
  1062. }
  1063. void MMKV::lock() {
  1064. SCOPED_LOCK(m_lock);
  1065. m_exclusiveProcessLock->lock();
  1066. }
  1067. void MMKV::unlock() {
  1068. SCOPED_LOCK(m_lock);
  1069. m_exclusiveProcessLock->unlock();
  1070. }
  1071. bool MMKV::try_lock() {
  1072. SCOPED_LOCK(m_lock);
  1073. return m_exclusiveProcessLock->try_lock();
  1074. }
  1075. #ifndef MMKV_WIN32
  1076. void MMKV::lock_thread() {
  1077. m_lock->lock();
  1078. }
  1079. void MMKV::unlock_thread() {
  1080. m_lock->unlock();
  1081. }
  1082. bool MMKV::try_lock_thread() {
  1083. return m_lock->try_lock();
  1084. }
  1085. #endif
  1086. // backup
  1087. static bool backupOneToDirectoryByFilePath(const string &mmapKey, const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  1088. File crcFile(srcPath, OpenFlag::ReadOnly);
  1089. if (!crcFile.isFileValid()) {
  1090. return false;
  1091. }
  1092. bool ret;
  1093. {
  1094. #ifdef MMKV_WIN32
  1095. MMKVInfo("backup one mmkv[%s] from [%ls] to [%ls]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1096. #else
  1097. MMKVInfo("backup one mmkv[%s] from [%s] to [%s]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1098. #endif
  1099. FileLock fileLock(crcFile.getFd());
  1100. InterProcessLock lock(&fileLock, SharedLockType);
  1101. SCOPED_LOCK(&lock);
  1102. ret = copyFile(srcPath, dstPath);
  1103. if (ret) {
  1104. auto srcCRCPath = srcPath + CRC_SUFFIX;
  1105. auto dstCRCPath = dstPath + CRC_SUFFIX;
  1106. ret = copyFile(srcCRCPath, dstCRCPath);
  1107. }
  1108. MMKVInfo("finish backup one mmkv[%s]", mmapKey.c_str());
  1109. }
  1110. return ret;
  1111. }
  1112. bool MMKV::backupOneToDirectory(const string &mmapKey, const MMKVPath_t &dstPath, const MMKVPath_t &srcPath, bool compareFullPath) {
  1113. if (!g_instanceLock) {
  1114. return false;
  1115. }
  1116. // we have to lock the creation of MMKV instance, regardless of in cache or not
  1117. SCOPED_LOCK(g_instanceLock);
  1118. MMKV *kv = nullptr;
  1119. if (!compareFullPath) {
  1120. auto itr = g_instanceDic->find(mmapKey);
  1121. if (itr != g_instanceDic->end()) {
  1122. kv = itr->second;
  1123. }
  1124. } else {
  1125. // mmapKey is actually filename, we can't simply call find()
  1126. for (auto &pair : *g_instanceDic) {
  1127. if (pair.second->m_path == srcPath) {
  1128. kv = pair.second;
  1129. break;
  1130. }
  1131. }
  1132. }
  1133. // get one in cache, do it the easy way
  1134. if (kv) {
  1135. #ifdef MMKV_WIN32
  1136. MMKVInfo("backup one cached mmkv[%s] from [%ls] to [%ls]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1137. #else
  1138. MMKVInfo("backup one cached mmkv[%s] from [%s] to [%s]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1139. #endif
  1140. SCOPED_LOCK(kv->m_lock);
  1141. SCOPED_LOCK(kv->m_sharedProcessLock);
  1142. kv->sync();
  1143. auto ret = copyFile(kv->m_path, dstPath);
  1144. if (ret) {
  1145. auto dstCRCPath = dstPath + CRC_SUFFIX;
  1146. ret = copyFile(kv->m_crcPath, dstCRCPath);
  1147. }
  1148. MMKVInfo("finish backup one mmkv[%s], ret: %d", mmapKey.c_str(), ret);
  1149. return ret;
  1150. }
  1151. // no luck with cache, do it the hard way
  1152. bool ret = backupOneToDirectoryByFilePath(mmapKey, srcPath, dstPath);
  1153. return ret;
  1154. }
  1155. bool MMKV::backupOneToDirectory(const string &mmapID, const MMKVPath_t &dstDir, const MMKVPath_t *srcDir) {
  1156. auto rootPath = srcDir ? srcDir : &g_realRootDir;
  1157. if (*rootPath == dstDir) {
  1158. return true;
  1159. }
  1160. mkPath(dstDir);
  1161. auto dstPath = mappedKVPathWithID(mmapID, &dstDir);
  1162. string mmapKey = mmapedKVKey(mmapID, rootPath);
  1163. #ifdef MMKV_ANDROID
  1164. string srcPath;
  1165. switch (tryMigrateLegacyMMKVFile(mmapID, rootPath)) {
  1166. case MigrateStatus::OldToNewMigrateFail: {
  1167. auto legacyID = legacyMmapedKVKey(mmapID, rootPath);
  1168. srcPath = mappedKVPathWithID(legacyID, rootPath);
  1169. break;
  1170. }
  1171. case MigrateStatus::NoneExist:
  1172. MMKVWarning("file with ID [%s] not exist in path [%s]", mmapID.c_str(), rootPath->c_str());
  1173. return false;
  1174. default:
  1175. srcPath = mappedKVPathWithID(mmapID, rootPath);
  1176. break;
  1177. }
  1178. #else
  1179. auto srcPath = mappedKVPathWithID(mmapID, rootPath);
  1180. #endif
  1181. return backupOneToDirectory(mmapKey, dstPath, srcPath, false);
  1182. }
  1183. bool endsWith(const MMKVPath_t &str, const MMKVPath_t &suffix) {
  1184. if (str.length() >= suffix.length()) {
  1185. return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
  1186. } else {
  1187. return false;
  1188. }
  1189. }
  1190. MMKVPath_t filename(const MMKVPath_t &path) {
  1191. auto startPos = path.rfind(MMKV_PATH_SLASH);
  1192. startPos++; // don't need to check for npos, because npos+1 == 0
  1193. auto filename = path.substr(startPos);
  1194. return filename;
  1195. }
  1196. size_t MMKV::backupAllToDirectory(const MMKVPath_t &dstDir, const MMKVPath_t &srcDir, bool isInSpecialDir) {
  1197. unordered_set<MMKVPath_t> mmapIDSet;
  1198. unordered_set<MMKVPath_t> mmapIDCRCSet;
  1199. walkInDir(srcDir, WalkFile, [&](const MMKVPath_t &filePath, WalkType) {
  1200. if (endsWith(filePath, CRC_SUFFIX)) {
  1201. mmapIDCRCSet.insert(filePath);
  1202. } else {
  1203. mmapIDSet.insert(filePath);
  1204. }
  1205. });
  1206. size_t count = 0;
  1207. if (!mmapIDSet.empty()) {
  1208. mkPath(dstDir);
  1209. auto compareFullPath = isInSpecialDir;
  1210. for (auto &srcPath : mmapIDSet) {
  1211. auto srcCRCPath = srcPath + CRC_SUFFIX;
  1212. if (mmapIDCRCSet.find(srcCRCPath) == mmapIDCRCSet.end()) {
  1213. #ifdef MMKV_WIN32
  1214. MMKVWarning("crc not exist [%ls]", srcCRCPath.c_str());
  1215. #else
  1216. MMKVWarning("crc not exist [%s]", srcCRCPath.c_str());
  1217. #endif
  1218. continue;
  1219. }
  1220. auto basename = filename(srcPath);
  1221. const auto &strBasename = MMKVPath_t2String(basename);
  1222. auto mmapKey = isInSpecialDir ? strBasename : mmapedKVKey(strBasename, &srcDir);
  1223. auto dstPath = dstDir + MMKV_PATH_SLASH;
  1224. dstPath += basename;
  1225. if (backupOneToDirectory(mmapKey, dstPath, srcPath, compareFullPath)) {
  1226. count++;
  1227. }
  1228. }
  1229. }
  1230. return count;
  1231. }
  1232. size_t MMKV::backupAllToDirectory(const MMKVPath_t &dstDir, const MMKVPath_t *srcDir) {
  1233. auto rootPath = srcDir ? srcDir : &g_realRootDir;
  1234. if (*rootPath == dstDir) {
  1235. return true;
  1236. }
  1237. auto count = backupAllToDirectory(dstDir, *rootPath, false);
  1238. auto specialSrcDir = *rootPath + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  1239. if (isFileExist(specialSrcDir)) {
  1240. auto specialDstDir = dstDir + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  1241. count += backupAllToDirectory(specialDstDir, specialSrcDir, true);
  1242. }
  1243. return count;
  1244. }
  1245. // restore
  1246. static bool restoreOneFromDirectoryByFilePath(const string &mmapKey, const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  1247. auto dstCRCPath = dstPath + CRC_SUFFIX;
  1248. File dstCRCFile(std::move(dstCRCPath), OpenFlag::ReadWrite | OpenFlag::Create);
  1249. if (!dstCRCFile.isFileValid()) {
  1250. return false;
  1251. }
  1252. bool ret;
  1253. {
  1254. #ifdef MMKV_WIN32
  1255. MMKVInfo("restore one mmkv[%s] from [%ls] to [%ls]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1256. #else
  1257. MMKVInfo("restore one mmkv[%s] from [%s] to [%s]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1258. #endif
  1259. FileLock fileLock(dstCRCFile.getFd());
  1260. InterProcessLock lock(&fileLock, ExclusiveLockType);
  1261. SCOPED_LOCK(&lock);
  1262. ret = copyFileContent(srcPath, dstPath);
  1263. if (ret) {
  1264. auto srcCRCPath = srcPath + CRC_SUFFIX;
  1265. ret = copyFileContent(srcCRCPath, dstCRCFile.getFd());
  1266. }
  1267. MMKVInfo("finish restore one mmkv[%s]", mmapKey.c_str());
  1268. }
  1269. return ret;
  1270. }
  1271. // We can't simply replace the existing file, because other processes might have already open it.
  1272. // They won't know a difference when the file has been replaced.
  1273. // We have to let them know by overriding the existing file with new content.
  1274. bool MMKV::restoreOneFromDirectory(const string &mmapKey, const MMKVPath_t &srcPath, const MMKVPath_t &dstPath, bool compareFullPath) {
  1275. if (!g_instanceLock) {
  1276. return false;
  1277. }
  1278. // we have to lock the creation of MMKV instance, regardless of in cache or not
  1279. SCOPED_LOCK(g_instanceLock);
  1280. MMKV *kv = nullptr;
  1281. if (!compareFullPath) {
  1282. auto itr = g_instanceDic->find(mmapKey);
  1283. if (itr != g_instanceDic->end()) {
  1284. kv = itr->second;
  1285. }
  1286. } else {
  1287. // mmapKey is actually filename, we can't simply call find()
  1288. for (auto &pair : *g_instanceDic) {
  1289. if (pair.second->m_path == dstPath) {
  1290. kv = pair.second;
  1291. break;
  1292. }
  1293. }
  1294. }
  1295. // get one in cache, do it the easy way
  1296. if (kv) {
  1297. #ifdef MMKV_WIN32
  1298. MMKVInfo("restore one cached mmkv[%s] from [%ls] to [%ls]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1299. #else
  1300. MMKVInfo("restore one cached mmkv[%s] from [%s] to [%s]", mmapKey.c_str(), srcPath.c_str(), dstPath.c_str());
  1301. #endif
  1302. SCOPED_LOCK(kv->m_lock);
  1303. SCOPED_LOCK(kv->m_exclusiveProcessLock);
  1304. kv->sync();
  1305. auto ret = copyFileContent(srcPath, kv->m_file->getFd());
  1306. kv->m_file->cleanMayflyFD();
  1307. if (ret) {
  1308. auto srcCRCPath = srcPath + CRC_SUFFIX;
  1309. // ret = copyFileContent(srcCRCPath, kv->m_metaFile->getFd());
  1310. // kv->m_metaFile->cleanMayflyFD();
  1311. #ifndef MMKV_ANDROID
  1312. MemoryFile srcCRCFile(srcCRCPath);
  1313. #else
  1314. MemoryFile srcCRCFile(srcCRCPath, DEFAULT_MMAP_SIZE, MMFILE_TYPE_FILE);
  1315. #endif
  1316. if (srcCRCFile.isFileValid()) {
  1317. memcpy(kv->m_metaFile->getMemory(), srcCRCFile.getMemory(), sizeof(MMKVMetaInfo));
  1318. } else {
  1319. ret = false;
  1320. }
  1321. }
  1322. // reload data after restore
  1323. kv->clearMemoryCache();
  1324. kv->loadFromFile();
  1325. if (kv->isMultiProcess()) {
  1326. kv->notifyContentChanged();
  1327. }
  1328. MMKVInfo("finish restore one mmkv[%s], ret: %d", mmapKey.c_str(), ret);
  1329. return ret;
  1330. }
  1331. // no luck with cache, do it the hard way
  1332. bool ret = restoreOneFromDirectoryByFilePath(mmapKey, srcPath, dstPath);
  1333. return ret;
  1334. }
  1335. bool MMKV::restoreOneFromDirectory(const string &mmapID, const MMKVPath_t &srcDir, const MMKVPath_t *dstDir) {
  1336. auto rootPath = dstDir ? dstDir : &g_realRootDir;
  1337. if (*rootPath == srcDir) {
  1338. return true;
  1339. }
  1340. mkPath(*rootPath);
  1341. auto srcPath = mappedKVPathWithID(mmapID, &srcDir);
  1342. auto mmapKey = mmapedKVKey(mmapID, rootPath);
  1343. #ifdef MMKV_ANDROID
  1344. string dstPath;
  1345. if (tryMigrateLegacyMMKVFile(mmapID, rootPath) == MigrateStatus::OldToNewMigrateFail) {
  1346. auto legacyID = legacyMmapedKVKey(mmapID, rootPath);
  1347. dstPath = mappedKVPathWithID(legacyID, rootPath);
  1348. } else {
  1349. dstPath = mappedKVPathWithID(mmapID, rootPath);
  1350. }
  1351. #else
  1352. auto dstPath = mappedKVPathWithID(mmapID, rootPath);
  1353. #endif
  1354. return restoreOneFromDirectory(mmapKey, srcPath, dstPath, false);
  1355. }
  1356. size_t MMKV::restoreAllFromDirectory(const MMKVPath_t &srcDir, const MMKVPath_t &dstDir, bool isInSpecialDir) {
  1357. unordered_set<MMKVPath_t> mmapIDSet;
  1358. unordered_set<MMKVPath_t> mmapIDCRCSet;
  1359. walkInDir(srcDir, WalkFile, [&](const MMKVPath_t &filePath, WalkType) {
  1360. if (endsWith(filePath, CRC_SUFFIX)) {
  1361. mmapIDCRCSet.insert(filePath);
  1362. } else {
  1363. mmapIDSet.insert(filePath);
  1364. }
  1365. });
  1366. size_t count = 0;
  1367. if (!mmapIDSet.empty()) {
  1368. mkPath(dstDir);
  1369. auto compareFullPath = isInSpecialDir;
  1370. for (auto &srcPath : mmapIDSet) {
  1371. auto srcCRCPath = srcPath + CRC_SUFFIX;
  1372. if (mmapIDCRCSet.find(srcCRCPath) == mmapIDCRCSet.end()) {
  1373. #ifdef MMKV_WIN32
  1374. MMKVWarning("crc not exist [%ls]", srcCRCPath.c_str());
  1375. #else
  1376. MMKVWarning("crc not exist [%s]", srcCRCPath.c_str());
  1377. #endif
  1378. continue;
  1379. }
  1380. auto basename = filename(srcPath);
  1381. const auto &strBasename = MMKVPath_t2String(basename);
  1382. auto mmapKey = isInSpecialDir ? strBasename : mmapedKVKey(strBasename, &dstDir);
  1383. auto dstPath = dstDir + MMKV_PATH_SLASH;
  1384. dstPath += basename;
  1385. if (restoreOneFromDirectory(mmapKey, srcPath, dstPath, compareFullPath)) {
  1386. count++;
  1387. }
  1388. }
  1389. }
  1390. return count;
  1391. }
  1392. size_t MMKV::restoreAllFromDirectory(const MMKVPath_t &srcDir, const MMKVPath_t *dstDir) {
  1393. auto rootPath = dstDir ? dstDir : &g_realRootDir;
  1394. if (*rootPath == srcDir) {
  1395. return true;
  1396. }
  1397. auto count = restoreAllFromDirectory(srcDir, *rootPath, true);
  1398. auto specialSrcDir = srcDir + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  1399. if (isFileExist(specialSrcDir)) {
  1400. auto specialDstDir = *rootPath + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  1401. count += restoreAllFromDirectory(specialSrcDir, specialDstDir, false);
  1402. }
  1403. return count;
  1404. }
  1405. // callbacks
  1406. void MMKV::registerErrorHandler(ErrorHandler handler) {
  1407. if (!g_instanceLock) {
  1408. return;
  1409. }
  1410. SCOPED_LOCK(g_instanceLock);
  1411. g_errorHandler = handler;
  1412. }
  1413. void MMKV::unRegisterErrorHandler() {
  1414. if (!g_instanceLock) {
  1415. return;
  1416. }
  1417. SCOPED_LOCK(g_instanceLock);
  1418. g_errorHandler = nullptr;
  1419. }
  1420. void MMKV::registerLogHandler(LogHandler handler) {
  1421. if (!g_instanceLock) {
  1422. return;
  1423. }
  1424. SCOPED_LOCK(g_instanceLock);
  1425. g_logHandler = handler;
  1426. }
  1427. void MMKV::unRegisterLogHandler() {
  1428. if (!g_instanceLock) {
  1429. return;
  1430. }
  1431. SCOPED_LOCK(g_instanceLock);
  1432. g_logHandler = nullptr;
  1433. }
  1434. void MMKV::setLogLevel(MMKVLogLevel level) {
  1435. if (!g_instanceLock) {
  1436. return;
  1437. }
  1438. SCOPED_LOCK(g_instanceLock);
  1439. g_currentLogLevel = level;
  1440. }
  1441. static void mkSpecialCharacterFileDirectory() {
  1442. MMKVPath_t path = g_realRootDir + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  1443. mkPath(path);
  1444. }
  1445. template <typename T>
  1446. static string md5(const basic_string<T> &value) {
  1447. uint8_t md[MD5_DIGEST_LENGTH] = {};
  1448. char tmp[3] = {}, buf[33] = {};
  1449. openssl::MD5((const uint8_t *) value.c_str(), value.size() * (sizeof(T) / sizeof(uint8_t)), md);
  1450. for (auto ch : md) {
  1451. snprintf(tmp, sizeof(tmp), "%2.2x", ch);
  1452. strcat(buf, tmp);
  1453. }
  1454. return {buf};
  1455. }
  1456. static MMKVPath_t encodeFilePath(const string &mmapID) {
  1457. const char *specialCharacters = "\\/:*?\"<>|";
  1458. string encodedID;
  1459. bool hasSpecialCharacter = false;
  1460. for (auto ch : mmapID) {
  1461. if (strchr(specialCharacters, ch) != nullptr) {
  1462. encodedID = md5(mmapID);
  1463. hasSpecialCharacter = true;
  1464. break;
  1465. }
  1466. }
  1467. if (hasSpecialCharacter) {
  1468. static ThreadOnceToken_t once = ThreadOnceUninitialized;
  1469. ThreadLock::ThreadOnce(&once, mkSpecialCharacterFileDirectory);
  1470. return MMKVPath_t(SPECIAL_CHARACTER_DIRECTORY_NAME) + MMKV_PATH_SLASH + string2MMKVPath_t(encodedID);
  1471. } else {
  1472. return string2MMKVPath_t(mmapID);
  1473. }
  1474. }
  1475. static MMKVPath_t encodeFilePath(const string &mmapID, const MMKVPath_t &rootDir) {
  1476. const char *specialCharacters = "\\/:*?\"<>|";
  1477. string encodedID;
  1478. bool hasSpecialCharacter = false;
  1479. for (auto ch : mmapID) {
  1480. if (strchr(specialCharacters, ch) != nullptr) {
  1481. encodedID = md5(mmapID);
  1482. hasSpecialCharacter = true;
  1483. break;
  1484. }
  1485. }
  1486. if (hasSpecialCharacter) {
  1487. MMKVPath_t path = rootDir + MMKV_PATH_SLASH + SPECIAL_CHARACTER_DIRECTORY_NAME;
  1488. mkPath(path);
  1489. return MMKVPath_t(SPECIAL_CHARACTER_DIRECTORY_NAME) + MMKV_PATH_SLASH + string2MMKVPath_t(encodedID);
  1490. } else {
  1491. return string2MMKVPath_t(mmapID);
  1492. }
  1493. }
  1494. string mmapedKVKey(const string &mmapID, const MMKVPath_t *rootPath) {
  1495. MMKVPath_t path;
  1496. // compare by pointer to speedup a bit, it's OK false detecting
  1497. if (rootPath && (rootPath != &g_realRootDir)) {
  1498. auto tmp = *rootPath + MMKV_PATH_SLASH + string2MMKVPath_t(mmapID);
  1499. path = absolutePath(tmp);
  1500. } else {
  1501. path = g_realRootDir + MMKV_PATH_SLASH + string2MMKVPath_t(mmapID);
  1502. }
  1503. return md5(path);
  1504. }
  1505. string legacyMmapedKVKey(const string &mmapID, const MMKVPath_t *rootPath) {
  1506. if (rootPath && (*rootPath != g_rootDir)) {
  1507. return md5(*rootPath + MMKV_PATH_SLASH + string2MMKVPath_t(mmapID));
  1508. }
  1509. return mmapID;
  1510. }
  1511. #ifndef MMKV_ANDROID
  1512. MMKVPath_t mappedKVPathWithID(const string &mmapID, const MMKVPath_t *rootPath) {
  1513. if (rootPath && (rootPath != &g_realRootDir)) {
  1514. auto path = *rootPath + MMKV_PATH_SLASH + encodeFilePath(mmapID, *rootPath);
  1515. return absolutePath(path);
  1516. }
  1517. auto path = g_realRootDir + MMKV_PATH_SLASH + encodeFilePath(mmapID);
  1518. return path;
  1519. }
  1520. #else
  1521. MMKVPath_t mappedKVPathWithID(const string &mmapID, const MMKVPath_t *rootPath, MMKVMode mode) {
  1522. if (mode & MMKV_ASHMEM) {
  1523. return ashmemMMKVPathWithID(encodeFilePath(mmapID));
  1524. } else if (rootPath && (rootPath != &g_realRootDir)) {
  1525. auto path = *rootPath + MMKV_PATH_SLASH + encodeFilePath(mmapID, *rootPath);
  1526. return absolutePath(path);
  1527. }
  1528. auto path = g_realRootDir + MMKV_PATH_SLASH + encodeFilePath(mmapID);
  1529. return path;
  1530. }
  1531. #endif
  1532. MMKVPath_t crcPathWithPath(const MMKVPath_t &kvPath) {
  1533. return kvPath + CRC_SUFFIX;
  1534. }
  1535. MMKVRecoverStrategic onMMKVCRCCheckFail(const string &mmapID) {
  1536. if (g_errorHandler) {
  1537. return g_errorHandler(mmapID, MMKVErrorType::MMKVCRCCheckFail);
  1538. }
  1539. return OnErrorDiscard;
  1540. }
  1541. MMKVRecoverStrategic onMMKVFileLengthError(const string &mmapID) {
  1542. if (g_errorHandler) {
  1543. return g_errorHandler(mmapID, MMKVErrorType::MMKVFileLength);
  1544. }
  1545. return OnErrorDiscard;
  1546. }
  1547. // NameSpace
  1548. NameSpace MMKV::nameSpace(const MMKVPath_t &rootDir) {
  1549. if (!g_instanceLock) {
  1550. ensureMinimalInitialize();
  1551. }
  1552. static ThreadOnceToken_t once = ThreadOnceUninitialized;
  1553. ThreadLock::ThreadOnce(&once, []{
  1554. g_namespaceLock = new ThreadLock;
  1555. g_namespaceLock->initialize();
  1556. });
  1557. SCOPED_LOCK(g_namespaceLock);
  1558. auto itr = g_realRootMap.find(rootDir);
  1559. if (itr == g_realRootMap.end()) {
  1560. auto realRoot = absolutePath(rootDir);
  1561. if (realRoot.ends_with(MMKV_PATH_SLASH)) {
  1562. realRoot.erase(realRoot.size() - 1);
  1563. }
  1564. itr = g_realRootMap.emplace(rootDir, realRoot).first;
  1565. }
  1566. return NameSpace(itr->second);
  1567. }
  1568. NameSpace MMKV::defaultNameSpace() {
  1569. if (g_rootDir.empty()) {
  1570. MMKVWarning("MMKV has not been initialized, there's no default NameSpace.");
  1571. return NameSpace(MMKVPath_t());
  1572. }
  1573. return NameSpace(g_realRootDir);
  1574. }
  1575. #ifndef MMKV_ANDROID
  1576. MMKV *NameSpace::mmkvWithID(const string &mmapID, MMKVMode mode, const string *cryptKey, size_t expectedCapacity) {
  1577. return MMKV::mmkvWithID(mmapID, mode, cryptKey, &m_rootDir, expectedCapacity);
  1578. }
  1579. #endif
  1580. bool NameSpace::backupOneToDirectory(const std::string &mmapID, const MMKVPath_t &dstDir) {
  1581. return MMKV::backupOneToDirectory(mmapID, dstDir, &m_rootDir);
  1582. }
  1583. bool NameSpace::restoreOneFromDirectory(const std::string &mmapID, const MMKVPath_t &srcDir) {
  1584. return MMKV::restoreOneFromDirectory(mmapID, srcDir, &m_rootDir);
  1585. }
  1586. size_t NameSpace::backupAllToDirectory(const MMKVPath_t &dstDir) {
  1587. return MMKV::backupAllToDirectory(dstDir, &m_rootDir);
  1588. }
  1589. size_t NameSpace::restoreAllFromDirectory(const MMKVPath_t &srcDir) {
  1590. return MMKV::restoreAllFromDirectory(srcDir, &m_rootDir);
  1591. }
  1592. bool NameSpace::isFileValid(const std::string &mmapID) {
  1593. return MMKV::isFileValid(mmapID, &m_rootDir);
  1594. }
  1595. bool NameSpace::removeStorage(const std::string &mmapID) {
  1596. return MMKV::removeStorage(mmapID, &m_rootDir);
  1597. }
  1598. bool NameSpace::checkExist(const std::string &mmapID) {
  1599. return MMKV::checkExist(mmapID, &m_rootDir);
  1600. }
  1601. MMKV_NAMESPACE_END