MemoryFile_OSX.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 "MemoryFile.h"
  21. #include "MMKVLog.h"
  22. #ifdef MMKV_IOS
  23. using namespace std;
  24. namespace mmkv {
  25. void tryResetFileProtection(const string &path) {
  26. @autoreleasepool {
  27. NSString *nsPath = [NSString stringWithUTF8String:path.c_str()];
  28. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:nsPath error:nullptr];
  29. NSString *protection = [attr valueForKey:NSFileProtectionKey];
  30. MMKVInfo("protection on [%@] is %@", nsPath, protection);
  31. if ([protection isEqualToString:NSFileProtectionCompleteUntilFirstUserAuthentication] == NO) {
  32. NSMutableDictionary *newAttr = [NSMutableDictionary dictionaryWithDictionary:attr];
  33. [newAttr setObject:NSFileProtectionCompleteUntilFirstUserAuthentication forKey:NSFileProtectionKey];
  34. NSError *err = nil;
  35. [[NSFileManager defaultManager] setAttributes:newAttr ofItemAtPath:nsPath error:&err];
  36. if (err != nil) {
  37. MMKVError("fail to set attribute %@ on [%@]: %@", NSFileProtectionCompleteUntilFirstUserAuthentication,
  38. nsPath, err);
  39. }
  40. }
  41. }
  42. }
  43. } // namespace mmkv
  44. #endif // MMKV_IOS
  45. #ifdef MMKV_APPLE
  46. #include <copyfile.h>
  47. #include <unistd.h>
  48. namespace mmkv {
  49. bool tryAtomicRename(const char *src, const char *dst) {
  50. if (!src || !dst) {
  51. return false;
  52. }
  53. bool renamed = false;
  54. // try atomic swap first
  55. if (@available(iOS 10.0, watchOS 3.0, macOS 10.12, *)) {
  56. // renameat2() equivalent
  57. if (renamex_np(src, dst, RENAME_SWAP) == 0) {
  58. renamed = true;
  59. if (strcmp(src, dst) != 0) {
  60. ::unlink(src);
  61. }
  62. } else if (errno != ENOENT) {
  63. MMKVError("fail to renamex_np %s to %s, %s", src, dst, strerror(errno));
  64. }
  65. }
  66. if (!renamed) {
  67. // try old style rename
  68. if (rename(src, dst) != 0) {
  69. MMKVError("fail to rename %s to %s, %s", src, dst, strerror(errno));
  70. return false;
  71. }
  72. }
  73. return true;
  74. }
  75. bool copyFile(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  76. // prepare a temp file for atomic rename, avoid data corruption of suddent crash
  77. NSString *uniqueFileName = [NSString stringWithFormat:@"mmkv_%zu", (size_t) NSDate.timeIntervalSinceReferenceDate];
  78. NSString *tmpFile = [NSTemporaryDirectory() stringByAppendingPathComponent:uniqueFileName];
  79. if (copyfile(srcPath.c_str(), tmpFile.UTF8String, nullptr, COPYFILE_UNLINK | COPYFILE_CLONE) != 0) {
  80. MMKVError("fail to copyfile [%s] to [%s], %s", srcPath.c_str(), tmpFile.UTF8String, strerror(errno));
  81. return false;
  82. }
  83. MMKVInfo("copyfile [%s] to [%s]", srcPath.c_str(), tmpFile.UTF8String);
  84. if (tryAtomicRename(tmpFile.UTF8String, dstPath.c_str())) {
  85. MMKVInfo("copyfile [%s] to [%s] finish.", srcPath.c_str(), dstPath.c_str());
  86. return true;
  87. }
  88. MMKVInfo("rename fail, try copy file content instead.");
  89. auto ret = copyFileContent(tmpFile.UTF8String, dstPath);
  90. unlink(tmpFile.UTF8String);
  91. return ret;
  92. }
  93. bool copyFileContent(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  94. File dstFile(dstPath, OpenFlag::WriteOnly | OpenFlag::Create | OpenFlag::Truncate);
  95. if (!dstFile.isFileValid()) {
  96. return false;
  97. }
  98. if (copyFileContent(srcPath, dstFile.getFd())) {
  99. MMKVInfo("copy content from %s to fd[%s] finish", srcPath.c_str(), dstPath.c_str());
  100. return true;
  101. }
  102. MMKVError("fail to copyfile(): target file %s", dstPath.c_str());
  103. return false;
  104. }
  105. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD) {
  106. if (dstFD < 0) {
  107. return false;
  108. }
  109. File srcFile(srcPath, OpenFlag::ReadOnly);
  110. if (!srcFile.isFileValid()) {
  111. return false;
  112. }
  113. // sendfile() equivalent
  114. if (::fcopyfile(srcFile.getFd(), dstFD, nullptr, COPYFILE_ALL) == 0) {
  115. MMKVInfo("copy content from %s to fd[%d] finish", srcPath.c_str(), dstFD);
  116. return true;
  117. }
  118. MMKVError("fail to copyfile(): %d(%s), source file %s", errno, strerror(errno), srcPath.c_str());
  119. return false;
  120. }
  121. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD, bool needTruncate) {
  122. return copyFileContent(srcPath, dstFD);
  123. }
  124. bool isDiskOfMMAPFileCorrupted(MemoryFile *file, bool &needReportReadFail) {
  125. uint32_t info;
  126. auto fd = file->getFd();
  127. auto path = file->getPath().c_str();
  128. auto oldPos = lseek(fd, 0, SEEK_CUR);
  129. lseek(fd, 0, SEEK_SET);
  130. auto size = read(fd, &info, sizeof(info));
  131. auto err = errno;
  132. lseek(fd, oldPos, SEEK_SET);
  133. if (size <= 0) {
  134. needReportReadFail = true;
  135. MMKVError("fail to read [%s] from fd [%d], errno: %d (%s)", path, fd, err, strerror(err));
  136. if (err == EDEVERR || err == EILSEQ || err == EINVAL || err == ENXIO) {
  137. MMKVWarning("file fail to read, consider it illegal, delete now: [%s]", path);
  138. return true;
  139. }
  140. }
  141. file->cleanMayflyFD();
  142. return false;
  143. }
  144. } // namespace mmkv
  145. #endif // MMKV_APPLE