MMKV_OSX.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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(), 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. if (isKeyEmpty(key)) {
  110. return false;
  111. }
  112. if (!obj) {
  113. removeValueForKey(key);
  114. return true;
  115. }
  116. NSData *tmpData = nil;
  117. if ([obj isKindOfClass:NSString.class]) {
  118. auto str = (NSString *) obj;
  119. tmpData = [str dataUsingEncoding:NSUTF8StringEncoding];
  120. } else if ([obj isKindOfClass:NSData.class]) {
  121. tmpData = (NSData *) obj;
  122. }
  123. if (tmpData) {
  124. // delay write the size needed for encoding tmpData
  125. // avoid memory copying
  126. return setDataForKey(MMBuffer(tmpData, MMBufferNoCopy), key, true);
  127. } else if ([obj isKindOfClass:NSDate.class]) {
  128. NSDate *oDate = (NSDate *) obj;
  129. double time = oDate.timeIntervalSince1970;
  130. return set(time, key);
  131. } else {
  132. /*if ([object conformsToProtocol:@protocol(NSCoding)])*/ {
  133. auto tmp = [NSKeyedArchiver archivedDataWithRootObject:obj];
  134. if (tmp.length > 0) {
  135. return setDataForKey(MMBuffer(tmp, MMBufferNoCopy), key);
  136. }
  137. }
  138. }
  139. return false;
  140. }
  141. NSObject *MMKV::getObject(MMKVKey_t key, Class cls) {
  142. if (isKeyEmpty(key) || !cls) {
  143. return nil;
  144. }
  145. SCOPED_LOCK(m_lock);
  146. SCOPED_LOCK(m_sharedProcessLock);
  147. auto data = getDataForKey(key);
  148. if (data.length() > 0) {
  149. if (MiniPBCoder::isCompatibleClass(cls)) {
  150. try {
  151. auto result = MiniPBCoder::decodeObject(data, cls);
  152. return result;
  153. } catch (std::exception &exception) {
  154. MMKVError("%s", exception.what());
  155. }
  156. } else {
  157. if ([cls conformsToProtocol:@protocol(NSCoding)]) {
  158. auto tmp = [NSData dataWithBytesNoCopy:data.getPtr() length:data.length() freeWhenDone:NO];
  159. try {
  160. id result = [NSKeyedUnarchiver unarchiveObjectWithData:tmp];
  161. return result;
  162. } catch (NSException *exception) {
  163. MMKVError("%s", exception.reason);
  164. }
  165. }
  166. }
  167. }
  168. return nil;
  169. }
  170. # ifndef MMKV_DISABLE_CRYPT
  171. constexpr uint32_t Fixed32Size = pbFixed32Size();
  172. pair<bool, KeyValueHolder>
  173. MMKV::appendDataWithKey(const MMBuffer &data, MMKVKey_t key, const KeyValueHolderCrypt &kvHolder, bool isDataHolder) {
  174. if (kvHolder.type != KeyValueHolderType_Offset) {
  175. return appendDataWithKey(data, key, isDataHolder);
  176. }
  177. SCOPED_LOCK(m_exclusiveProcessLock);
  178. uint32_t keyLength = kvHolder.keySize;
  179. // size needed to encode the key
  180. size_t rawKeySize = keyLength + pbRawVarint32Size(keyLength);
  181. auto basePtr = (uint8_t *) m_file->getMemory() + Fixed32Size;
  182. MMBuffer keyData(rawKeySize);
  183. AESCrypt decrypter = m_crypter->cloneWithStatus(kvHolder.cryptStatus);
  184. decrypter.decrypt(basePtr + kvHolder.offset, keyData.getPtr(), rawKeySize);
  185. return doAppendDataWithKey(data, keyData, isDataHolder, keyLength);
  186. }
  187. # endif
  188. NSArray *MMKV::allKeys() {
  189. SCOPED_LOCK(m_lock);
  190. checkLoadData();
  191. NSMutableArray *keys = [NSMutableArray array];
  192. if (m_crypter) {
  193. for (const auto &pair : *m_dicCrypt) {
  194. [keys addObject:pair.first];
  195. }
  196. } else {
  197. for (const auto &pair : *m_dic) {
  198. [keys addObject:pair.first];
  199. }
  200. }
  201. return keys;
  202. }
  203. void MMKV::removeValuesForKeys(NSArray *arrKeys) {
  204. if (arrKeys.count == 0) {
  205. return;
  206. }
  207. if (arrKeys.count == 1) {
  208. return removeValueForKey(arrKeys[0]);
  209. }
  210. SCOPED_LOCK(m_lock);
  211. SCOPED_LOCK(m_exclusiveProcessLock);
  212. checkLoadData();
  213. size_t deleteCount = 0;
  214. if (m_crypter) {
  215. for (NSString *key in arrKeys) {
  216. auto itr = m_dicCrypt->find(key);
  217. if (itr != m_dicCrypt->end()) {
  218. auto oldKey = itr->first;
  219. m_dicCrypt->erase(itr);
  220. [oldKey release];
  221. deleteCount++;
  222. }
  223. }
  224. } else {
  225. for (NSString *key in arrKeys) {
  226. auto itr = m_dic->find(key);
  227. if (itr != m_dic->end()) {
  228. auto oldKey = itr->first;
  229. m_dic->erase(itr);
  230. [oldKey release];
  231. deleteCount++;
  232. }
  233. }
  234. }
  235. if (deleteCount > 0) {
  236. m_hasFullWriteback = false;
  237. fullWriteback();
  238. }
  239. }
  240. void MMKV::enumerateKeys(EnumerateBlock block) {
  241. if (block == nil) {
  242. return;
  243. }
  244. SCOPED_LOCK(m_lock);
  245. checkLoadData();
  246. MMKVInfo("enumerate [%s] begin", m_mmapID.c_str());
  247. if (m_crypter) {
  248. for (const auto &pair : *m_dicCrypt) {
  249. BOOL stop = NO;
  250. block(pair.first, &stop);
  251. if (stop) {
  252. break;
  253. }
  254. }
  255. } else {
  256. for (const auto &pair : *m_dic) {
  257. BOOL stop = NO;
  258. block(pair.first, &stop);
  259. if (stop) {
  260. break;
  261. }
  262. }
  263. }
  264. MMKVInfo("enumerate [%s] finish", m_mmapID.c_str());
  265. }
  266. MMKV_NAMESPACE_END
  267. # include <sys/sysctl.h>
  268. static void GetAppleMachineInfo(int &device, int &version) {
  269. device = UnKnown;
  270. version = 0;
  271. # if 0
  272. struct utsname systemInfo = {};
  273. uname(&systemInfo);
  274. std::string machine(systemInfo.machine);
  275. # else
  276. size_t size;
  277. sysctlbyname("hw.machine", nullptr, &size, nullptr, 0);
  278. char *answer = (char *) malloc(size);
  279. sysctlbyname("hw.machine", answer, &size, nullptr, 0);
  280. std::string machine(answer);
  281. free(answer);
  282. # endif
  283. if (machine.find("PowerMac") != std::string::npos || machine.find("Power Macintosh") != std::string::npos) {
  284. device = PowerMac;
  285. } else if (machine.find("Mac") != std::string::npos || machine.find("Macintosh") != std::string::npos) {
  286. device = Mac;
  287. } else if (machine.find("iPhone") != std::string::npos) {
  288. device = iPhone;
  289. } else if (machine.find("iPod") != std::string::npos) {
  290. device = iPod;
  291. } else if (machine.find("iPad") != std::string::npos) {
  292. device = iPad;
  293. } else if (machine.find("AppleTV") != std::string::npos) {
  294. device = AppleTV;
  295. } else if (machine.find("AppleWatch") != std::string::npos) {
  296. device = AppleWatch;
  297. }
  298. auto pos = machine.find_first_of("0123456789");
  299. if (pos != std::string::npos) {
  300. version = std::atoi(machine.substr(pos).c_str());
  301. }
  302. }
  303. #endif // MMKV_APPLE