Skip to content

Commit fc888bf

Browse files
committed
util: Fix multiple use of LockDirectory
This commit fixes problems with calling LockDirectory multiple times on the same directory, or from multiple threads. It also fixes the build on OpenBSD. - Wrap the boost::interprocess::file_lock in a std::unique_ptr inside the map that keeps track of per-directory locks. This fixes a build issue with the clang 4.0.0+boost-1.58.0p8 version combo on OpenBSD 6.2, and should have no observable effect otherwise. - Protect the locks map using a mutex. - Make sure that only locks that are successfully acquired are inserted in the map. - Open the lock file for appending only if we know we don't have the lock yet - The `FILE* file = fsbridge::fopen(pathLockFile, "a");` wipes the 'we own this lock' administration, likely because it opens a new fd for the locked file then closes it.
1 parent f4f4f51 commit fc888bf

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/util.cpp

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -375,18 +375,32 @@ int LogPrintStr(const std::string &str)
375375

376376
bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
377377
{
378+
// A map that contains all the currently held directory locks. After
379+
// successful locking, these will be held here until the global
380+
// destructor cleans them up and thus automatically unlocks them.
381+
static std::map<std::string, std::unique_ptr<boost::interprocess::file_lock>> locks;
382+
// Protect the map with a mutex
383+
static std::mutex cs;
384+
std::lock_guard<std::mutex> ulock(cs);
378385
fs::path pathLockFile = directory / lockfile_name;
379-
FILE* file = fsbridge::fopen(pathLockFile, "a"); // empty lock file; created if it doesn't exist.
386+
387+
// If a lock for this directory already exists in the map, don't try to re-lock it
388+
if (locks.count(pathLockFile.string())) {
389+
return true;
390+
}
391+
392+
// Create empty lock file if it doesn't exist.
393+
FILE* file = fsbridge::fopen(pathLockFile, "a");
380394
if (file) fclose(file);
381395

382396
try {
383-
static std::map<std::string, boost::interprocess::file_lock> locks;
384-
boost::interprocess::file_lock& lock = locks.emplace(pathLockFile.string(), pathLockFile.string().c_str()).first->second;
385-
if (!lock.try_lock()) {
397+
auto lock = MakeUnique<boost::interprocess::file_lock>(pathLockFile.string().c_str());
398+
if (!lock->try_lock()) {
386399
return false;
387400
}
388-
if (probe_only) {
389-
lock.unlock();
401+
if (!probe_only) {
402+
// Lock successful and we're not just probing, put it into the map
403+
locks.emplace(pathLockFile.string(), std::move(lock));
390404
}
391405
} catch (const boost::interprocess::interprocess_exception& e) {
392406
return error("Error while attempting to lock directory %s: %s", directory.string(), e.what());

0 commit comments

Comments
 (0)