MMKV_OSX.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. * Tencent is pleased to support the open source community by making
  3. * MMKV available.
  4. *
  5. * Copyright (C) 2019 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 "MMKVPredef.h"
  21. #ifdef MMKV_APPLE
  22. # include "CodedInputData.h"
  23. # include "CodedOutputData.h"
  24. # include "InterProcessLock.h"
  25. # include "MMKV.h"
  26. # include "MemoryFile.h"
  27. # include "MiniPBCoder.h"
  28. # include "PBUtility.h"
  29. # include "ScopedLock.hpp"
  30. # include "ThreadLock.h"
  31. # include "aes/AESCrypt.h"
  32. # include <sys/utsname.h>
  33. # ifdef MMKV_IOS
  34. # include "MMKV_OSX.h"
  35. # include <sys/mman.h>
  36. # endif
  37. # ifdef __aarch64__
  38. # include "Checksum.h"
  39. # endif
  40. # if __has_feature(objc_arc)
  41. # error This file must be compiled with MRC. Use -fno-objc-arc flag.
  42. # endif
  43. using namespace std;
  44. using namespace mmkv;
  45. extern ThreadLock *g_instanceLock;
  46. extern MMKVPath_t g_rootDir;
  47. enum { UnKnown = 0, PowerMac = 1, Mac, iPhone, iPod, iPad, AppleTV, AppleWatch };
  48. static void GetAppleMachineInfo(int &device, int &version);
  49. MMKV_NAMESPACE_BEGIN
  50. # ifdef MMKV_IOS
  51. MLockPtr::MLockPtr(void *ptr, size_t size) : m_lockDownSize(0), m_lockedPtr(nullptr) {
  52. if (!ptr || size == 0) {
  53. return;
  54. }
  55. // calc ptr to mlock()
  56. auto writePtr = (size_t) ptr;
  57. auto lockPtr = (writePtr / DEFAULT_MMAP_SIZE) * DEFAULT_MMAP_SIZE;
  58. auto lockDownSize = writePtr - lockPtr + size;
  59. if (mlock((void *) lockPtr, lockDownSize) == 0) {
  60. m_lockedPtr = (uint8_t *) lockPtr;
  61. m_lockDownSize = lockDownSize;
  62. } else {
  63. MMKVError("fail to mlock [%p], %s", m_lockedPtr, strerror(errno));
  64. // just fail on this condition, otherwise app will crash anyway
  65. }
  66. }
  67. MLockPtr::MLockPtr(MLockPtr &&other) : m_lockDownSize(other.m_lockDownSize), m_lockedPtr(other.m_lockedPtr) {
  68. other.m_lockedPtr = nullptr;
  69. }
  70. MLockPtr::~MLockPtr() {
  71. if (m_lockedPtr) {
  72. munlock(m_lockedPtr, m_lockDownSize);
  73. }
  74. }
  75. # endif
  76. extern ThreadOnceToken_t once_control;
  77. extern void initialize();
  78. void MMKV::minimalInit(MMKVPath_t defaultRootDir) {
  79. ThreadLock::ThreadOnce(&once_control, initialize);
  80. // crc32 instruction requires A10 chip, aka iPhone 7 or iPad 6th generation
  81. int device = 0, version = 0;
  82. GetAppleMachineInfo(device, version);
  83. MMKVInfo("Apple Device:%d, version:%d", device, version);
  84. g_rootDir = defaultRootDir;
  85. mkPath(g_rootDir);
  86. MMKVInfo("default root dir: " MMKV_PATH_FORMAT, g_rootDir.c_str());
  87. }
  88. # ifdef MMKV_IOS
  89. static bool g_isInBackground = false;
  90. void MMKV::setIsInBackground(bool isInBackground) {
  91. SCOPED_LOCK(g_instanceLock);
  92. g_isInBackground = isInBackground;
  93. MMKVInfo("g_isInBackground:%d", g_isInBackground);
  94. }
  95. bool MMKV::isInBackground() {
  96. SCOPED_LOCK(g_instanceLock);
  97. return g_isInBackground;
  98. }
  99. pair<bool, MLockPtr> guardForBackgroundWriting(void *ptr, size_t size) {
  100. if (g_isInBackground) {
  101. MLockPtr mlockPtr(ptr, size);
  102. return make_pair(mlockPtr.isLocked(), std::move(mlockPtr));
  103. } else {
  104. return make_pair(true, MLockPtr(nullptr, 0));
  105. }
  106. }
  107. # endif // MMKV_IOS
  108. bool MMKV::set(NSObject<NSCoding> *__unsafe_unretained obj, MMKVKey_t key) {
  109. return set(obj, key, m_expiredInSeconds);
  110. }
  111. bool MMKV::set(NSObject<NSCoding> *__unsafe_unretained obj, MMKVKey_t key, uint32_t expireDuration) {
  112. if (isKeyEmpty(key)) {
  113. return false;
  114. }
  115. if (!obj) {
  116. removeValueForKey(key);
  117. return true;
  118. }
  119. NSData *tmpData = nil;
  120. if ([obj isKindOfClass:NSString.class]) {
  121. auto str = (NSString *) obj;
  122. tmpData = [str dataUsingEncoding:NSUTF8StringEncoding];
  123. } else if ([obj isKindOfClass:NSData.class]) {
  124. tmpData = (NSData *) obj;
  125. }
  126. if (tmpData) {
  127. // delay write the size needed for encoding tmpData
  128. // avoid memory copying
  129. if (likely(!m_enableKeyExpire)) {
  130. return setDataForKey(MMBuffer(tmpData, MMBufferNoCopy), key, true);
  131. } else {
  132. MMBuffer data(tmpData, MMBufferNoCopy);
  133. if (data.length() > 0) {
  134. auto tmp = MMBuffer(pbMMBufferSize(data) + Fixed32Size);
  135. CodedOutputData output(tmp.getPtr(), tmp.length());
  136. output.writeData(data);
  137. auto time = (expireDuration != 0) ? getCurrentTimeInSecond() + expireDuration : 0;
  138. output.writeRawLittleEndian32(UInt32ToInt32(time));
  139. data = std::move(tmp);
  140. }
  141. return setDataForKey(std::move(data), key);
  142. }
  143. } else if ([obj isKindOfClass:NSDate.class]) {
  144. NSDate *oDate = (NSDate *) obj;
  145. double time = oDate.timeIntervalSince1970;
  146. return set(time, key, expireDuration);
  147. } else {
  148. /*if ([object conformsToProtocol:@protocol(NSCoding)])*/ {
  149. @try {
  150. NSError *error = nil;
  151. auto archived = [NSKeyedArchiver archivedDataWithRootObject:obj requiringSecureCoding:NO error:&error];
  152. if (error) {
  153. MMKVError("fail to archive: %@", error);
  154. return false;
  155. }
  156. if (archived.length > 0) {
  157. if (likely(!m_enableKeyExpire)) {
  158. return setDataForKey(MMBuffer(archived, MMBufferNoCopy), key);
  159. } else {
  160. MMBuffer data(archived, MMBufferNoCopy);
  161. if (data.length() > 0) {
  162. auto tmp = MMBuffer(data.length() + Fixed32Size);
  163. CodedOutputData output(tmp.getPtr(), tmp.length());
  164. output.writeRawData(data); // NSKeyedArchiver has its own size management
  165. auto time = (expireDuration != 0) ? getCurrentTimeInSecond() + expireDuration : 0;
  166. output.writeRawLittleEndian32(UInt32ToInt32(time));
  167. data = std::move(tmp);
  168. }
  169. return setDataForKey(std::move(data), key);
  170. }
  171. }
  172. } @catch (NSException *exception) {
  173. MMKVError("exception: %@", exception.reason);
  174. }
  175. }
  176. }
  177. return false;
  178. }
  179. static id unSecureUnArchiveObjectWithData(NSData *data) {
  180. @try {
  181. NSError *error = nil;
  182. auto unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:&error];
  183. if (error) {
  184. MMKVError("fail to init unarchiver %@", error);
  185. return nil;
  186. }
  187. unarchiver.requiresSecureCoding = NO;
  188. id result = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey];
  189. [unarchiver release];
  190. return result;
  191. } @catch (NSException *exception) {
  192. MMKVError("exception: %@", exception.reason);
  193. }
  194. return nil;
  195. }
  196. NSObject *MMKV::getObject(MMKVKey_t key, Class cls) {
  197. if (isKeyEmpty(key) || !cls) {
  198. return nil;
  199. }
  200. SCOPED_LOCK(m_lock);
  201. SCOPED_LOCK(m_sharedProcessLock);
  202. auto data = getDataForKey(key);
  203. if (data.length() > 0) {
  204. if (MiniPBCoder::isCompatibleClass(cls)) {
  205. try {
  206. auto result = MiniPBCoder::decodeObject(data, cls);
  207. return result;
  208. } catch (std::exception &exception) {
  209. MMKVError("%s", exception.what());
  210. }
  211. } else {
  212. if ([cls conformsToProtocol:@protocol(NSCoding)]) {
  213. auto tmp = [NSData dataWithBytesNoCopy:data.getPtr() length:data.length() freeWhenDone:NO];
  214. return unSecureUnArchiveObjectWithData(tmp);
  215. }
  216. }
  217. }
  218. return nil;
  219. }
  220. # ifndef MMKV_DISABLE_CRYPT
  221. pair<bool, KeyValueHolder>
  222. MMKV::appendDataWithKey(const MMBuffer &data, MMKVKey_t key, const KeyValueHolderCrypt &kvHolder, bool isDataHolder) {
  223. if (kvHolder.type != KeyValueHolderType_Offset) {
  224. return appendDataWithKey(data, key, isDataHolder);
  225. }
  226. SCOPED_LOCK(m_exclusiveProcessLock);
  227. uint32_t keyLength = kvHolder.keySize;
  228. // size needed to encode the key
  229. size_t rawKeySize = keyLength + pbRawVarint32Size(keyLength);
  230. auto basePtr = (uint8_t *) m_file->getMemory() + Fixed32Size;
  231. MMBuffer keyData(rawKeySize);
  232. AESCrypt decrypter = m_crypter->cloneWithStatus(kvHolder.cryptStatus);
  233. decrypter.decrypt(basePtr + kvHolder.offset, keyData.getPtr(), rawKeySize);
  234. return doAppendDataWithKey(data, keyData, isDataHolder, keyLength);
  235. }
  236. # endif
  237. NSArray *MMKV::allKeys(bool filterExpire) {
  238. SCOPED_LOCK(m_lock);
  239. checkLoadData();
  240. if (unlikely(filterExpire && m_enableKeyExpire)) {
  241. SCOPED_LOCK(m_exclusiveProcessLock);
  242. fullWriteback(nullptr, true);
  243. }
  244. NSMutableArray *keys = [NSMutableArray array];
  245. if (m_crypter) {
  246. for (const auto &pair : *m_dicCrypt) {
  247. [keys addObject:pair.first];
  248. }
  249. } else {
  250. for (const auto &pair : *m_dic) {
  251. [keys addObject:pair.first];
  252. }
  253. }
  254. return keys;
  255. }
  256. void MMKV::removeValuesForKeys(NSArray *arrKeys) {
  257. if (arrKeys.count == 0) {
  258. return;
  259. }
  260. if (arrKeys.count == 1) {
  261. return removeValueForKey(arrKeys[0]);
  262. }
  263. SCOPED_LOCK(m_lock);
  264. SCOPED_LOCK(m_exclusiveProcessLock);
  265. checkLoadData();
  266. size_t deleteCount = 0;
  267. if (m_crypter) {
  268. for (NSString *key in arrKeys) {
  269. auto itr = m_dicCrypt->find(key);
  270. if (itr != m_dicCrypt->end()) {
  271. auto oldKey = itr->first;
  272. m_dicCrypt->erase(itr);
  273. [oldKey release];
  274. deleteCount++;
  275. }
  276. }
  277. } else {
  278. for (NSString *key in arrKeys) {
  279. auto itr = m_dic->find(key);
  280. if (itr != m_dic->end()) {
  281. auto oldKey = itr->first;
  282. m_dic->erase(itr);
  283. [oldKey release];
  284. deleteCount++;
  285. }
  286. }
  287. }
  288. if (deleteCount > 0) {
  289. m_hasFullWriteback = false;
  290. fullWriteback();
  291. }
  292. }
  293. void MMKV::enumerateKeys(EnumerateBlock block) {
  294. if (block == nil) {
  295. return;
  296. }
  297. SCOPED_LOCK(m_lock);
  298. checkLoadData();
  299. MMKVInfo("enumerate [%s] begin", m_mmapID.c_str());
  300. if (m_crypter) {
  301. for (const auto &pair : *m_dicCrypt) {
  302. BOOL stop = NO;
  303. block(pair.first, &stop);
  304. if (stop) {
  305. break;
  306. }
  307. }
  308. } else {
  309. for (const auto &pair : *m_dic) {
  310. BOOL stop = NO;
  311. block(pair.first, &stop);
  312. if (stop) {
  313. break;
  314. }
  315. }
  316. }
  317. MMKVInfo("enumerate [%s] finish", m_mmapID.c_str());
  318. }
  319. MMKV_NAMESPACE_END
  320. # include <sys/sysctl.h>
  321. static void GetAppleMachineInfo(int &device, int &version) {
  322. device = UnKnown;
  323. version = 0;
  324. # if 0
  325. struct utsname systemInfo = {};
  326. uname(&systemInfo);
  327. std::string machine(systemInfo.machine);
  328. # else
  329. size_t size;
  330. sysctlbyname("hw.machine", nullptr, &size, nullptr, 0);
  331. char *answer = (char *) malloc(size);
  332. sysctlbyname("hw.machine", answer, &size, nullptr, 0);
  333. std::string machine(answer);
  334. free(answer);
  335. # endif
  336. if (machine.find("PowerMac") != std::string::npos || machine.find("Power Macintosh") != std::string::npos) {
  337. device = PowerMac;
  338. } else if (machine.find("Mac") != std::string::npos || machine.find("Macintosh") != std::string::npos) {
  339. device = Mac;
  340. } else if (machine.find("iPhone") != std::string::npos) {
  341. device = iPhone;
  342. } else if (machine.find("iPod") != std::string::npos) {
  343. device = iPod;
  344. } else if (machine.find("iPad") != std::string::npos) {
  345. device = iPad;
  346. } else if (machine.find("AppleTV") != std::string::npos) {
  347. device = AppleTV;
  348. } else if (machine.find("AppleWatch") != std::string::npos) {
  349. device = AppleWatch;
  350. }
  351. auto pos = machine.find_first_of("0123456789");
  352. if (pos != std::string::npos) {
  353. version = std::atoi(machine.substr(pos).c_str());
  354. }
  355. }
  356. #endif // MMKV_APPLE