MemoryFile.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. # include <unistd.h>
  36. # include <filesystem>
  37. using namespace std;
  38. namespace fs = std::filesystem;
  39. namespace mmkv {
  40. static bool getFileSize(const char *path, size_t &size);
  41. # ifdef MMKV_ANDROID
  42. extern size_t ASharedMemory_getSize(int fd);
  43. # else
  44. File::File(MMKVPath_t path, OpenFlag flag) : m_path(std::move(path)), m_fd(-1), m_flag(flag) {
  45. open();
  46. }
  47. MemoryFile::MemoryFile(MMKVPath_t path, size_t expectedCapacity, bool readOnly, bool mayflyFD)
  48. : m_diskFile(std::move(path), readOnly ? OpenFlag::ReadOnly : (OpenFlag::ReadWrite | OpenFlag::Create))
  49. , m_ptr(nullptr), m_size(0), m_readOnly(readOnly), m_isMayflyFD(mayflyFD)
  50. {
  51. reloadFromFile(expectedCapacity);
  52. }
  53. # endif // !defined(MMKV_ANDROID)
  54. # ifdef MMKV_IOS
  55. void tryResetFileProtection(const string &path);
  56. # endif
  57. static int OpenFlag2NativeFlag(OpenFlag flag) {
  58. int native = O_CLOEXEC;
  59. if ((flag & OpenFlagRWMask) == OpenFlag::ReadWrite) {
  60. native |= O_RDWR;
  61. } else if (flag & OpenFlag::ReadOnly) {
  62. native |= O_RDONLY;
  63. } else if (flag & OpenFlag::WriteOnly) {
  64. native |= O_WRONLY;
  65. }
  66. if (flag & OpenFlag::Create) {
  67. native |= O_CREAT;
  68. }
  69. if (flag & OpenFlag::Excel) {
  70. native |= O_EXCL;
  71. }
  72. if (flag & OpenFlag::Truncate) {
  73. native |= O_TRUNC;
  74. }
  75. return native;
  76. }
  77. bool File::open() {
  78. # ifdef MMKV_ANDROID
  79. if (m_fileType == MMFILE_TYPE_ASHMEM) {
  80. return isFileValid();
  81. }
  82. # endif
  83. if (isFileValid()) {
  84. return true;
  85. }
  86. m_fd = ::open(m_path.c_str(), OpenFlag2NativeFlag(m_flag), S_IRWXU);
  87. if (!isFileValid()) {
  88. MMKVError("fail to open [%s], flag 0x%x, %d(%s)", m_path.c_str(), m_flag, errno, strerror(errno));
  89. return false;
  90. }
  91. MMKVInfo("open fd[%d], flag 0x%x, %s", m_fd, m_flag, m_path.c_str());
  92. return true;
  93. }
  94. void File::close() {
  95. if (isFileValid()) {
  96. MMKVInfo("closing fd[%d], %s", m_fd, m_path.c_str());
  97. if (::close(m_fd) == 0) {
  98. m_fd = -1;
  99. } else {
  100. MMKVError("fail to close [%s], %d(%s)", m_path.c_str(), errno, strerror(errno));
  101. }
  102. }
  103. }
  104. size_t File::getActualFileSize() const {
  105. # ifdef MMKV_ANDROID
  106. if (m_fileType == MMFILE_TYPE_ASHMEM) {
  107. return ASharedMemory_getSize(m_fd);
  108. }
  109. # endif
  110. size_t size = 0;
  111. if (isFileValid()) {
  112. mmkv::getFileSize(m_fd, size);
  113. } else {
  114. mmkv::getFileSize(m_path.c_str(), size);
  115. }
  116. return size;
  117. }
  118. bool MemoryFile::openIfNeeded() {
  119. if (!m_diskFile.isFileValid()) {
  120. return m_diskFile.open();
  121. }
  122. return true;
  123. }
  124. void MemoryFile::cleanMayflyFD() {
  125. if (m_isMayflyFD && m_diskFile.isFileValid()) {
  126. m_diskFile.close();
  127. }
  128. }
  129. size_t MemoryFile::getActualFileSize() {
  130. if (!m_isMayflyFD && !m_diskFile.isFileValid()) {
  131. return 0;
  132. }
  133. return m_diskFile.getActualFileSize();
  134. }
  135. MMKVFileHandle_t MemoryFile::getFd() {
  136. if (m_isMayflyFD) {
  137. openIfNeeded();
  138. }
  139. return m_diskFile.getFd();
  140. }
  141. bool MemoryFile::truncate(size_t size, FileLock *fileLock) {
  142. if (m_isMayflyFD) {
  143. openIfNeeded();
  144. }
  145. if (!m_diskFile.isFileValid()) {
  146. return false;
  147. }
  148. if (size == m_size) {
  149. return true;
  150. }
  151. if (m_readOnly) {
  152. // truncate readonly file not allow
  153. return false;
  154. }
  155. # ifdef MMKV_ANDROID
  156. if (m_diskFile.m_fileType == MMFILE_TYPE_ASHMEM) {
  157. if (size > m_size) {
  158. MMKVError("ashmem %s reach size limit:%zu, consider configure with larger size", m_diskFile.m_path.c_str(), m_size);
  159. } else {
  160. MMKVInfo("no way to trim ashmem %s from %zu to smaller size %zu", m_diskFile.m_path.c_str(), m_size, size);
  161. }
  162. return false;
  163. }
  164. # endif // MMKV_ANDROID
  165. auto oldSize = m_size;
  166. m_size = size;
  167. // round up to (n * pagesize)
  168. if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
  169. m_size = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
  170. }
  171. if (::ftruncate(m_diskFile.m_fd, static_cast<off_t>(m_size)) != 0) {
  172. MMKVError("fail to truncate [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno));
  173. m_size = oldSize;
  174. return false;
  175. }
  176. if (m_size > oldSize) {
  177. if (!zeroFillFile(m_diskFile.m_fd, oldSize, m_size - oldSize)) {
  178. MMKVError("fail to zeroFile [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno));
  179. m_size = oldSize;
  180. // redo ftruncate to its previous size
  181. int status = ::ftruncate(m_diskFile.m_fd, static_cast<off_t>(m_size));
  182. if (status != 0) {
  183. MMKVError("failed to truncate back [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno));
  184. } else {
  185. MMKVError("success to truncate [%s] back to size %zu", m_diskFile.m_path.c_str(), m_size);
  186. MMKVError("after truncate, file size = %zu", getActualFileSize());
  187. }
  188. return false;
  189. }
  190. }
  191. if (m_ptr) {
  192. if (munmap(m_ptr, oldSize) != 0) {
  193. MMKVError("fail to munmap [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  194. }
  195. }
  196. return mmapOrCleanup(fileLock);
  197. }
  198. bool MemoryFile::msync(SyncFlag syncFlag) {
  199. if (m_readOnly) {
  200. // there's no point in msync() readonly memory
  201. return true;
  202. }
  203. if (m_ptr) {
  204. auto ret = ::msync(m_ptr, m_size, syncFlag ? MS_SYNC : MS_ASYNC);
  205. if (ret == 0) {
  206. return true;
  207. }
  208. MMKVError("fail to msync [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  209. }
  210. return false;
  211. }
  212. bool MemoryFile::mmapOrCleanup(FileLock *fileLock) {
  213. auto oldPtr = m_ptr;
  214. auto mode = m_readOnly ? PROT_READ : (PROT_READ | PROT_WRITE);
  215. m_ptr = (char *) ::mmap(m_ptr, m_size, mode, MAP_SHARED, m_diskFile.m_fd, 0);
  216. if (m_ptr == MAP_FAILED) {
  217. MMKVError("fail to mmap [%s], mode 0x%x, %s", m_diskFile.m_path.c_str(), mode, strerror(errno));
  218. m_ptr = nullptr;
  219. doCleanMemoryCache(true);
  220. return false;
  221. }
  222. MMKVInfo("mmap to address [%p], oldPtr [%p], [%s]", m_ptr, oldPtr, m_diskFile.m_path.c_str());
  223. if (m_isMayflyFD && fileLock) {
  224. fileLock->destroyAndUnLock();
  225. }
  226. cleanMayflyFD();
  227. return true;
  228. }
  229. void MemoryFile::reloadFromFile(size_t expectedCapacity) {
  230. # ifdef MMKV_ANDROID
  231. if (m_fileType == MMFILE_TYPE_ASHMEM) {
  232. return;
  233. }
  234. # endif
  235. if (isFileValid()) {
  236. MMKVWarning("calling reloadFromFile while the cache [%s] is still valid", m_diskFile.m_path.c_str());
  237. MMKV_ASSERT(0);
  238. doCleanMemoryCache(false);
  239. }
  240. if (openIfNeeded()) {
  241. FileLock fileLock(m_diskFile.m_fd);
  242. InterProcessLock lock(&fileLock, SharedLockType);
  243. SCOPED_LOCK(&lock);
  244. mmkv::getFileSize(m_diskFile.m_fd, m_size);
  245. size_t expectedSize = std::max<size_t>(DEFAULT_MMAP_SIZE, roundUp<size_t>(expectedCapacity, DEFAULT_MMAP_SIZE));
  246. // round up to (n * pagesize)
  247. if (!m_readOnly && (m_size < expectedSize || (m_size % DEFAULT_MMAP_SIZE != 0))) {
  248. InterProcessLock exclusiveLock(&fileLock, ExclusiveLockType);
  249. SCOPED_LOCK(&exclusiveLock);
  250. size_t roundSize = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;;
  251. roundSize = std::max<size_t>(expectedSize, roundSize);
  252. truncate(roundSize, &fileLock);
  253. } else {
  254. mmapOrCleanup(&fileLock);
  255. }
  256. # ifdef MMKV_IOS
  257. if (!m_readOnly) {
  258. tryResetFileProtection(m_diskFile.m_path);
  259. }
  260. # endif
  261. }
  262. }
  263. void MemoryFile::doCleanMemoryCache(bool forceClean) {
  264. # ifdef MMKV_ANDROID
  265. if (m_diskFile.m_fileType == MMFILE_TYPE_ASHMEM && !forceClean) {
  266. return;
  267. }
  268. # endif
  269. if (m_ptr && m_ptr != MAP_FAILED) {
  270. if (munmap(m_ptr, m_size) != 0) {
  271. MMKVError("fail to munmap [%s], %s", m_diskFile.m_path.c_str(), strerror(errno));
  272. }
  273. }
  274. m_ptr = nullptr;
  275. m_diskFile.close();
  276. m_size = 0;
  277. }
  278. bool isFileExist(const string &nsFilePath) {
  279. if (nsFilePath.empty()) {
  280. return false;
  281. }
  282. return access(nsFilePath.c_str(), F_OK) == 0;
  283. }
  284. #ifndef MMKV_APPLE
  285. extern bool mkPath(const MMKVPath_t &str) {
  286. char *path = strdup(str.c_str());
  287. struct stat sb = {};
  288. bool done = false;
  289. char *slash = path;
  290. while (!done) {
  291. slash += strspn(slash, "/");
  292. slash += strcspn(slash, "/");
  293. done = (*slash == '\0');
  294. *slash = '\0';
  295. if (stat(path, &sb) != 0) {
  296. if (errno != ENOENT || mkdir(path, 0777) != 0) {
  297. MMKVWarning("%s : %s", path, strerror(errno));
  298. // there's report that some Android devices might not have access permission on parent dir
  299. if (done) {
  300. free(path);
  301. return false;
  302. }
  303. goto LContinue;
  304. }
  305. } else if (!S_ISDIR(sb.st_mode)) {
  306. MMKVWarning("%s: %s", path, strerror(ENOTDIR));
  307. free(path);
  308. return false;
  309. }
  310. LContinue:
  311. *slash = '/';
  312. }
  313. free(path);
  314. return true;
  315. }
  316. #else
  317. // avoid using so-called privacy API
  318. extern bool mkPath(const MMKVPath_t &str) {
  319. auto path = [NSString stringWithUTF8String:str.c_str()];
  320. NSError *error = nil;
  321. auto ret = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
  322. if (!ret) {
  323. MMKVWarning("%s", error.localizedDescription.UTF8String);
  324. return false;
  325. }
  326. return true;
  327. }
  328. #endif
  329. MMBuffer *readWholeFile(const MMKVPath_t &path) {
  330. MMBuffer *buffer = nullptr;
  331. int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
  332. if (fd >= 0) {
  333. auto fileLength = lseek(fd, 0, SEEK_END);
  334. if (fileLength > 0) {
  335. buffer = new MMBuffer(static_cast<size_t>(fileLength));
  336. lseek(fd, 0, SEEK_SET);
  337. auto readSize = read(fd, buffer->getPtr(), static_cast<size_t>(fileLength));
  338. if (readSize != -1) {
  339. //fileSize = readSize;
  340. } else {
  341. MMKVWarning("fail to read %s: %s", path.c_str(), strerror(errno));
  342. delete buffer;
  343. buffer = nullptr;
  344. }
  345. }
  346. close(fd);
  347. } else {
  348. MMKVWarning("fail to open %s: %s", path.c_str(), strerror(errno));
  349. }
  350. return buffer;
  351. }
  352. bool zeroFillFile(int fd, size_t startPos, size_t size) {
  353. if (fd < 0) {
  354. return false;
  355. }
  356. if (lseek(fd, static_cast<off_t>(startPos), SEEK_SET) < 0) {
  357. MMKVError("fail to lseek fd[%d], error:%s", fd, strerror(errno));
  358. return false;
  359. }
  360. static const char zeros[4096] = {};
  361. while (size >= sizeof(zeros)) {
  362. if (write(fd, zeros, sizeof(zeros)) < 0) {
  363. MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
  364. return false;
  365. }
  366. size -= sizeof(zeros);
  367. }
  368. if (size > 0) {
  369. if (write(fd, zeros, size) < 0) {
  370. MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
  371. return false;
  372. }
  373. }
  374. return true;
  375. }
  376. #ifndef MMKV_APPLE
  377. bool getFileSize(int fd, size_t &size) {
  378. struct stat st = {};
  379. if (fstat(fd, &st) != -1) {
  380. size = (size_t) st.st_size;
  381. return true;
  382. }
  383. return false;
  384. }
  385. bool getFileSize(const char *path, size_t &size) {
  386. struct stat st = {};
  387. if (stat(path, &st) != -1) {
  388. size = (size_t) st.st_size;
  389. return true;
  390. }
  391. return false;
  392. }
  393. #else // !MMKV_APPLE
  394. // avoid using so-called privacy API
  395. bool getFileSize(int fd, size_t &size) {
  396. auto cur = lseek(fd, 0, SEEK_CUR);
  397. if (cur == -1) {
  398. return false;
  399. }
  400. auto end = lseek(fd, 0, SEEK_END);
  401. if (end == -1) {
  402. return false;
  403. }
  404. size = (size_t) end;
  405. lseek(fd, cur, SEEK_SET);
  406. return true;
  407. }
  408. bool getFileSize(const char *path, size_t &size) {
  409. auto fd = open(path, O_RDONLY);
  410. if (fd >= 0) {
  411. auto ret = getFileSize(fd, size);
  412. close(fd);
  413. return ret;
  414. }
  415. return false;
  416. }
  417. #endif // !MMKV_APPLE
  418. size_t getPageSize() {
  419. return static_cast<size_t>(getpagesize());
  420. }
  421. extern MMKVPath_t absolutePath(const MMKVPath_t &path) {
  422. fs::path relative_path(path);
  423. fs::path absolute_path = fs::absolute(relative_path);
  424. fs::path normalized = fs::weakly_canonical(absolute_path);
  425. return normalized.string();
  426. }
  427. #ifndef MMKV_APPLE
  428. static pair<MMKVPath_t, int> createUniqueTempFile(const char *prefix) {
  429. char path[PATH_MAX];
  430. #ifdef MMKV_ANDROID
  431. snprintf(path, PATH_MAX, "%s/%s.XXXXXX", g_android_tmpDir.c_str(), prefix);
  432. #else
  433. snprintf(path, PATH_MAX, "%s/%s.XXXXXX", P_tmpdir, prefix);
  434. #endif
  435. auto fd = mkstemp(path);
  436. if (fd < 0) {
  437. MMKVError("fail to create unique temp file [%s], %d(%s)", path, errno, strerror(errno));
  438. return {"", fd};
  439. }
  440. MMKVDebug("create unique temp file [%s] with fd[%d]", path, fd);
  441. return {MMKVPath_t(path), fd};
  442. }
  443. #if !defined(MMKV_ANDROID) && !defined(MMKV_LINUX)
  444. bool tryAtomicRename(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  445. if (::rename(srcPath.c_str(), dstPath.c_str()) != 0) {
  446. MMKVError("fail to rename [%s] to [%s], %d(%s)", srcPath.c_str(), dstPath.c_str(), errno, strerror(errno));
  447. return false;
  448. }
  449. return true;
  450. }
  451. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD, bool needTruncate) {
  452. if (dstFD < 0) {
  453. return false;
  454. }
  455. bool ret = false;
  456. File srcFile(srcPath, OpenFlag::ReadOnly);
  457. if (!srcFile.isFileValid()) {
  458. return false;
  459. }
  460. auto bufferSize = getPageSize();
  461. auto buffer = (char *) malloc(bufferSize);
  462. if (!buffer) {
  463. MMKVError("fail to malloc size %zu, %d(%s)", bufferSize, errno, strerror(errno));
  464. goto errorOut;
  465. }
  466. lseek(dstFD, 0, SEEK_SET);
  467. // the POSIX standard don't have sendfile()/fcopyfile() equivalent, do it the hard way
  468. while (true) {
  469. auto sizeRead = read(srcFile.getFd(), buffer, bufferSize);
  470. if (sizeRead < 0) {
  471. MMKVError("fail to read file [%s], %d(%s)", srcPath.c_str(), errno, strerror(errno));
  472. goto errorOut;
  473. }
  474. size_t totalWrite = 0;
  475. do {
  476. auto sizeWrite = write(dstFD, buffer + totalWrite, sizeRead - totalWrite);
  477. if (sizeWrite < 0) {
  478. MMKVError("fail to write fd [%d], %d(%s)", dstFD, errno, strerror(errno));
  479. goto errorOut;
  480. }
  481. totalWrite += sizeWrite;
  482. } while (totalWrite < sizeRead);
  483. if (sizeRead < bufferSize) {
  484. break;
  485. }
  486. }
  487. if (needTruncate) {
  488. size_t dstFileSize = 0;
  489. getFileSize(dstFD, dstFileSize);
  490. auto srcFileSize = srcFile.getActualFileSize();
  491. if ((dstFileSize != srcFileSize) && (::ftruncate(dstFD, static_cast<off_t>(srcFileSize)) != 0)) {
  492. MMKVError("fail to truncate [%d] to size [%zu], %d(%s)", dstFD, srcFileSize, errno, strerror(errno));
  493. goto errorOut;
  494. }
  495. }
  496. ret = true;
  497. MMKVInfo("copy content from %s to fd[%d] finish", srcPath.c_str(), dstFD);
  498. errorOut:
  499. free(buffer);
  500. return ret;
  501. }
  502. #endif // !defined(MMKV_ANDROID) && !defined(MMKV_LINUX)
  503. // copy to a temp file then rename it
  504. // this is the best we can do under the POSIX standard
  505. bool copyFile(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  506. auto pair = createUniqueTempFile("MMKV");
  507. auto tmpFD = pair.second;
  508. auto &tmpPath = pair.first;
  509. if (tmpFD < 0) {
  510. return false;
  511. }
  512. bool renamed = false;
  513. if (copyFileContent(srcPath, tmpFD, false)) {
  514. MMKVInfo("copyfile [%s] to [%s]", srcPath.c_str(), tmpPath.c_str());
  515. renamed = tryAtomicRename(tmpPath, dstPath);
  516. if (!renamed) {
  517. MMKVInfo("rename fail, try copy file content instead.");
  518. if (copyFileContent(tmpPath, dstPath)) {
  519. renamed = true;
  520. ::unlink(tmpPath.c_str());
  521. }
  522. }
  523. if (renamed) {
  524. MMKVInfo("copyfile [%s] to [%s] finish.", srcPath.c_str(), dstPath.c_str());
  525. }
  526. }
  527. ::close(tmpFD);
  528. if (!renamed) {
  529. ::unlink(tmpPath.c_str());
  530. }
  531. return renamed;
  532. }
  533. bool copyFileContent(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  534. File dstFile(dstPath, OpenFlag::WriteOnly | OpenFlag::Create | OpenFlag::Truncate);
  535. if (!dstFile.isFileValid()) {
  536. return false;
  537. }
  538. auto ret = copyFileContent(srcPath, dstFile.getFd(), false);
  539. if (!ret) {
  540. MMKVError("fail to copyfile(): target file %s", dstPath.c_str());
  541. } else {
  542. MMKVInfo("copy content from %s to [%s] finish", srcPath.c_str(), dstPath.c_str());
  543. }
  544. return ret;
  545. }
  546. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD) {
  547. return copyFileContent(srcPath, dstFD, true);
  548. }
  549. #endif // !defined(MMKV_APPLE)
  550. void walkInDir(const MMKVPath_t &dirPath, WalkType type, const function<void(const MMKVPath_t&, WalkType)> &walker) {
  551. auto folderPathStr = dirPath.data();
  552. DIR *dir = opendir(folderPathStr);
  553. if (!dir) {
  554. MMKVError("opendir failed: %d(%s), %s", errno, strerror(errno), dirPath.c_str());
  555. return;
  556. }
  557. char childPath[PATH_MAX];
  558. size_t folderPathLength = dirPath.size();
  559. strncpy(childPath, folderPathStr, folderPathLength + 1);
  560. if (folderPathStr[folderPathLength - 1] != '/') {
  561. childPath[folderPathLength] = '/';
  562. folderPathLength++;
  563. }
  564. while (auto child = readdir(dir)) {
  565. if ((child->d_type & DT_REG) && (type & WalkFile)) {
  566. #if defined(_DIRENT_HAVE_D_NAMLEN) || defined(__APPLE__)
  567. stpcpy(childPath + folderPathLength, child->d_name);
  568. childPath[folderPathLength + child->d_namlen] = 0;
  569. #else
  570. strcpy(childPath + folderPathLength, child->d_name);
  571. #endif
  572. walker(childPath, WalkFile);
  573. } else if ((child->d_type & DT_DIR) && (type & WalkFolder)) {
  574. #if defined(_DIRENT_HAVE_D_NAMLEN) || defined(__APPLE__)
  575. if ((child->d_namlen == 1 && child->d_name[0] == '.') ||
  576. (child->d_namlen == 2 && child->d_name[0] == '.' && child->d_name[1] == '.')) {
  577. continue;
  578. }
  579. stpcpy(childPath + folderPathLength, child->d_name);
  580. childPath[folderPathLength + child->d_namlen] = 0;
  581. #else
  582. if (strcmp(child->d_name, ".") == 0 || strcmp(child->d_name, "..") == 0) {
  583. continue;
  584. }
  585. strcpy(childPath + folderPathLength, child->d_name);
  586. #endif
  587. walker(childPath, WalkFolder);
  588. }
  589. }
  590. closedir(dir);
  591. }
  592. bool deleteFile(const MMKVPath_t &path) {
  593. auto filename = path.c_str();
  594. if (::unlink(filename) != 0) {
  595. auto err = errno;
  596. MMKVError("fail to delete file [%s], %d (%s)", filename, err, strerror(err));
  597. return false;
  598. }
  599. return true;
  600. }
  601. #ifndef MMKV_APPLE
  602. bool isDiskOfMMAPFileCorrupted(MemoryFile *file, bool &needReportReadFail) {
  603. // TODO: maybe we need reading a larger chunk than 4 byte in Android/Linux
  604. uint32_t info;
  605. auto fd = file->getFd();
  606. auto path = file->getPath().c_str();
  607. auto oldPos = lseek(fd, 0, SEEK_CUR);
  608. lseek(fd, 0, SEEK_SET);
  609. auto size = read(fd, &info, sizeof(info));
  610. auto err = errno;
  611. lseek(fd, oldPos, SEEK_SET);
  612. if (size <= 0) {
  613. needReportReadFail = true;
  614. MMKVError("fail to read [%s] from fd [%d], errno: %d (%s)", path, fd, err, strerror(err));
  615. if (err == EIO || err == EILSEQ || err == EINVAL || err == ENXIO) {
  616. MMKVWarning("file fail to read, consider it illegal, delete now: [%s]", path);
  617. return true;
  618. }
  619. }
  620. file->cleanMayflyFD();
  621. return false;
  622. }
  623. #endif
  624. } // namespace mmkv
  625. #endif // !defined(MMKV_WIN32)