MemoryFile.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. clearMemoryCache();
  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. free(path);
  242. return false;
  243. }
  244. } else if (!S_ISDIR(sb.st_mode)) {
  245. MMKVWarning("%s: %s", path, strerror(ENOTDIR));
  246. free(path);
  247. return false;
  248. }
  249. *slash = '/';
  250. }
  251. free(path);
  252. return true;
  253. }
  254. MMBuffer *readWholeFile(const MMKVPath_t &path) {
  255. MMBuffer *buffer = nullptr;
  256. int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
  257. if (fd >= 0) {
  258. auto fileLength = lseek(fd, 0, SEEK_END);
  259. if (fileLength > 0) {
  260. buffer = new MMBuffer(static_cast<size_t>(fileLength));
  261. lseek(fd, 0, SEEK_SET);
  262. auto readSize = read(fd, buffer->getPtr(), static_cast<size_t>(fileLength));
  263. if (readSize != -1) {
  264. //fileSize = readSize;
  265. } else {
  266. MMKVWarning("fail to read %s: %s", path.c_str(), strerror(errno));
  267. delete buffer;
  268. buffer = nullptr;
  269. }
  270. }
  271. close(fd);
  272. } else {
  273. MMKVWarning("fail to open %s: %s", path.c_str(), strerror(errno));
  274. }
  275. return buffer;
  276. }
  277. bool zeroFillFile(int fd, size_t startPos, size_t size) {
  278. if (fd < 0) {
  279. return false;
  280. }
  281. if (lseek(fd, static_cast<off_t>(startPos), SEEK_SET) < 0) {
  282. MMKVError("fail to lseek fd[%d], error:%s", fd, strerror(errno));
  283. return false;
  284. }
  285. static const char zeros[4096] = {};
  286. while (size >= sizeof(zeros)) {
  287. if (write(fd, zeros, sizeof(zeros)) < 0) {
  288. MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
  289. return false;
  290. }
  291. size -= sizeof(zeros);
  292. }
  293. if (size > 0) {
  294. if (write(fd, zeros, size) < 0) {
  295. MMKVError("fail to write fd[%d], error:%s", fd, strerror(errno));
  296. return false;
  297. }
  298. }
  299. return true;
  300. }
  301. bool getFileSize(int fd, size_t &size) {
  302. struct stat st = {};
  303. if (fstat(fd, &st) != -1) {
  304. size = (size_t) st.st_size;
  305. return true;
  306. }
  307. return false;
  308. }
  309. size_t getPageSize() {
  310. return static_cast<size_t>(getpagesize());
  311. }
  312. #ifndef MMKV_APPLE
  313. static pair<MMKVPath_t, int> createUniqueTempFile(const char *prefix) {
  314. char path[PATH_MAX];
  315. #ifdef MMKV_ANDROID
  316. snprintf(path, PATH_MAX, "%s/%s.XXXXXX", g_android_tmpDir.c_str(), prefix);
  317. #else
  318. snprintf(path, PATH_MAX, "%s/%s.XXXXXX", P_tmpdir, prefix);
  319. #endif
  320. auto fd = mkstemp(path);
  321. if (fd < 0) {
  322. MMKVError("fail to create unique temp file [%s], %d(%s)", path, errno, strerror(errno));
  323. return {"", fd};
  324. }
  325. MMKVDebug("create unique temp file [%s] with fd[%d]", path, fd);
  326. return {MMKVPath_t(path), fd};
  327. }
  328. #if !defined(MMKV_ANDROID) && !defined(MMKV_LINUX)
  329. bool tryAtomicRename(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  330. if (::rename(srcPath.c_str(), dstPath.c_str()) != 0) {
  331. MMKVError("fail to rename [%s] to [%s], %d(%s)", srcPath.c_str(), dstPath.c_str(), errno, strerror(errno));
  332. return false;
  333. }
  334. return true;
  335. }
  336. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD, bool needTruncate) {
  337. if (dstFD < 0) {
  338. return false;
  339. }
  340. bool ret = false;
  341. File srcFile(srcPath, OpenFlag::ReadOnly);
  342. if (!srcFile.isFileValid()) {
  343. return false;
  344. }
  345. auto bufferSize = getPageSize();
  346. auto buffer = (char *) malloc(bufferSize);
  347. if (!buffer) {
  348. MMKVError("fail to malloc size %zu, %d(%s)", bufferSize, errno, strerror(errno));
  349. goto errorOut;
  350. }
  351. lseek(dstFD, 0, SEEK_SET);
  352. // the POSIX standard don't have sendfile()/fcopyfile() equivalent, do it the hard way
  353. while (true) {
  354. auto sizeRead = read(srcFile.getFd(), buffer, bufferSize);
  355. if (sizeRead < 0) {
  356. MMKVError("fail to read file [%s], %d(%s)", srcPath.c_str(), errno, strerror(errno));
  357. goto errorOut;
  358. }
  359. size_t totalWrite = 0;
  360. do {
  361. auto sizeWrite = write(dstFD, buffer + totalWrite, sizeRead - totalWrite);
  362. if (sizeWrite < 0) {
  363. MMKVError("fail to write fd [%d], %d(%s)", dstFD, errno, strerror(errno));
  364. goto errorOut;
  365. }
  366. totalWrite += sizeWrite;
  367. } while (totalWrite < sizeRead);
  368. if (sizeRead < bufferSize) {
  369. break;
  370. }
  371. }
  372. if (needTruncate) {
  373. size_t dstFileSize = 0;
  374. getFileSize(dstFD, dstFileSize);
  375. auto srcFileSize = srcFile.getActualFileSize();
  376. if ((dstFileSize != srcFileSize) && (::ftruncate(dstFD, static_cast<off_t>(srcFileSize)) != 0)) {
  377. MMKVError("fail to truncate [%d] to size [%zu], %d(%s)", dstFD, srcFileSize, errno, strerror(errno));
  378. goto errorOut;
  379. }
  380. }
  381. ret = true;
  382. MMKVInfo("copy content from %s to fd[%d] finish", srcPath.c_str(), dstFD);
  383. errorOut:
  384. free(buffer);
  385. return ret;
  386. }
  387. #endif // !defined(MMKV_ANDROID) && !defined(MMKV_LINUX)
  388. // copy to a temp file then rename it
  389. // this is the best we can do under the POSIX standard
  390. bool copyFile(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  391. auto pair = createUniqueTempFile("MMKV");
  392. auto tmpFD = pair.second;
  393. auto &tmpPath = pair.first;
  394. if (tmpFD < 0) {
  395. return false;
  396. }
  397. bool renamed = false;
  398. if (copyFileContent(srcPath, tmpFD, false)) {
  399. MMKVInfo("copyfile [%s] to [%s]", srcPath.c_str(), tmpPath.c_str());
  400. renamed = tryAtomicRename(tmpPath, dstPath);
  401. if (renamed) {
  402. MMKVInfo("copyfile [%s] to [%s] finish.", srcPath.c_str(), dstPath.c_str());
  403. }
  404. }
  405. ::close(tmpFD);
  406. if (!renamed) {
  407. ::unlink(tmpPath.c_str());
  408. }
  409. return renamed;
  410. }
  411. bool copyFileContent(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
  412. File dstFile(dstPath, OpenFlag::WriteOnly | OpenFlag::Create | OpenFlag::Truncate);
  413. if (!dstFile.isFileValid()) {
  414. return false;
  415. }
  416. auto ret = copyFileContent(srcPath, dstFile.getFd(), false);
  417. if (!ret) {
  418. MMKVError("fail to copyfile(): target file %s", dstPath.c_str());
  419. } else {
  420. MMKVInfo("copy content from %s to [%s] finish", srcPath.c_str(), dstPath.c_str());
  421. }
  422. return ret;
  423. }
  424. bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD) {
  425. return copyFileContent(srcPath, dstFD, true);
  426. }
  427. #endif // !defined(MMKV_APPLE)
  428. void walkInDir(const MMKVPath_t &dirPath, WalkType type, const function<void(const MMKVPath_t&, WalkType)> &walker) {
  429. auto folderPathStr = dirPath.data();
  430. DIR *dir = opendir(folderPathStr);
  431. if (!dir) {
  432. MMKVError("opendir failed: %d(%s), %s", errno, strerror(errno), dirPath.c_str());
  433. return;
  434. }
  435. char childPath[PATH_MAX];
  436. size_t folderPathLength = dirPath.size();
  437. strncpy(childPath, folderPathStr, folderPathLength + 1);
  438. if (folderPathStr[folderPathLength - 1] != '/') {
  439. childPath[folderPathLength] = '/';
  440. folderPathLength++;
  441. }
  442. while (auto child = readdir(dir)) {
  443. if ((child->d_type & DT_REG) && (type & WalkFile)) {
  444. #ifdef _DIRENT_HAVE_D_NAMLEN
  445. stpcpy(childPath + folderPathLength, child->d_name);
  446. childPath[folderPathLength + child->d_namlen] = 0;
  447. #else
  448. strcpy(childPath + folderPathLength, child->d_name);
  449. #endif
  450. walker(childPath, WalkFile);
  451. } else if ((child->d_type & DT_DIR) && (type & WalkFolder)) {
  452. #ifdef _DIRENT_HAVE_D_NAMLEN
  453. if ((child->d_namlen == 1 && child->d_name[0] == '.') ||
  454. (child->d_namlen == 2 && child->d_name[0] == '.' && child->d_name[1] == '.')) {
  455. continue;
  456. }
  457. stpcpy(childPath + folderPathLength, child->d_name);
  458. childPath[folderPathLength + child->d_namlen] = 0;
  459. #else
  460. if (strcmp(child->d_name, ".") == 0 || strcmp(child->d_name, "..") == 0) {
  461. continue;
  462. }
  463. strcpy(childPath + folderPathLength, child->d_name);
  464. #endif
  465. walker(childPath, WalkFolder);
  466. }
  467. }
  468. closedir(dir);
  469. }
  470. } // namespace mmkv
  471. #endif // !defined(MMKV_WIN32)