MemoryFile.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 "MemoryFile.h"
  21. #ifndef MMKV_WIN32
  22. # include "InterProcessLock.h"
  23. # include "MMBuffer.h"
  24. # include "MMKVLog.h"
  25. # include "ScopedLock.hpp"
  26. # include <cerrno>
  27. # include <utility>
  28. # include <fcntl.h>
  29. # include <sys/mman.h>
  30. # include <sys/stat.h>
  31. # include <unistd.h>
  32. # include <sys/file.h>
  33. # include <dirent.h>
  34. # include <cstring>
  35. using namespace std;
  36. namespace mmkv {
  37. extern bool getFileSize(int fd, size_t &size);
  38. # ifdef MMKV_ANDROID
  39. extern size_t ASharedMemory_getSize(int fd);
  40. # else
  41. File::File(MMKVPath_t path, OpenFlag flag) : m_path(std::move(path)), m_fd(-1), m_flag(flag) {
  42. open();
  43. }
  44. MemoryFile::MemoryFile(MMKVPath_t path) : m_diskFile(std::move(path), OpenFlag::ReadWrite | OpenFlag::Create), m_ptr(nullptr), m_size(0) {
  45. reloadFromFile();
  46. }
  47. # endif // !defined(MMKV_ANDROID)
  48. # ifdef MMKV_IOS
  49. void tryResetFileProtection(const string &path);
  50. # endif
  51. static int OpenFlag2NativeFlag(OpenFlag flag) {
  52. int native = O_CLOEXEC;
  53. if (flag & OpenFlag::ReadWrite) {
  54. native |= O_RDWR;
  55. } else if (flag & OpenFlag::ReadOnly) {
  56. native |= O_RDONLY;
  57. } else if (flag & OpenFlag::WriteOnly) {
  58. native |= O_WRONLY;
  59. }
  60. if (flag & OpenFlag::Create) {
  61. native |= O_CREAT;
  62. }
  63. if (flag & OpenFlag::Excel) {
  64. native |= O_EXCL;
  65. }
  66. if (flag & OpenFlag::Truncate) {
  67. native |= O_TRUNC;
  68. }
  69. return native;
  70. }
  71. bool File::open() {
  72. # ifdef MMKV_ANDROID
  73. if (m_fileType == MMFILE_TYPE_ASHMEM) {
  74. return isFileValid();
  75. }
  76. # endif
  77. if (isFileValid()) {
  78. return true;
  79. }
  80. m_fd = ::open(m_path.c_str(), OpenFlag2NativeFlag(m_flag), S_IRWXU);
  81. if (!isFileValid()) {
  82. MMKVError("fail to open [%s], %d(%s)", m_path.c_str(), errno, strerror(errno));
  83. return false;
  84. }
  85. MMKVInfo("open fd[%p], %s", m_fd, m_path.c_str());
  86. return true;
  87. }
  88. void File::close() {
  89. if (isFileValid()) {
  90. MMKVInfo("closing fd[%p], %s", m_fd, m_path.c_str());
  91. if (::close(m_fd) == 0) {
  92. m_fd = -1;
  93. } else {
  94. MMKVError("fail to close [%s], %d(%s)", m_path.c_str(), errno, strerror(errno));
  95. }
  96. }
  97. }
  98. size_t File::getActualFileSize() const {
  99. # ifdef MMKV_ANDROID
  100. if (m_fileType == MMFILE_TYPE_ASHMEM) {
  101. return ASharedMemory_getSize(m_fd);
  102. }
  103. # endif
  104. size_t size = 0;
  105. mmkv::getFileSize(m_fd, size);
  106. return size;
  107. }
  108. bool MemoryFile::truncate(size_t size) {
  109. if (!m_diskFile.isFileValid()) {
  110. return false;
  111. }
  112. if (size == m_size) {
  113. return true;
  114. }
  115. # ifdef MMKV_ANDROID
  116. if (m_diskFile.m_fileType == MMFILE_TYPE_ASHMEM) {
  117. if (size > m_size) {
  118. MMKVError("ashmem %s reach size limit:%zu, consider configure with larger size", m_diskFile.m_path.c_str(), m_size);
  119. } else {
  120. MMKVInfo("no way to trim ashmem %s from %zu to smaller size %zu", m_diskFile.m_path.c_str(), m_size, size);
  121. }
  122. return false;
  123. }
  124. # endif // MMKV_ANDROID
  125. auto oldSize = m_size;
  126. m_size = size;
  127. // round up to (n * pagesize)
  128. if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
  129. m_size = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
  130. }
  131. if (::ftruncate(m_diskFile.m_fd, static_cast<off_t>(m_size)) != 0) {
  132. MMKVError("fail to truncate [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno));
  133. m_size = oldSize;
  134. return false;
  135. }
  136. if (m_size > oldSize) {
  137. if (!zeroFillFile(m_diskFile.m_fd, oldSize, m_size - oldSize)) {
  138. MMKVError("fail to zeroFile [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno));
  139. m_size = oldSize;
  140. return false;
  141. }
  142. }
  143. if (m_ptr) {
  144. if (munmap(m_ptr, oldSize) != 0) {
  145. MMKVError("fail to munmap [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  146. }
  147. }
  148. auto ret = mmap();
  149. if (!ret) {
  150. doCleanMemoryCache(true);
  151. }
  152. return ret;
  153. }
  154. bool MemoryFile::msync(SyncFlag syncFlag) {
  155. if (m_ptr) {
  156. auto ret = ::msync(m_ptr, m_size, syncFlag ? MS_SYNC : MS_ASYNC);
  157. if (ret == 0) {
  158. return true;
  159. }
  160. MMKVError("fail to msync [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  161. }
  162. return false;
  163. }
  164. bool MemoryFile::mmap() {
  165. m_ptr = (char *) ::mmap(m_ptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_diskFile.m_fd, 0);
  166. if (m_ptr == MAP_FAILED) {
  167. MMKVError("fail to mmap [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  168. m_ptr = nullptr;
  169. return false;
  170. }
  171. return true;
  172. }
  173. void MemoryFile::reloadFromFile() {
  174. # ifdef MMKV_ANDROID
  175. if (m_fileType == MMFILE_TYPE_ASHMEM) {
  176. return;
  177. }
  178. # endif
  179. if (isFileValid()) {
  180. MMKVWarning("calling reloadFromFile while the cache [%s] is still valid", m_diskFile.m_path.c_str());
  181. MMKV_ASSERT(0);
  182. doCleanMemoryCache(false);
  183. }
  184. if (!m_diskFile.open()) {
  185. MMKVError("fail to open:%s, %s", m_diskFile.m_path.c_str(), strerror(errno));
  186. } else {
  187. FileLock fileLock(m_diskFile.m_fd);
  188. InterProcessLock lock(&fileLock, ExclusiveLockType);
  189. SCOPED_LOCK(&lock);
  190. mmkv::getFileSize(m_diskFile.m_fd, m_size);
  191. // round up to (n * pagesize)
  192. if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
  193. size_t roundSize = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
  194. truncate(roundSize);
  195. } else {
  196. auto ret = mmap();
  197. if (!ret) {
  198. doCleanMemoryCache(true);
  199. }
  200. }
  201. # ifdef MMKV_IOS
  202. tryResetFileProtection(m_diskFile.m_path);
  203. # endif
  204. }
  205. }
  206. void MemoryFile::doCleanMemoryCache(bool forceClean) {
  207. # ifdef MMKV_ANDROID
  208. if (m_diskFile.m_fileType == MMFILE_TYPE_ASHMEM && !forceClean) {
  209. return;
  210. }
  211. # endif
  212. if (m_ptr && m_ptr != MAP_FAILED) {
  213. if (munmap(m_ptr, m_size) != 0) {
  214. MMKVError("fail to munmap [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  215. }
  216. }
  217. m_ptr = nullptr;
  218. m_diskFile.close();
  219. m_size = 0;
  220. }
  221. bool isFileExist(const string &nsFilePath) {
  222. if (nsFilePath.empty()) {
  223. return false;
  224. }
  225. struct stat temp = {};
  226. return lstat(nsFilePath.c_str(), &temp) == 0;
  227. }
  228. extern bool mkPath(const MMKVPath_t &str) {
  229. char *path = strdup(str.c_str());
  230. struct stat sb = {};
  231. bool done = false;
  232. char *slash = path;
  233. while (!done) {
  234. slash += strspn(slash, "/");
  235. slash += strcspn(slash, "/");
  236. done = (*slash == '\0');
  237. *slash = '\0';
  238. if (stat(path, &sb) != 0) {
  239. if (errno != ENOENT || mkdir(path, 0777) != 0) {
  240. MMKVWarning("%s : %s", path, strerror(errno));
  241. // there's report that some Android devices might not have access permission on parent dir
  242. if (done) {
  243. free(path);
  244. return false;
  245. }
  246. goto LContinue;
  247. }
  248. } else if (!S_ISDIR(sb.st_mode)) {
  249. MMKVWarning("%s: %s", path, strerror(ENOTDIR));
  250. free(path);
  251. return false;
  252. }
  253. LContinue:
  254. *slash = '/';
  255. }
  256. free(path);
  257. return true;
  258. }
  259. MMBuffer *readWholeFile(const MMKVPath_t &path) {
  260. MMBuffer *buffer = nullptr;
  261. int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
  262. if (fd >= 0) {
  263. auto fileLength = lseek(fd, 0, SEEK_END);
  264. if (fileLength > 0) {
  265. buffer = new MMBuffer(static_cast<size_t>(fileLength));
  266. lseek(fd, 0, SEEK_SET);
  267. auto readSize = read(fd, buffer->getPtr(), static_cast<size_t>(fileLength));
  268. if (readSize != -1) {
  269. //fileSize = readSize;
  270. } else {
  271. MMKVWarning("fail to read %s: %s", path.c_str(), strerror(errno));
  272. delete buffer;
  273. buffer = nullptr;
  274. }
  275. }
  276. close(fd);
  277. } else {
  278. MMKVWarning("fail to open %s: %s", path.c_str(), strerror(errno));
  279. }
  280. return buffer;
  281. }
  282. bool zeroFillFile(int fd, size_t startPos, size_t size) {
  283. if (fd < 0) {
  284. return false;
  285. }
  286. if (lseek(fd, static_cast<off_t>(startPos), SEEK_SET) < 0) {
  287. MMKVError("fail to lseek fd[%d], error:%s", fd, strerror(errno));
  288. return false;
  289. }
  290. static const char zeros[4096] = {};
  291. while (size >= sizeof(zeros)) {
  292. if (write(fd, zeros, sizeof(zeros)) < 0) {
  293. MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
  294. return false;
  295. }
  296. size -= sizeof(zeros);
  297. }
  298. if (size > 0) {
  299. if (write(fd, zeros, size) < 0) {
  300. MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
  301. return false;
  302. }
  303. }
  304. return true;
  305. }
  306. bool getFileSize(int fd, size_t &size) {
  307. struct stat st = {};
  308. if (fstat(fd, &st) != -1) {
  309. size = (size_t) st.st_size;
  310. return true;
  311. }
  312. return false;
  313. }
  314. size_t getPageSize() {
  315. return static_cast<size_t>(getpagesize());
  316. }
  317. #ifndef MMKV_APPLE
  318. static pair<MMKVPath_t, int> createUniqueTempFile(const char *prefix) {
  319. char path[PATH_MAX];
  320. #ifdef MMKV_ANDROID
  321. snprintf(path, PATH_MAX, "%s/%s.XXXXXX", g_android_tmpDir.c_str(), prefix);
  322. #else
  323. snprintf(path, PATH_MAX, "%s/%s.XXXXXX", P_tmpdir, prefix);
  324. #endif
  325. auto fd = mkstemp(path);
  326. if (fd < 0) {
  327. MMKVError("fail to create unique temp file [%s], %d(%s)", path, errno, strerror(errno));
  328. return {"", fd};
  329. }
  330. MMKVDebug("create unique temp file [%s] with fd[%d]", path, fd);
  331. return {MMKVPath_t(path), fd};
  332. }
  333. #if !defined(MMKV_ANDROID) && !defined(MMKV_LINUX)
  334. bool tryAtomicRename(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  335. if (::rename(srcPath.c_str(), dstPath.c_str()) != 0) {
  336. MMKVError("fail to rename [%s] to [%s], %d(%s)", srcPath.c_str(), dstPath.c_str(), errno, strerror(errno));
  337. return false;
  338. }
  339. return true;
  340. }
  341. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD, bool needTruncate) {
  342. if (dstFD < 0) {
  343. return false;
  344. }
  345. bool ret = false;
  346. File srcFile(srcPath, OpenFlag::ReadOnly);
  347. if (!srcFile.isFileValid()) {
  348. return false;
  349. }
  350. auto bufferSize = getPageSize();
  351. auto buffer = (char *) malloc(bufferSize);
  352. if (!buffer) {
  353. MMKVError("fail to malloc size %zu, %d(%s)", bufferSize, errno, strerror(errno));
  354. goto errorOut;
  355. }
  356. lseek(dstFD, 0, SEEK_SET);
  357. // the POSIX standard don't have sendfile()/fcopyfile() equivalent, do it the hard way
  358. while (true) {
  359. auto sizeRead = read(srcFile.getFd(), buffer, bufferSize);
  360. if (sizeRead < 0) {
  361. MMKVError("fail to read file [%s], %d(%s)", srcPath.c_str(), errno, strerror(errno));
  362. goto errorOut;
  363. }
  364. size_t totalWrite = 0;
  365. do {
  366. auto sizeWrite = write(dstFD, buffer + totalWrite, sizeRead - totalWrite);
  367. if (sizeWrite < 0) {
  368. MMKVError("fail to write fd [%d], %d(%s)", dstFD, errno, strerror(errno));
  369. goto errorOut;
  370. }
  371. totalWrite += sizeWrite;
  372. } while (totalWrite < sizeRead);
  373. if (sizeRead < bufferSize) {
  374. break;
  375. }
  376. }
  377. if (needTruncate) {
  378. size_t dstFileSize = 0;
  379. getFileSize(dstFD, dstFileSize);
  380. auto srcFileSize = srcFile.getActualFileSize();
  381. if ((dstFileSize != srcFileSize) && (::ftruncate(dstFD, static_cast<off_t>(srcFileSize)) != 0)) {
  382. MMKVError("fail to truncate [%d] to size [%zu], %d(%s)", dstFD, srcFileSize, errno, strerror(errno));
  383. goto errorOut;
  384. }
  385. }
  386. ret = true;
  387. MMKVInfo("copy content from %s to fd[%d] finish", srcPath.c_str(), dstFD);
  388. errorOut:
  389. free(buffer);
  390. return ret;
  391. }
  392. #endif // !defined(MMKV_ANDROID) && !defined(MMKV_LINUX)
  393. // copy to a temp file then rename it
  394. // this is the best we can do under the POSIX standard
  395. bool copyFile(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  396. auto pair = createUniqueTempFile("MMKV");
  397. auto tmpFD = pair.second;
  398. auto &tmpPath = pair.first;
  399. if (tmpFD < 0) {
  400. return false;
  401. }
  402. bool renamed = false;
  403. if (copyFileContent(srcPath, tmpFD, false)) {
  404. MMKVInfo("copyfile [%s] to [%s]", srcPath.c_str(), tmpPath.c_str());
  405. renamed = tryAtomicRename(tmpPath, dstPath);
  406. if (renamed) {
  407. MMKVInfo("copyfile [%s] to [%s] finish.", srcPath.c_str(), dstPath.c_str());
  408. }
  409. }
  410. ::close(tmpFD);
  411. if (!renamed) {
  412. ::unlink(tmpPath.c_str());
  413. }
  414. return renamed;
  415. }
  416. bool copyFileContent(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  417. File dstFile(dstPath, OpenFlag::WriteOnly | OpenFlag::Create | OpenFlag::Truncate);
  418. if (!dstFile.isFileValid()) {
  419. return false;
  420. }
  421. auto ret = copyFileContent(srcPath, dstFile.getFd(), false);
  422. if (!ret) {
  423. MMKVError("fail to copyfile(): target file %s", dstPath.c_str());
  424. } else {
  425. MMKVInfo("copy content from %s to [%s] finish", srcPath.c_str(), dstPath.c_str());
  426. }
  427. return ret;
  428. }
  429. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD) {
  430. return copyFileContent(srcPath, dstFD, true);
  431. }
  432. #endif // !defined(MMKV_APPLE)
  433. void walkInDir(const MMKVPath_t &dirPath, WalkType type, const function<void(const MMKVPath_t&, WalkType)> &walker) {
  434. auto folderPathStr = dirPath.data();
  435. DIR *dir = opendir(folderPathStr);
  436. if (!dir) {
  437. MMKVError("opendir failed: %d(%s), %s", errno, strerror(errno), dirPath.c_str());
  438. return;
  439. }
  440. char childPath[PATH_MAX];
  441. size_t folderPathLength = dirPath.size();
  442. strncpy(childPath, folderPathStr, folderPathLength + 1);
  443. if (folderPathStr[folderPathLength - 1] != '/') {
  444. childPath[folderPathLength] = '/';
  445. folderPathLength++;
  446. }
  447. while (auto child = readdir(dir)) {
  448. if ((child->d_type & DT_REG) && (type & WalkFile)) {
  449. #ifdef _DIRENT_HAVE_D_NAMLEN
  450. stpcpy(childPath + folderPathLength, child->d_name);
  451. childPath[folderPathLength + child->d_namlen] = 0;
  452. #else
  453. strcpy(childPath + folderPathLength, child->d_name);
  454. #endif
  455. walker(childPath, WalkFile);
  456. } else if ((child->d_type & DT_DIR) && (type & WalkFolder)) {
  457. #ifdef _DIRENT_HAVE_D_NAMLEN
  458. if ((child->d_namlen == 1 && child->d_name[0] == '.') ||
  459. (child->d_namlen == 2 && child->d_name[0] == '.' && child->d_name[1] == '.')) {
  460. continue;
  461. }
  462. stpcpy(childPath + folderPathLength, child->d_name);
  463. childPath[folderPathLength + child->d_namlen] = 0;
  464. #else
  465. if (strcmp(child->d_name, ".") == 0 || strcmp(child->d_name, "..") == 0) {
  466. continue;
  467. }
  468. strcpy(childPath + folderPathLength, child->d_name);
  469. #endif
  470. walker(childPath, WalkFolder);
  471. }
  472. }
  473. closedir(dir);
  474. }
  475. } // namespace mmkv
  476. #endif // !defined(MMKV_WIN32)