-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
MMKV.cpp
1214 lines (1053 loc) · 35.8 KB
/
MMKV.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Tencent is pleased to support the open source community by making
* MMKV available.
*
* Copyright (C) 2018 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MMKV.h"
#include "CodedInputData.h"
#include "CodedOutputData.h"
#include "InterProcessLock.h"
#include "MMBuffer.h"
#include "MMKVLog.h"
#include "MiniPBCoder.h"
#include "MmapedFile.h"
#include "PBUtility.h"
#include "ScopedLock.hpp"
#include "aes/AESCrypt.h"
#include <algorithm>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <zlib.h>
using namespace std;
static unordered_map<std::string, MMKV *> *g_instanceDic;
static ThreadLock g_instanceLock;
static std::string g_rootDir;
#define DEFAULT_MMAP_ID "mmkv.default"
constexpr uint32_t Fixed32Size = pbFixed32Size(0);
static string mappedKVPathWithID(const string &mmapID, MMKVMode mode);
static string crcPathWithID(const string &mmapID, MMKVMode mode);
enum : bool {
KeepSequence = false,
IncreaseSequence = true,
};
MMKV::MMKV(const std::string &mmapID, int size, MMKVMode mode, string *cryptKey)
: m_mmapID(mmapID)
, m_path(mappedKVPathWithID(m_mmapID, mode))
, m_crcPath(crcPathWithID(m_mmapID, mode))
, m_metaFile(m_crcPath, DEFAULT_MMAP_SIZE, (mode & MMKV_ASHMEM) ? MMAP_ASHMEM : MMAP_FILE)
, m_crypter(nullptr)
, m_fileLock(m_metaFile.getFd())
, m_sharedProcessLock(&m_fileLock, SharedLockType)
, m_exclusiveProcessLock(&m_fileLock, ExclusiveLockType)
, m_isInterProcess((mode & MMKV_MULTI_PROCESS) != 0)
, m_isAshmem((mode & MMKV_ASHMEM) != 0) {
m_fd = -1;
m_ptr = nullptr;
m_size = 0;
m_actualSize = 0;
m_output = nullptr;
if (m_isAshmem) {
m_ashmemFile = new MmapedFile(m_mmapID, static_cast<size_t>(size), MMAP_ASHMEM);
m_fd = m_ashmemFile->getFd();
} else {
m_ashmemFile = nullptr;
}
if (cryptKey && cryptKey->length() > 0) {
m_crypter = new AESCrypt((const unsigned char *) cryptKey->data(), cryptKey->length());
}
m_needLoadFromFile = true;
m_crcDigest = 0;
m_sharedProcessLock.m_enable = m_isInterProcess;
m_exclusiveProcessLock.m_enable = m_isInterProcess;
// sensitive zone
{
SCOPEDLOCK(m_sharedProcessLock);
loadFromFile();
}
}
MMKV::MMKV(const string &mmapID, int ashmemFD, int ashmemMetaFD, string *cryptKey)
: m_mmapID(mmapID)
, m_path("")
, m_crcPath("")
, m_metaFile(ashmemMetaFD)
, m_crypter(nullptr)
, m_fileLock(m_metaFile.getFd())
, m_sharedProcessLock(&m_fileLock, SharedLockType)
, m_exclusiveProcessLock(&m_fileLock, ExclusiveLockType)
, m_isInterProcess(true)
, m_isAshmem(true) {
// check mmapID with ashmemID
{
auto ashmemID = m_metaFile.getName();
size_t pos = ashmemID.find_last_of('.');
if (pos != string::npos) {
ashmemID.erase(pos, string::npos);
}
if (mmapID != ashmemID) {
MMKVWarning("mmapID[%s] != ashmem[%s]", mmapID.c_str(), ashmemID.c_str());
}
}
m_path = string(ASHMEM_NAME_DEF) + "/" + m_mmapID;
m_crcPath = string(ASHMEM_NAME_DEF) + "/" + m_metaFile.getName();
m_fd = ashmemFD;
m_ptr = nullptr;
m_size = 0;
m_actualSize = 0;
m_output = nullptr;
if (m_isAshmem) {
m_ashmemFile = new MmapedFile(m_fd);
} else {
m_ashmemFile = nullptr;
}
if (cryptKey && cryptKey->length() > 0) {
m_crypter = new AESCrypt((const unsigned char *) cryptKey->data(), cryptKey->length());
}
m_needLoadFromFile = true;
m_crcDigest = 0;
m_sharedProcessLock.m_enable = m_isInterProcess;
m_exclusiveProcessLock.m_enable = m_isInterProcess;
// sensitive zone
{
SCOPEDLOCK(m_sharedProcessLock);
loadFromFile();
}
}
MMKV::~MMKV() {
clearMemoryState();
if (m_ashmemFile) {
delete m_ashmemFile;
m_ashmemFile = nullptr;
}
if (m_crypter) {
delete m_crypter;
m_crypter = nullptr;
}
}
MMKV *MMKV::defaultMMKV(MMKVMode mode, string *cryptKey) {
return mmkvWithID(DEFAULT_MMAP_ID, DEFAULT_MMAP_SIZE, mode, cryptKey);
}
void initialize() {
g_instanceDic = new unordered_map<std::string, MMKV *>;
g_instanceLock = ThreadLock();
//testAESCrypt();
MMKVInfo("page size:%d", DEFAULT_MMAP_SIZE);
}
void MMKV::initializeMMKV(const std::string &rootDir) {
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
pthread_once(&once_control, initialize);
g_rootDir = rootDir;
char *path = strdup(g_rootDir.c_str());
mkPath(path);
free(path);
MMKVInfo("root dir: %s", g_rootDir.c_str());
}
MMKV *MMKV::mmkvWithID(const std::string &mmapID, int size, MMKVMode mode, string *cryptKey) {
if (mmapID.empty()) {
return nullptr;
}
SCOPEDLOCK(g_instanceLock);
auto itr = g_instanceDic->find(mmapID);
if (itr != g_instanceDic->end()) {
MMKV *kv = itr->second;
return kv;
}
auto kv = new MMKV(mmapID, size, mode, cryptKey);
(*g_instanceDic)[mmapID] = kv;
return kv;
}
MMKV *MMKV::mmkvWithAshmemFD(const string &mmapID, int fd, int metaFD, string *cryptKey) {
if (fd < 0) {
return nullptr;
}
SCOPEDLOCK(g_instanceLock);
auto itr = g_instanceDic->find(mmapID);
if (itr != g_instanceDic->end()) {
MMKV *kv = itr->second;
kv->checkReSetCryptKey(fd, metaFD, cryptKey);
return kv;
}
auto kv = new MMKV(mmapID, fd, metaFD, cryptKey);
(*g_instanceDic)[mmapID] = kv;
return kv;
}
void MMKV::onExit() {
SCOPEDLOCK(g_instanceLock);
for (auto &itr : *g_instanceDic) {
MMKV *kv = itr.second;
kv->sync();
kv->clearMemoryState();
}
}
const std::string &MMKV::mmapID() {
return m_mmapID;
}
std::string MMKV::cryptKey() {
SCOPEDLOCK(m_lock);
if (m_crypter) {
char key[AES_KEY_LEN];
m_crypter->getKey(key);
return string(key, strnlen(key, AES_KEY_LEN));
}
return "";
}
#pragma mark - really dirty work
void decryptBuffer(AESCrypt &crypter, MMBuffer &inputBuffer) {
size_t length = inputBuffer.length();
MMBuffer tmp(length);
auto input = (unsigned char *) inputBuffer.getPtr();
auto output = (unsigned char *) tmp.getPtr();
crypter.decrypt(input, output, length);
inputBuffer = std::move(tmp);
}
void MMKV::loadFromFile() {
if (m_isAshmem) {
loadFromAshmem();
return;
}
m_metaInfo.read(m_metaFile.getMemory());
m_fd = open(m_path.c_str(), O_RDWR | O_CREAT, S_IRWXU);
if (m_fd < 0) {
MMKVError("fail to open:%s, %s", m_path.c_str(), strerror(errno));
} else {
m_size = 0;
struct stat st = {0};
if (fstat(m_fd, &st) != -1) {
m_size = static_cast<size_t>(st.st_size);
}
// round up to (n * pagesize)
if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
size_t oldSize = m_size;
m_size = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
if (ftruncate(m_fd, m_size) != 0) {
MMKVError("fail to truncate [%s] to size %zu, %s", m_mmapID.c_str(), m_size,
strerror(errno));
m_size = static_cast<size_t>(st.st_size);
}
zeroFillFile(m_fd, oldSize, m_size - oldSize);
}
m_ptr = (char *) mmap(nullptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd, 0);
if (m_ptr == MAP_FAILED) {
MMKVError("fail to mmap [%s], %s", m_mmapID.c_str(), strerror(errno));
} else {
memcpy(&m_actualSize, m_ptr, Fixed32Size);
MMKVInfo("loading [%s] with %zu size in total, file size is %zu", m_mmapID.c_str(),
m_actualSize, m_size);
bool loaded = false;
if (m_actualSize > 0) {
if (m_actualSize < m_size && m_actualSize + Fixed32Size <= m_size) {
if (checkFileCRCValid()) {
MMKVInfo("loading [%s] with crc %u sequence %u", m_mmapID.c_str(),
m_metaInfo.m_crcDigest, m_metaInfo.m_sequence);
MMBuffer inputBuffer(m_ptr + Fixed32Size, m_actualSize, MMBufferNoCopy);
if (m_crypter) {
decryptBuffer(*m_crypter, inputBuffer);
}
m_dic = MiniPBCoder::decodeMap(inputBuffer);
m_output = new CodedOutputData(m_ptr + Fixed32Size + m_actualSize,
m_size - Fixed32Size - m_actualSize);
loaded = true;
}
}
}
if (!loaded) {
SCOPEDLOCK(m_exclusiveProcessLock);
if (m_actualSize > 0) {
writeAcutalSize(0);
}
m_output = new CodedOutputData(m_ptr + Fixed32Size, m_size - Fixed32Size);
recaculateCRCDigest();
}
MMKVInfo("loaded [%s] with %zu values", m_mmapID.c_str(), m_dic.size());
}
}
if (!isFileValid()) {
MMKVWarning("[%s] file not valid", m_mmapID.c_str());
}
m_needLoadFromFile = false;
}
void MMKV::loadFromAshmem() {
m_metaInfo.read(m_metaFile.getMemory());
if (m_fd < 0 || !m_ashmemFile) {
MMKVError("ashmem file invalid %s, fd:%d", m_path.c_str(), m_fd);
} else {
m_size = m_ashmemFile->getFileSize();
m_ptr = (char *) m_ashmemFile->getMemory();
if (m_ptr != MAP_FAILED) {
memcpy(&m_actualSize, m_ptr, Fixed32Size);
MMKVInfo("loading [%s] with %zu size in total, file size is %zu", m_mmapID.c_str(),
m_actualSize, m_size);
bool loaded = false;
if (m_actualSize > 0) {
if (m_actualSize < m_size && m_actualSize + Fixed32Size <= m_size) {
if (checkFileCRCValid()) {
MMKVInfo("loading [%s] with crc %u sequence %u", m_mmapID.c_str(),
m_metaInfo.m_crcDigest, m_metaInfo.m_sequence);
MMBuffer inputBuffer(m_ptr + Fixed32Size, m_actualSize, MMBufferNoCopy);
if (m_crypter) {
decryptBuffer(*m_crypter, inputBuffer);
}
m_dic = MiniPBCoder::decodeMap(inputBuffer);
m_output = new CodedOutputData(m_ptr + Fixed32Size + m_actualSize,
m_size - Fixed32Size - m_actualSize);
loaded = true;
}
}
}
if (!loaded) {
SCOPEDLOCK(m_exclusiveProcessLock);
if (m_actualSize > 0) {
writeAcutalSize(0);
}
m_output = new CodedOutputData(m_ptr + Fixed32Size, m_size - Fixed32Size);
recaculateCRCDigest();
}
MMKVInfo("loaded [%s] with %zu values", m_mmapID.c_str(), m_dic.size());
}
}
if (!isFileValid()) {
MMKVWarning("[%s] ashmem not valid", m_mmapID.c_str());
}
m_needLoadFromFile = false;
}
// read from last m_position
void MMKV::partialLoadFromFile() {
m_metaInfo.read(m_metaFile.getMemory());
size_t oldActualSize = m_actualSize;
memcpy(&m_actualSize, m_ptr, Fixed32Size);
MMKVDebug("loading [%s] with file size %zu, oldActualSize %zu, newActualSize %zu",
m_mmapID.c_str(), m_size, oldActualSize, m_actualSize);
if (m_actualSize > 0) {
if (m_actualSize < m_size && m_actualSize + Fixed32Size <= m_size) {
if (m_actualSize > oldActualSize) {
size_t bufferSize = m_actualSize - oldActualSize;
MMBuffer inputBuffer(m_ptr + Fixed32Size + oldActualSize, bufferSize,
MMBufferNoCopy);
// incremental update crc digest
m_crcDigest = (uint32_t) crc32(m_crcDigest, (const uint8_t *) inputBuffer.getPtr(),
static_cast<uInt>(inputBuffer.length()));
if (m_crcDigest == m_metaInfo.m_crcDigest) {
if (m_crypter) {
decryptBuffer(*m_crypter, inputBuffer);
}
auto dic = MiniPBCoder::decodeMap(inputBuffer, bufferSize);
for (auto &itr : dic) {
//m_dic[itr.first] = std::move(itr.second);
auto target = m_dic.find(itr.first);
if (target == m_dic.end()) {
m_dic.emplace(itr.first, std::move(itr.second));
} else {
target->second = std::move(itr.second);
}
}
m_output->seek(bufferSize);
MMKVDebug("partial loaded [%s] with %zu values", m_mmapID.c_str(),
m_dic.size());
return;
} else {
MMKVError("m_crcDigest[%u] != m_metaInfo.m_crcDigest[%u]", m_crcDigest,
m_metaInfo.m_crcDigest);
}
}
}
}
// something is wrong, do a full load
clearMemoryState();
loadFromFile();
}
void MMKV::checkLoadData() {
if (m_needLoadFromFile) {
SCOPEDLOCK(m_sharedProcessLock);
m_needLoadFromFile = false;
loadFromFile();
return;
}
if (!m_isInterProcess) {
return;
}
// TODO: atomic lock m_metaFile?
MMKVMetaInfo metaInfo;
metaInfo.read(m_metaFile.getMemory());
if (m_metaInfo.m_sequence != metaInfo.m_sequence) {
MMKVInfo("[%s] oldSeq %u, newSeq %u", m_mmapID.c_str(), m_metaInfo.m_sequence,
metaInfo.m_sequence);
SCOPEDLOCK(m_sharedProcessLock);
clearMemoryState();
loadFromFile();
} else if (m_metaInfo.m_crcDigest != metaInfo.m_crcDigest) {
MMKVDebug("[%s] oldCrc %u, newCrc %u", m_mmapID.c_str(), m_metaInfo.m_crcDigest,
metaInfo.m_crcDigest);
SCOPEDLOCK(m_sharedProcessLock);
size_t fileSize = 0;
if (m_isAshmem) {
fileSize = m_size;
} else {
struct stat st = {0};
if (fstat(m_fd, &st) != -1) {
fileSize = (size_t) st.st_size;
}
}
if (m_size != fileSize) {
MMKVInfo("file size has changed [%s] from %zu to %zu", m_mmapID.c_str(), m_size,
fileSize);
clearMemoryState();
loadFromFile();
} else {
partialLoadFromFile();
}
}
}
void MMKV::clearAll() {
MMKVInfo("cleaning all key-values from [%s]", m_mmapID.c_str());
SCOPEDLOCK(m_lock);
SCOPEDLOCK(m_exclusiveProcessLock);
if (m_needLoadFromFile && !m_isAshmem) {
removeFile(m_path.c_str());
loadFromFile();
return;
}
if (m_ptr && m_ptr != MAP_FAILED) {
// for truncate
size_t size = std::min<size_t>(static_cast<size_t>(DEFAULT_MMAP_SIZE), m_size);
memset(m_ptr, 0, size);
if (msync(m_ptr, size, MS_SYNC) != 0) {
MMKVError("fail to msync [%s]:%s", m_mmapID.c_str(), strerror(errno));
}
}
if (!m_isAshmem) {
if (m_fd >= 0) {
if (m_size != DEFAULT_MMAP_SIZE) {
MMKVInfo("truncating [%s] from %zu to %d", m_mmapID.c_str(), m_size,
DEFAULT_MMAP_SIZE);
if (ftruncate(m_fd, DEFAULT_MMAP_SIZE) != 0) {
MMKVError("fail to truncate [%s] to size %d, %s", m_mmapID.c_str(),
DEFAULT_MMAP_SIZE, strerror(errno));
}
}
}
}
clearMemoryState();
loadFromFile();
}
void MMKV::clearMemoryState() {
MMKVInfo("clearMemoryState [%s]", m_mmapID.c_str());
SCOPEDLOCK(m_lock);
if (m_needLoadFromFile) {
return;
}
m_needLoadFromFile = true;
m_dic.clear();
if (m_crypter) {
m_crypter->reset();
}
if (m_output) {
delete m_output;
}
m_output = nullptr;
if (!m_isAshmem) {
if (m_ptr && m_ptr != MAP_FAILED) {
if (munmap(m_ptr, m_size) != 0) {
MMKVError("fail to munmap [%s], %s", m_mmapID.c_str(), strerror(errno));
}
}
m_ptr = nullptr;
if (m_fd >= 0) {
if (close(m_fd) != 0) {
MMKVError("fail to close [%s], %s", m_mmapID.c_str(), strerror(errno));
}
}
m_fd = -1;
}
m_size = 0;
m_actualSize = 0;
}
// since we use append mode, when -[setData: forKey:] many times, space may not be enough
// try a full rewrite to make space
bool MMKV::ensureMemorySize(size_t newSize) {
if (!isFileValid()) {
MMKVWarning("[%s] file not valid", m_mmapID.c_str());
return false;
}
if (newSize >= m_output->spaceLeft()) {
// try a full rewrite to make space
static const int offset = pbFixed32Size(0);
MMBuffer data = MiniPBCoder::encodeDataWithObject(m_dic);
size_t lenNeeded = data.length() + offset + newSize;
if (m_isAshmem) {
if (lenNeeded > m_size) {
MMKVWarning("ashmem %s reach size limit:%zu, consider configure with larger size",
m_mmapID.c_str(), m_size);
return false;
}
} else {
size_t futureUsage = newSize * std::max<size_t>(8, (m_dic.size() + 1) / 2);
// 1. no space for a full rewrite, double it
// 2. or space is not large enough for future usage, double it to avoid frequently full rewrite
if (lenNeeded >= m_size || (lenNeeded + futureUsage) >= m_size) {
size_t oldSize = m_size;
do {
m_size *= 2;
} while (lenNeeded + futureUsage >= m_size);
MMKVInfo(
"extending [%s] file size from %zu to %zu, incoming size:%zu, futrue usage:%zu",
m_mmapID.c_str(), oldSize, m_size, newSize, futureUsage);
// if we can't extend size, rollback to old state
if (ftruncate(m_fd, m_size) != 0) {
MMKVError("fail to truncate [%s] to size %zu, %s", m_mmapID.c_str(), m_size,
strerror(errno));
m_size = oldSize;
return false;
}
if (!zeroFillFile(m_fd, oldSize, m_size - oldSize)) {
MMKVError("fail to zeroFile [%s] to size %zu, %s", m_mmapID.c_str(), m_size,
strerror(errno));
m_size = oldSize;
return false;
}
if (munmap(m_ptr, oldSize) != 0) {
MMKVError("fail to munmap [%s], %s", m_mmapID.c_str(), strerror(errno));
}
m_ptr = (char *) mmap(m_ptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd, 0);
if (m_ptr == MAP_FAILED) {
MMKVError("fail to mmap [%s], %s", m_mmapID.c_str(), strerror(errno));
}
// check if we fail to make more space
if (!isFileValid()) {
MMKVWarning("[%s] file not valid", m_mmapID.c_str());
return false;
}
}
}
if (m_crypter) {
m_crypter->reset();
auto ptr = (unsigned char *) data.getPtr();
m_crypter->encrypt(ptr, ptr, data.length());
}
writeAcutalSize(data.length());
delete m_output;
m_output = new CodedOutputData(m_ptr + offset, m_size - offset);
m_output->writeRawData(data);
recaculateCRCDigest();
}
return true;
}
void MMKV::writeAcutalSize(size_t actualSize) {
assert(m_ptr != 0);
assert(m_ptr != MAP_FAILED);
memcpy(m_ptr, &actualSize, Fixed32Size);
m_actualSize = actualSize;
}
const MMBuffer &MMKV::getDataForKey(const std::string &key) {
SCOPEDLOCK(m_lock);
checkLoadData();
auto itr = m_dic.find(key);
if (itr != m_dic.end()) {
return itr->second;
}
static MMBuffer nan(0);
return nan;
}
bool MMKV::setDataForKey(MMBuffer &&data, const std::string &key) {
if (data.length() == 0 || key.empty()) {
return false;
}
SCOPEDLOCK(m_lock);
SCOPEDLOCK(m_exclusiveProcessLock);
checkLoadData();
// m_dic[key] = std::move(data);
auto itr = m_dic.find(key);
if (itr == m_dic.end()) {
itr = m_dic.emplace(key, std::move(data)).first;
} else {
itr->second = std::move(data);
}
return appendDataWithKey(itr->second, key);
}
bool MMKV::removeDataForKey(const std::string &key) {
if (key.empty()) {
return false;
}
auto deleteCount = m_dic.erase(key);
if (deleteCount > 0) {
static MMBuffer nan(0);
return appendDataWithKey(nan, key);
}
return false;
}
bool MMKV::appendDataWithKey(const MMBuffer &data, const std::string &key) {
size_t keyLength = key.length();
// size needed to encode the key
size_t size = keyLength + pbRawVarint32Size((int32_t) keyLength);
// size needed to encode the value
size += data.length() + pbRawVarint32Size((int32_t) data.length());
SCOPEDLOCK(m_exclusiveProcessLock);
bool hasEnoughSize = ensureMemorySize(size);
if (!hasEnoughSize || !isFileValid()) {
return false;
}
if (m_actualSize == 0) {
auto allData = MiniPBCoder::encodeDataWithObject(m_dic);
if (allData.length() > 0) {
if (m_crypter) {
m_crypter->reset();
auto ptr = (unsigned char *) allData.getPtr();
m_crypter->encrypt(ptr, ptr, allData.length());
}
writeAcutalSize(allData.length());
m_output->writeRawData(allData); // note: don't write size of data
recaculateCRCDigest();
return true;
}
return false;
} else {
writeAcutalSize(m_actualSize + size);
m_output->writeString(key);
m_output->writeData(data); // note: write size of data
auto ptr = (uint8_t *) m_ptr + Fixed32Size + m_actualSize - size;
if (m_crypter) {
m_crypter->encrypt(ptr, ptr, size);
}
updateCRCDigest(ptr, size, KeepSequence);
return true;
}
}
bool MMKV::fullWriteback() {
if (m_needLoadFromFile) {
return true;
}
if (!isFileValid()) {
MMKVWarning("[%s] file not valid", m_mmapID.c_str());
return false;
}
if (m_dic.empty()) {
clearAll();
return true;
}
auto allData = MiniPBCoder::encodeDataWithObject(m_dic);
SCOPEDLOCK(m_exclusiveProcessLock);
if (allData.length() > 0 && isFileValid()) {
if (allData.length() + Fixed32Size <= m_size) {
if (m_crypter) {
m_crypter->reset();
auto ptr = (unsigned char *) allData.getPtr();
m_crypter->encrypt(ptr, ptr, allData.length());
}
writeAcutalSize(allData.length());
delete m_output;
m_output = new CodedOutputData(m_ptr + Fixed32Size, m_size - Fixed32Size);
m_output->writeRawData(allData); // note: don't write size of data
recaculateCRCDigest();
return true;
} else {
// ensureMemorySize will extend file & full rewrite, no need to write back again
return ensureMemorySize(allData.length() + Fixed32Size - m_size);
}
}
return false;
}
bool MMKV::reKey(const std::string &cryptKey) {
SCOPEDLOCK(m_lock);
checkLoadData();
if (m_crypter) {
if (cryptKey.length() > 0) {
string oldKey = this->cryptKey();
if (cryptKey == oldKey) {
return true;
} else {
// change encryption key
MMKVInfo("reKey with new aes key");
delete m_crypter;
auto ptr = (const unsigned char *) cryptKey.data();
m_crypter = new AESCrypt(ptr, cryptKey.length());
return fullWriteback();
}
} else {
// decryption to plain text
MMKVInfo("reKey with no aes key");
delete m_crypter;
m_crypter = nullptr;
return fullWriteback();
}
} else {
if (cryptKey.length() > 0) {
// transform plain text to encrypted text
MMKVInfo("reKey with aes key");
auto ptr = (const unsigned char *) cryptKey.data();
m_crypter = new AESCrypt(ptr, cryptKey.length());
return fullWriteback();
} else {
return true;
}
}
return false;
}
void MMKV::checkReSetCryptKey(const std::string *cryptKey) {
SCOPEDLOCK(m_lock);
if (m_crypter) {
if (cryptKey) {
string oldKey = this->cryptKey();
if (oldKey != *cryptKey) {
MMKVInfo("setting new aes key");
delete m_crypter;
auto ptr = (const unsigned char *) cryptKey->data();
m_crypter = new AESCrypt(ptr, cryptKey->length());
checkLoadData();
} else {
// nothing to do
}
} else {
MMKVInfo("reset aes key");
delete m_crypter;
m_crypter = nullptr;
checkLoadData();
}
} else {
if (cryptKey) {
MMKVInfo("setting new aes key");
auto ptr = (const unsigned char *) cryptKey->data();
m_crypter = new AESCrypt(ptr, cryptKey->length());
checkLoadData();
} else {
// nothing to do
}
}
}
void MMKV::checkReSetCryptKey(int fd, int metaFD, std::string *cryptKey) {
SCOPEDLOCK(m_lock);
checkReSetCryptKey(cryptKey);
if (m_isAshmem) {
if (m_fd != fd) {
close(fd);
}
if (m_metaFile.getFd() != metaFD) {
close(metaFD);
}
}
}
bool MMKV::isFileValid() {
if (m_fd >= 0 && m_size > 0 && m_output && m_ptr && m_ptr != MAP_FAILED) {
return true;
}
return false;
}
#pragma mark - crc
// assuming m_ptr & m_size is set
bool MMKV::checkFileCRCValid() {
if (m_ptr && m_ptr != MAP_FAILED) {
constexpr int offset = pbFixed32Size(0);
m_crcDigest =
(uint32_t) crc32(0, (const uint8_t *) m_ptr + offset, (uint32_t) m_actualSize);
m_metaInfo.read(m_metaFile.getMemory());
if (m_crcDigest == m_metaInfo.m_crcDigest) {
return true;
}
MMKVError("check crc [%s] fail, crc32:%u, m_crcDigest:%u", m_mmapID.c_str(),
m_metaInfo.m_crcDigest, m_crcDigest);
}
return false;
}
void MMKV::recaculateCRCDigest() {
if (m_ptr && m_ptr != MAP_FAILED) {
m_crcDigest = 0;
constexpr int offset = pbFixed32Size(0);
updateCRCDigest((const uint8_t *) m_ptr + offset, m_actualSize, IncreaseSequence);
}
}
void MMKV::updateCRCDigest(const uint8_t *ptr, size_t length, bool increaseSequence) {
if (!ptr) {
return;
}
m_crcDigest = (uint32_t) crc32(m_crcDigest, ptr, (uint32_t) length);
void *crcPtr = m_metaFile.getMemory();
if (crcPtr == nullptr || crcPtr == MAP_FAILED) {
return;
}
m_metaInfo.m_crcDigest = m_crcDigest;
if (increaseSequence) {
m_metaInfo.m_sequence++;
}
if (m_metaInfo.m_version == 0) {
m_metaInfo.m_version = 1;
}
m_metaInfo.write(crcPtr);
}
#pragma mark - set & get
bool MMKV::setStringForKey(const std::string &value, const std::string &key) {
if (key.empty()) {
return false;
}
auto data = MiniPBCoder::encodeDataWithObject(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setBytesForKey(const MMBuffer &value, const std::string &key) {
if (key.empty()) {
return false;
}
auto data = MiniPBCoder::encodeDataWithObject(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setBool(bool value, const std::string &key) {
if (key.empty()) {
return false;
}
size_t size = pbBoolSize(value);
MMBuffer data(size);
CodedOutputData output(data.getPtr(), size);
output.writeBool(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setInt32(int32_t value, const std::string &key) {
if (key.empty()) {
return false;
}
size_t size = pbInt32Size(value);
MMBuffer data(size);
CodedOutputData output(data.getPtr(), size);
output.writeInt32(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setInt64(int64_t value, const std::string &key) {
if (key.empty()) {
return false;
}
size_t size = pbInt64Size(value);
MMBuffer data(size);
CodedOutputData output(data.getPtr(), size);
output.writeInt64(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setFloat(float value, const std::string &key) {
if (key.empty()) {
return false;
}
size_t size = pbFloatSize(value);
MMBuffer data(size);
CodedOutputData output(data.getPtr(), size);
output.writeFloat(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setDouble(double value, const std::string &key) {
if (key.empty()) {
return false;
}
size_t size = pbDoubleSize(value);
MMBuffer data(size);
CodedOutputData output(data.getPtr(), size);
output.writeDouble(value);
return setDataForKey(std::move(data), key);
}
bool MMKV::setVectorForKey(const std::vector<std::string> &v, const std::string &key) {
if (key.empty()) {
return false;
}
auto data = MiniPBCoder::encodeDataWithObject(v);
return setDataForKey(std::move(data), key);
}
bool MMKV::getStringForKey(const std::string &key, std::string &result) {
if (key.empty()) {
return false;
}