Bitcoin ABC 0.32.11
P2P Digital Currency
fs_helpers.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2023 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <util/fs_helpers.h>
7
8#if defined(HAVE_CONFIG_H)
9#include <config/bitcoin-config.h>
10#endif
11
12#include <logging.h>
13#include <sync.h>
14#include <util/fs.h>
15#include <util/syserror.h>
16
17#include <cerrno>
18#include <fstream>
19#include <map>
20#include <memory>
21#include <string>
22#include <system_error>
23#include <utility>
24
25#ifndef WIN32
26// for posix_fallocate, in config/CMakeLists.txt we check if it is present after
27// this
28#ifdef __linux__
29
30#ifdef _POSIX_C_SOURCE
31#undef _POSIX_C_SOURCE
32#endif
33
34#define _POSIX_C_SOURCE 200112L
35
36#endif // __linux__
37
38#include <fcntl.h>
39#include <sys/resource.h>
40#include <unistd.h>
41#else
42#include <io.h> /* For _get_osfhandle, _chsize */
43#include <shlobj.h> /* For SHGetSpecialFolderPathW */
44#endif // WIN32
45
53static std::map<std::string, std::unique_ptr<fsbridge::FileLock>>
55namespace util {
57 const std::string lockfile_name, bool probe_only) {
59 fs::path pathLockFile = directory / lockfile_name;
60
61 // If a lock for this directory already exists in the map, don't try to
62 // re-lock it
63 if (dir_locks.count(fs::PathToString(pathLockFile))) {
65 }
66
67 // Create empty lock file if it doesn't exist.
68 if (auto created{fsbridge::fopen(pathLockFile, "a")}) {
69 std::fclose(created);
70 } else {
72 }
73 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
74 if (!lock->TryLock()) {
75 LogError("Error while attempting to lock directory %s: %s\n",
76 fs::PathToString(directory), lock->GetReason());
78 }
79 if (!probe_only) {
80 // Lock successful and we're not just probing, put it into the map
81 dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
82 }
84}
85} // namespace util
86void UnlockDirectory(const fs::path &directory,
87 const std::string &lockfile_name) {
89 dir_locks.erase(fs::PathToString(directory / lockfile_name));
90}
91
94 dir_locks.clear();
95}
96
97bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes) {
98 // 50 MiB
99 constexpr uint64_t min_disk_space = 52428800;
100
101 uint64_t free_bytes_available = fs::space(dir).available;
102 return free_bytes_available >= min_disk_space + additional_bytes;
103}
104
105std::streampos GetFileSize(const char *path, std::streamsize max) {
106 std::ifstream file{path, std::ios::binary};
107 file.ignore(max);
108 return file.gcount();
109}
110
111bool FileCommit(FILE *file) {
112 // harmless if redundantly called
113 if (fflush(file) != 0) {
114 LogPrintf("fflush failed: %s\n", SysErrorString(errno));
115 return false;
116 }
117#ifdef WIN32
118 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
119 if (FlushFileBuffers(hFile) == 0) {
120 LogPrintf("FlushFileBuffers failed: %s\n",
121 Win32ErrorString(GetLastError()));
122 return false;
123 }
124#elif defined(MAC_OSX) && defined(F_FULLFSYNC)
125 // Manpage says "value other than -1" is returned on success
126 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) {
127 LogPrintf("fcntl F_FULLFSYNC failed: %s\n", SysErrorString(errno));
128 return false;
129 }
130#elif HAVE_FDATASYNC
131 // Ignore EINVAL for filesystems that don't support sync
132 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) {
133 LogPrintf("fdatasync failed: %s\n", SysErrorString(errno));
134 return false;
135 }
136#else
137 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
138 LogPrintf("fsync failed: %s\n", SysErrorString(errno));
139 return false;
140 }
141#endif
142 return true;
143}
144
145void DirectoryCommit(const fs::path &dirname) {
146#ifndef WIN32
147 FILE *file = fsbridge::fopen(dirname, "r");
148 if (file) {
149 fsync(fileno(file));
150 fclose(file);
151 }
152#endif
153}
154
155bool TruncateFile(FILE *file, unsigned int length) {
156#if defined(WIN32)
157 return _chsize(_fileno(file), length) == 0;
158#else
159 return ftruncate(fileno(file), length) == 0;
160#endif
161}
162
169#if defined(WIN32)
170 return 8192;
171#else
172 struct rlimit limitFD;
173 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
174 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
175 limitFD.rlim_cur = nMinFD;
176 if (limitFD.rlim_cur > limitFD.rlim_max) {
177 limitFD.rlim_cur = limitFD.rlim_max;
178 }
179 setrlimit(RLIMIT_NOFILE, &limitFD);
180 getrlimit(RLIMIT_NOFILE, &limitFD);
181 }
182 return limitFD.rlim_cur;
183 }
184 // getrlimit failed, assume it's fine.
185 return nMinFD;
186#endif
187}
188
194void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
195#if defined(WIN32)
196 // Windows-specific version.
197 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
198 LARGE_INTEGER nFileSize;
199 int64_t nEndPos = (int64_t)offset + length;
200 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
201 nFileSize.u.HighPart = nEndPos >> 32;
202 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
203 SetEndOfFile(hFile);
204#elif defined(MAC_OSX)
205 // OSX specific version
206 // NOTE: Contrary to other OS versions, the OSX version assumes that
207 // NOTE: offset is the size of the file.
208 fstore_t fst;
209 fst.fst_flags = F_ALLOCATECONTIG;
210 fst.fst_posmode = F_PEOFPOSMODE;
211 fst.fst_offset = 0;
212 // mac os fst_length takes the number of free bytes to allocate,
213 // not the desired file size
214 fst.fst_length = length;
215 fst.fst_bytesalloc = 0;
216 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
217 fst.fst_flags = F_ALLOCATEALL;
218 fcntl(fileno(file), F_PREALLOCATE, &fst);
219 }
220 ftruncate(fileno(file), static_cast<off_t>(offset) + length);
221#elif defined(HAVE_POSIX_FALLOCATE)
222 // Version using posix_fallocate
223 off_t nEndPos = (off_t)offset + length;
224 posix_fallocate(fileno(file), 0, nEndPos);
225#else
226 // Fallback version
227 // TODO: just write one byte per block
228 static const char buf[65536] = {};
229 if (fseek(file, offset, SEEK_SET)) {
230 return;
231 }
232 while (length > 0) {
233 unsigned int now = 65536;
234 if (length < now) {
235 now = length;
236 }
237 // Allowed to fail; this function is advisory anyway.
238 fwrite(buf, 1, now, file);
239 length -= now;
240 }
241#endif
242}
243
244#ifdef WIN32
245fs::path GetSpecialFolderPath(int nFolder, bool fCreate) {
246 WCHAR pszPath[MAX_PATH] = L"";
247
248 if (SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) {
249 return fs::path(pszPath);
250 }
251
252 LogPrintf(
253 "SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
254 return fs::path("");
255}
256#endif
257
258bool RenameOver(fs::path src, fs::path dest) {
259 std::error_code error;
260 fs::rename(src, dest, error);
261 return !error;
262}
263
270 try {
271 return fs::create_directories(p);
272 } catch (const fs::filesystem_error &) {
273 if (!fs::exists(p) || !fs::is_directory(p)) {
274 throw;
275 }
276 }
277
278 // create_directory didn't create the directory, it had to have existed
279 // already.
280 return false;
281}
Different type to mark Mutex at global scope.
Definition: sync.h:144
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
#define MAX_PATH
Definition: compat.h:70
static GlobalMutex cs_dir_locks
Mutex to protect dir_locks.
Definition: fs_helpers.cpp:47
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: fs_helpers.cpp:86
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:258
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: fs_helpers.cpp:105
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:168
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: fs_helpers.cpp:145
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: fs_helpers.cpp:92
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:269
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
This function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: fs_helpers.cpp:194
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:97
bool TruncateFile(FILE *file, unsigned int length)
Definition: fs_helpers.cpp:155
static std::map< std::string, std::unique_ptr< fsbridge::FileLock > > dir_locks GUARDED_BY(cs_dir_locks)
A map that contains all the currently held directory locks.
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:111
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition: fs.h:185
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
LockResult LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: fs_helpers.cpp:56
LockResult
Definition: fs_helpers.h:39
#define LOCK(cs)
Definition: sync.h:306
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:20