From 1160d701005cebdd110a167c6b1dc9db2dcc5444 Mon Sep 17 00:00:00 2001 From: OrbitZore Date: Mon, 2 Nov 2026 02:44:07 +0800 Subject: [PATCH] =?UTF-8?q?fix(gitmount):=20=E8=A7=A3=E9=94=81=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E5=BC=82=E5=B8=B8=E5=AE=89=E5=85=A8=E2=80=94=E2=80=94?= =?UTF-8?q?ScopedUnlock=E3=80=81/commits=20=E9=A3=9E=E8=A1=8C=E5=AE=88?= =?UTF-8?q?=E5=8D=AB=E4=B8=8E=E5=9B=9E=E8=B0=83=E8=BE=B9=E7=95=8C=E5=85=9C?= =?UTF-8?q?=E5=BA=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 安全审查发现(issue #4):分段加载的 5 处手写 mu_.unlock()…mu_.lock() 窗口毫无异常安全——窗口内的 std::string::assign / make_shared / push_back 分配大小可被仓库内容驱动(ODB 解压无上限),失败时 (1) 外层 lock_guard 对未上锁的 mutex 解锁(C++/POSIX 双重 UB); (2) 异常穿透 libfuse 纯 C 栈帧且全仓库无 handler → std::terminate, 挂载进程 SIGABRT,所有在途请求失败。 加重缺陷:/commits 生成段先置 commits_generating_=true 再解锁, 抛异常后 flag 永不复位、epoch 不再前进、无 notify——后续所有 /commits open 永久阻塞在条件变量上,每个阻塞 open 占用一个 libfuse worker(默认上限 10),耗尽后整个文件系统失去响应。 三部分同批修复: - src/lock_guards.hpp 新增 ScopedUnlock RAII 守卫(构造解锁/析构 重锁,含异常展开路径),替换全部 5 处手写窗口:tree_locked、 commit_facts_locked、load_blob_locked、cb_open 超大 blob 钉住、 cb_open commits 生成;窗口语义逐行不变(锁外读、锁内缓存 重查/插入顺序保持)。 - /commits single-flight 状态机抽成可测的 SingleFlight + GeneratorFinish(finish 经同一 unique_lock 幂等重锁,任意退出 路径复位 flag/推进 epoch/notify);open_commits 生成段包 try/catch(bad_alloc 等映射为生成失败,§3.5 重试语义),可见 语义不变:fast path、搭车者共享缓冲(0)或 -EIO、失败下次 open 重试。 - 六个 FUSE 回调(getattr/readlink/opendir/open/read/statfs) 边界兜底:catch (bad_alloc) → -ENOMEM,catch (...) → -EIO; cb_open 的 Handle 改 unique_ptr 管理以免异常路径泄漏。 新增 tests/unit/test_lock_guards.cpp(Catch2 v3):ScopedUnlock 窗口内未锁/出作用域重锁、异常展开后 mutex 可正常加解锁; SingleFlight 生成者抛异常后搭车者限时醒来得到失败结果且 flag 已复位、成功路径搭车共享、finish 幂等且 GeneratorFinish 恰好 触发一次。CHANGELOG 记录 Unreleased/Fixed(RFC 0000 §3.4 语境)。 Closes #4 --- CHANGELOG.md | 24 ++ CMakeLists.txt | 1 + src/gitmount.cpp | 617 +++++++++++++++++--------------- src/gitmount.hpp | 10 +- src/lock_guards.hpp | 141 ++++++++ tests/unit/test_lock_guards.cpp | 217 +++++++++++ 6 files changed, 724 insertions(+), 286 deletions(-) create mode 100644 src/lock_guards.hpp create mode 100644 tests/unit/test_lock_guards.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index b96f654..4b41fcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,30 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed +- Exception safety of the segmented-loading unlock windows (issue #4; RFC + 0000 §3.4 concurrency model): an allocation failure inside one of the five + manual `mu_.unlock() … mu_.lock()` windows (tree/commit-facts/blob loads, + oversized-blob open-pin, `/commits` open) previously made the surrounding + `std::lock_guard` unlock an already-unlocked mutex (UB) and the exception + escape through libfuse's C frames into `std::terminate`. All five windows + now use a `ScopedUnlock` RAII guard (`src/lock_guards.hpp`) that re-locks + on every exit path, exception unwinding included. +- An exception in `/commits` generation no longer wedges the single-flight + state forever: the state machine is now a `SingleFlight` guard whose + `GeneratorFinish` resets the in-flight flag, advances the wake-up epoch and + notifies riders on every exit path (re-locking through the same + `unique_lock`); generation failures — `bad_alloc` included — map to EIO + with retry-on-next-open (§3.5) instead of parking every later open on the + condition variable until the libfuse worker pool (default 10) is exhausted + and the whole filesystem stalls. +- FUSE callback boundaries (`getattr`, `readlink`, `opendir`, `open`, + `read`, `statfs`) now translate escaped exceptions into `-ENOMEM` + (`std::bad_alloc`) / `-EIO` (anything else) — no exception can cross into + libfuse's C frames and abort the mount. + ## [0.0.4] - 2026-09-26 ### Fixed diff --git a/CMakeLists.txt b/CMakeLists.txt index f178ad1..340433e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,6 +142,7 @@ if(GITMOUNT_BUILD_TESTS) tests/unit/test_object_cache.cpp tests/unit/test_errmap.cpp tests/unit/test_ino_registry.cpp + tests/unit/test_lock_guards.cpp tests/unit/test_options.cpp tests/unit/test_gitmodules.cpp tests/unit/test_rawobj.cpp diff --git a/src/gitmount.cpp b/src/gitmount.cpp index e750f38..96815b8 100644 --- a/src/gitmount.cpp +++ b/src/gitmount.cpp @@ -655,25 +655,30 @@ std::shared_ptr Gitmount::tree_locked(const git_oid& tre if (hit->kind == MetaValue::Kind::Tree) return hit->tree; } - mu_.unlock(); + // Read outside the lock (segmented load). ScopedUnlock re-locks mu_ on + // every exit path — including an allocation failure (issue #4) — so the + // caller's lock_guard never destructs an unlocked mutex. git_object_t type = GIT_OBJECT_ANY; std::string buf; - int rc = repo_->read_object(tree, &type, &buf); + int rc = 0; bool bad = false; std::shared_ptr owned; - if (rc == 0 && type != GIT_OBJECT_TREE) rc = ENOENT; // like git_tree_lookup - if (rc == 0) { - auto idx = rawobj::index_tree(buf.data(), buf.size(), repo_->oid_type()); - if (!idx) { - bad = true; // corrupt/hand-crafted garbage - } else { - auto td = std::make_shared(); - td->raw = std::move(buf); - td->offsets = std::move(*idx); - owned = std::move(td); + { + ScopedUnlock unlock(mu_); + rc = repo_->read_object(tree, &type, &buf); + if (rc == 0 && type != GIT_OBJECT_TREE) rc = ENOENT; // like git_tree_lookup + if (rc == 0) { + auto idx = rawobj::index_tree(buf.data(), buf.size(), repo_->oid_type()); + if (!idx) { + bad = true; // corrupt/hand-crafted garbage + } else { + auto td = std::make_shared(); + td->raw = std::move(buf); + td->offsets = std::move(*idx); + owned = std::move(td); + } } } - mu_.lock(); *malformed = bad; if (rc != 0 || bad) return nullptr; @@ -699,41 +704,43 @@ int Gitmount::commit_facts_locked(const git_oid& target, git_oid* commit_out, } } - // Miss: read the object and walk the tag chain outside the lock. - mu_.unlock(); + // Miss: read the object and walk the tag chain outside the lock + // (ScopedUnlock re-locks on every exit path, including throws — issue #4). git_oid cur = target; rawobj::CommitFacts facts; int rc = 0; bool ok = false; - for (int hop = 0; hop < 16; ++hop) { - git_object_t type = GIT_OBJECT_ANY; - std::string buf; - rc = repo_->read_object(cur, &type, &buf); - if (rc != 0) break; - if (type == GIT_OBJECT_COMMIT) { - auto f = rawobj::parse_commit(buf.data(), buf.size(), repo_->oid_type()); - if (!f) { - rc = EIO; // malformed commit object + { + ScopedUnlock unlock(mu_); + for (int hop = 0; hop < 16; ++hop) { + git_object_t type = GIT_OBJECT_ANY; + std::string buf; + rc = repo_->read_object(cur, &type, &buf); + if (rc != 0) break; + if (type == GIT_OBJECT_COMMIT) { + auto f = rawobj::parse_commit(buf.data(), buf.size(), repo_->oid_type()); + if (!f) { + rc = EIO; // malformed commit object + break; + } + facts = *f; + ok = true; break; } - facts = *f; - ok = true; - break; - } - if (type == GIT_OBJECT_TAG) { - auto next = rawobj::parse_tag(buf.data(), buf.size(), repo_->oid_type()); - if (!next) { - rc = EIO; - break; + if (type == GIT_OBJECT_TAG) { + auto next = rawobj::parse_tag(buf.data(), buf.size(), repo_->oid_type()); + if (!next) { + rc = EIO; + break; + } + cur = *next; + continue; } - cur = *next; - continue; + rc = EINVAL; // tree/blob: non-commit target (§3.1 unified rule) + break; } - rc = EINVAL; // tree/blob: non-commit target (§3.1 unified rule) - break; + if (!ok && rc == 0) rc = EINVAL; // tag chain too deep } - if (!ok && rc == 0) rc = EINVAL; // tag chain too deep - mu_.lock(); if (rc != 0) return -rc; if (auto hit = meta_cache_.lookup(key)) { // lost the race @@ -775,13 +782,16 @@ int Gitmount::load_blob_locked(const git_oid& oid, BlobView* view) { return 0; } - // Miss: decompress outside the lock (§3.4 exception 3). - mu_.unlock(); + // Miss: decompress outside the lock (§3.4 exception 3); ScopedUnlock + // re-locks on every exit path, including allocation failures (issue #4). std::string data; - const int rc = repo_->read_blob(oid, &data); - if (rc == 0) - log::vlog("blob decompressed (cache miss load): %s %zu bytes", key.c_str(), data.size()); - mu_.lock(); + int rc = 0; + { + ScopedUnlock unlock(mu_); + rc = repo_->read_blob(oid, &data); + if (rc == 0) + log::vlog("blob decompressed (cache miss load): %s %zu bytes", key.c_str(), data.size()); + } if (rc != 0) return rc; // Re-check: a concurrent loader may have won the race (no strict @@ -839,7 +849,7 @@ std::string Gitmount::compute_fingerprint_locked() { } int Gitmount::open_commits(std::shared_ptr* out) { - std::unique_lock g(commits_gen_mu_); + auto g = commits_flight_.hold(); // Fast path under mu_. { @@ -850,11 +860,10 @@ int Gitmount::open_commits(std::shared_ptr* out) { } } - if (commits_generating_) { - // Single-flight: wait for the in-flight generation and share its - // outcome — success reuses the buffer, failure maps to EIO (§3.4/§3.5). - const std::uint64_t epoch = commits_epoch_; - commits_cv_.wait(g, [&] { return commits_epoch_ != epoch; }); + if (!commits_flight_.begin_or_wait(g)) { + // Single-flight rider: the in-flight generation finished — share its + // outcome. A published buffer wins; no buffer means it failed → EIO + // (§3.4/§3.5), and the next open retries generation from scratch. std::lock_guard lk(mu_); if (commits_buffer_) { *out = commits_buffer_; @@ -863,23 +872,33 @@ int Gitmount::open_commits(std::shared_ptr* out) { return -EIO; } - // Double-check after acquiring the generation lock. + // Generator. GeneratorFinish resets the flight on every exit path — + // including exceptions, which previously left the in-flight flag set + // forever, parking all later opens on the condition variable until the + // libfuse worker pool drained (issue #4). + GeneratorFinish fin(commits_flight_, g); + + // Double-check after acquiring the generation lock: the repo's refs may + // have changed back to the cached fingerprint since the fast path. { std::lock_guard lk(mu_); if (commits_buffer_ && commits_fingerprint_ == compute_fingerprint_locked()) { *out = commits_buffer_; + fin.finish(); return 0; } } - commits_generating_ = true; g.unlock(); // ---- generation (chunked locking inside list_commits) ------------------ + // Any exception (bad_alloc in fingerprint/ref handling or buffer growth) + // maps to generation failure: ok=false → EIO, next open retries (§3.5) — + // nothing may escape open_commits with the flight still marked in progress. std::string fingerprint; std::string buffer; bool ok = false; - { + try { std::lock_guard lk(mu_); fingerprint = compute_fingerprint_locked(); @@ -918,11 +937,11 @@ int Gitmount::open_commits(std::shared_ptr* out) { ok = repo_->list_commits(pushes, [this] { mu_.unlock(); }, [this] { mu_.lock(); }, &buffer) == 0; + } catch (...) { + ok = false; // e.g. bad_alloc: generation failed, retry on next open } g.lock(); - commits_generating_ = false; - ++commits_epoch_; { std::lock_guard lk(mu_); if (ok) { @@ -934,7 +953,7 @@ int Gitmount::open_commits(std::shared_ptr* out) { // Failure: half-built buffer dropped, fingerprint untouched — "as if // never generated"; the next open retries from scratch (§3.5). } - commits_cv_.notify_all(); + fin.finish(); // reset flag, advance epoch, wake riders (§3.4/§3.5) return ok ? 0 : -EIO; } @@ -1010,120 +1029,142 @@ void Gitmount::fill_file_stat(struct stat* st, std::int64_t mtime, std::uint64_t // --------------------------------------------------------------------------- int Gitmount::cb_getattr(const char* path_c, struct stat* st, struct fuse_file_info*) { - Gitmount* fs = self(); - const std::string path(path_c); - std::lock_guard lk(fs->mu_); - - Node node; - const int rc = fs->resolve_locked(path, &node); - if (rc != 0) return rc; + // Boundary guard (issue #4): no exception may escape a FUSE callback into + // libfuse's C frames — allocation failure maps to ENOMEM, anything else + // to EIO. + try { + Gitmount* fs = self(); + const std::string path(path_c); + std::lock_guard lk(fs->mu_); + + Node node; + const int rc = fs->resolve_locked(path, &node); + if (rc != 0) return rc; - switch (node.type) { - case Node::Type::RootDir: - case Node::Type::EntryDir: - case Node::Type::GroupDir: - fs->fill_dir_stat(st, fs->mount_time_); // mount-time stamps (§3.2) - break; - case Node::Type::TreeDir: - case Node::Type::SubmoduleDir: - fs->fill_dir_stat(st, node.commit_time); - break; - case Node::Type::BlobFile: { - // Header-only size: no full decompression for ordinary blobs and no - // revwalk here (RFC 0000 §3.2/§3.3). - std::uint64_t size = 0; - const int rc2 = fs->repo_->blob_size(node.blob_oid, &size); - if (rc2 != 0) return -rc2; - fs->fill_file_stat(st, node.commit_time, size, S_IFREG | (node.executable ? 0755u : 0644u)); - break; - } - case Node::Type::Symlink: { - // Explicit exception (§3.2): st_size is the truncation-semantics - // length — the first NUL locates the truncation point. - BlobView view; - const int rc2 = fs->load_blob_locked(node.blob_oid, &view); - if (rc2 != 0) return -rc2; - const void* nulp = std::memchr(view.data(), '\0', view.size()); - const std::uint64_t len = - nulp ? static_cast(static_cast(nulp) - view.data()) - : view.size(); - fs->fill_file_stat(st, node.commit_time, len, S_IFLNK | 0777); - break; - } - case Node::Type::SubmoduleMarker: { - const std::string content = fs->submodule_marker_content_locked( - node.commit_root_tree, node.marker_path, node.gitlink_oid); - fs->fill_file_stat(st, node.commit_time, content.size(), S_IFREG | 0644); - break; - } - case Node::Type::CommitsFile: { - // Pure cache read: never triggers revwalk or fingerprint recompute; - // st_size = 0 before first generation (RFC 0000 §3.3/§3.5). - const std::uint64_t size = fs->commits_buffer_ ? fs->commits_buffer_->size() : 0; - const std::int64_t mtime = fs->commits_buffer_ ? fs->commits_generated_at_ : fs->mount_time_; - fs->fill_file_stat(st, mtime, size, S_IFREG | 0444); - break; + switch (node.type) { + case Node::Type::RootDir: + case Node::Type::EntryDir: + case Node::Type::GroupDir: + fs->fill_dir_stat(st, fs->mount_time_); // mount-time stamps (§3.2) + break; + case Node::Type::TreeDir: + case Node::Type::SubmoduleDir: + fs->fill_dir_stat(st, node.commit_time); + break; + case Node::Type::BlobFile: { + // Header-only size: no full decompression for ordinary blobs and no + // revwalk here (RFC 0000 §3.2/§3.3). + std::uint64_t size = 0; + const int rc2 = fs->repo_->blob_size(node.blob_oid, &size); + if (rc2 != 0) return -rc2; + fs->fill_file_stat(st, node.commit_time, size, S_IFREG | (node.executable ? 0755u : 0644u)); + break; + } + case Node::Type::Symlink: { + // Explicit exception (§3.2): st_size is the truncation-semantics + // length — the first NUL locates the truncation point. + BlobView view; + const int rc2 = fs->load_blob_locked(node.blob_oid, &view); + if (rc2 != 0) return -rc2; + const void* nulp = std::memchr(view.data(), '\0', view.size()); + const std::uint64_t len = + nulp ? static_cast(static_cast(nulp) - view.data()) + : view.size(); + fs->fill_file_stat(st, node.commit_time, len, S_IFLNK | 0777); + break; + } + case Node::Type::SubmoduleMarker: { + const std::string content = fs->submodule_marker_content_locked( + node.commit_root_tree, node.marker_path, node.gitlink_oid); + fs->fill_file_stat(st, node.commit_time, content.size(), S_IFREG | 0644); + break; + } + case Node::Type::CommitsFile: { + // Pure cache read: never triggers revwalk or fingerprint recompute; + // st_size = 0 before first generation (RFC 0000 §3.3/§3.5). + const std::uint64_t size = fs->commits_buffer_ ? fs->commits_buffer_->size() : 0; + const std::int64_t mtime = + fs->commits_buffer_ ? fs->commits_generated_at_ : fs->mount_time_; + fs->fill_file_stat(st, mtime, size, S_IFREG | 0444); + break; + } + case Node::Type::JsonFile: + fs->fill_file_stat(st, fs->mount_time_, fs->json_content_.size(), S_IFREG | 0444); + break; } - case Node::Type::JsonFile: - fs->fill_file_stat(st, fs->mount_time_, fs->json_content_.size(), S_IFREG | 0444); - break; - } - st->st_ino = fs->inos_.register_path(path); - return 0; + st->st_ino = fs->inos_.register_path(path); + return 0; + } catch (const std::bad_alloc&) { + return -ENOMEM; + } catch (...) { + return -EIO; + } } int Gitmount::cb_readlink(const char* path_c, char* buf, std::size_t size) { - Gitmount* fs = self(); - std::lock_guard lk(fs->mu_); + try { + Gitmount* fs = self(); + std::lock_guard lk(fs->mu_); - Node node; - const int rc = fs->resolve_locked(path_c, &node); - if (rc != 0) return rc; - if (node.type != Node::Type::Symlink) return -EINVAL; - - BlobView view; - const int rc2 = fs->load_blob_locked(node.blob_oid, &view); - if (rc2 != 0) return -rc2; - - // Truncate at the first NUL (kernel targets cannot contain NUL); an empty - // blob is an empty target; truncation length >= PATH_MAX is ENAMETOOLONG - // (boundary pinned to >= in RFC 0000 §3.3). - const char* data = view.data(); - std::size_t len = view.size(); - const void* nulp = std::memchr(data, '\0', view.size()); - if (nulp) len = static_cast(static_cast(nulp) - data); - if (len >= PATH_MAX) return -ENAMETOOLONG; - if (size == 0) return -EINVAL; - const std::size_t copy = std::min(len, size - 1); - std::memcpy(buf, data, copy); - buf[copy] = '\0'; - return 0; + Node node; + const int rc = fs->resolve_locked(path_c, &node); + if (rc != 0) return rc; + if (node.type != Node::Type::Symlink) return -EINVAL; + + BlobView view; + const int rc2 = fs->load_blob_locked(node.blob_oid, &view); + if (rc2 != 0) return -rc2; + + // Truncate at the first NUL (kernel targets cannot contain NUL); an empty + // blob is an empty target; truncation length >= PATH_MAX is ENAMETOOLONG + // (boundary pinned to >= in RFC 0000 §3.3). + const char* data = view.data(); + std::size_t len = view.size(); + const void* nulp = std::memchr(data, '\0', view.size()); + if (nulp) len = static_cast(static_cast(nulp) - data); + if (len >= PATH_MAX) return -ENAMETOOLONG; + if (size == 0) return -EINVAL; + const std::size_t copy = std::min(len, size - 1); + std::memcpy(buf, data, copy); + buf[copy] = '\0'; + return 0; + } catch (const std::bad_alloc&) { + return -ENOMEM; + } catch (...) { + return -EIO; + } } int Gitmount::cb_opendir(const char* path_c, struct fuse_file_info* fi) { - Gitmount* fs = self(); - const std::string path(path_c); - std::lock_guard lk(fs->mu_); + try { + Gitmount* fs = self(); + const std::string path(path_c); + std::lock_guard lk(fs->mu_); - Node node; - const int rc = fs->resolve_locked(path, &node); - if (rc != 0) return rc; + Node node; + const int rc = fs->resolve_locked(path, &node); + if (rc != 0) return rc; - std::vector entries; - if (fs->list_dir_locked(path, node, &entries) != 0) return -ENOTDIR; + std::vector entries; + if (fs->list_dir_locked(path, node, &entries) != 0) return -ENOTDIR; - // Register inodes for every listed entry (lazy registration on readdir, - // RFC 0000 §3.2) and pin the snapshot on fi->fh for stable offsets within - // this directory stream (§3.3). - std::string parent = path == "/" ? "" : path; - for (auto& e : entries) { - const std::string child = parent + "/" + e.name; - e.ino = fs->inos_.register_path(child); - } + // Register inodes for every listed entry (lazy registration on readdir, + // RFC 0000 §3.2) and pin the snapshot on fi->fh for stable offsets within + // this directory stream (§3.3). + std::string parent = path == "/" ? "" : path; + for (auto& e : entries) { + const std::string child = parent + "/" + e.name; + e.ino = fs->inos_.register_path(child); + } - fi->fh = reinterpret_cast(new DirList{std::move(entries)}); - return 0; + fi->fh = reinterpret_cast(new DirList{std::move(entries)}); + return 0; + } catch (const std::bad_alloc&) { + return -ENOMEM; + } catch (...) { + return -EIO; + } } int Gitmount::cb_readdir(const char*, void* buf, fuse_fill_dir_t filler, off_t offset, @@ -1150,131 +1191,141 @@ int Gitmount::cb_releasedir(const char*, struct fuse_file_info* fi) { } int Gitmount::cb_open(const char* path_c, struct fuse_file_info* fi) { - Gitmount* fs = self(); - const std::string path(path_c); + try { + Gitmount* fs = self(); + const std::string path(path_c); - // Only O_RDONLY opens are valid; write flags get EROFS (RFC 0000 §3.3). - if ((fi->flags & O_ACCMODE) != O_RDONLY) return -EROFS; + // Only O_RDONLY opens are valid; write flags get EROFS (RFC 0000 §3.3). + if ((fi->flags & O_ACCMODE) != O_RDONLY) return -EROFS; - std::lock_guard lk(fs->mu_); - Node node; - const int rc = fs->resolve_locked(path, &node); - if (rc != 0) return rc; + std::lock_guard lk(fs->mu_); + Node node; + const int rc = fs->resolve_locked(path, &node); + if (rc != 0) return rc; - auto* handle = new Handle(); - switch (node.type) { - case Node::Type::BlobFile: { - // Oversized admission via header-only size (boundary is >=, §3.5): - // decompress once OUTSIDE the lock and pin on this handle — every - // read of this open slices the pinned block (§3.3/§3.5). - std::uint64_t size = 0; - const int rc2 = fs->repo_->blob_size(node.blob_oid, &size); - if (rc2 != 0) { - delete handle; - return -rc2; - } - if (size >= fs->blob_cache_.capacity()) { - fs->mu_.unlock(); - std::string data; - const int rc3 = fs->decompress_blob_unlocked(node.blob_oid, &data); - fs->mu_.lock(); - if (rc3 != 0) { - delete handle; - return -rc3; + // unique_ptr so the handle is freed on the exception paths too. + auto handle = std::make_unique(); + switch (node.type) { + case Node::Type::BlobFile: { + // Oversized admission via header-only size (boundary is >=, §3.5): + // decompress once OUTSIDE the lock and pin on this handle — every + // read of this open slices the pinned block (§3.3/§3.5). + std::uint64_t size = 0; + const int rc2 = fs->repo_->blob_size(node.blob_oid, &size); + if (rc2 != 0) return -rc2; + if (size >= fs->blob_cache_.capacity()) { + // ScopedUnlock re-locks mu_ on every exit path, including the + // bad_alloc of the (unbounded) oversized decompression (issue #4). + std::string data; + int rc3 = 0; + { + ScopedUnlock unlock(fs->mu_); + rc3 = fs->decompress_blob_unlocked(node.blob_oid, &data); + } + if (rc3 != 0) return -rc3; + handle->kind = Handle::Kind::PinnedBlob; + handle->data = std::move(data); + } else { + handle->kind = Handle::Kind::Plain; } - handle->kind = Handle::Kind::PinnedBlob; - handle->data = std::move(data); - } else { - handle->kind = Handle::Kind::Plain; + break; } - break; - } - case Node::Type::Symlink: - handle->kind = Handle::Kind::Plain; // readlink is the access path - break; - case Node::Type::CommitsFile: { - // First open triggers generation; the buffer version is pinned on - // this handle until release (RFC 0000 §3.3/§3.5). open_commits takes - // its own (outer) generation lock — mu_ is released while it runs. - fs->mu_.unlock(); - std::shared_ptr buffer; - const int rc2 = fs->open_commits(&buffer); - fs->mu_.lock(); - if (rc2 != 0) { - delete handle; - return rc2; + case Node::Type::Symlink: + handle->kind = Handle::Kind::Plain; // readlink is the access path + break; + case Node::Type::CommitsFile: { + // First open triggers generation; the buffer version is pinned on + // this handle until release (RFC 0000 §3.3/§3.5). open_commits takes + // its own (outer) generation lock — mu_ is released while it runs. + std::shared_ptr buffer; + int rc2 = 0; + { + ScopedUnlock unlock(fs->mu_); + rc2 = fs->open_commits(&buffer); + } + if (rc2 != 0) return rc2; + handle->kind = Handle::Kind::PinnedCommits; + handle->shared = std::move(buffer); + break; } - handle->kind = Handle::Kind::PinnedCommits; - handle->shared = std::move(buffer); - break; + case Node::Type::JsonFile: + // Immutable for the mount: no pinning needed (§3.6). + handle->kind = Handle::Kind::Synthetic; + handle->shared = std::make_shared(fs->json_content_); + break; + case Node::Type::SubmoduleMarker: + handle->kind = Handle::Kind::Synthetic; + handle->shared = std::make_shared(fs->submodule_marker_content_locked( + node.commit_root_tree, node.marker_path, node.gitlink_oid)); + break; + case Node::Type::RootDir: + case Node::Type::EntryDir: + case Node::Type::GroupDir: + case Node::Type::TreeDir: + case Node::Type::SubmoduleDir: + handle->kind = Handle::Kind::Dir; + break; } - case Node::Type::JsonFile: - // Immutable for the mount: no pinning needed (§3.6). - handle->kind = Handle::Kind::Synthetic; - handle->shared = std::make_shared(fs->json_content_); - break; - case Node::Type::SubmoduleMarker: - handle->kind = Handle::Kind::Synthetic; - handle->shared = std::make_shared(fs->submodule_marker_content_locked( - node.commit_root_tree, node.marker_path, node.gitlink_oid)); - break; - case Node::Type::RootDir: - case Node::Type::EntryDir: - case Node::Type::GroupDir: - case Node::Type::TreeDir: - case Node::Type::SubmoduleDir: - handle->kind = Handle::Kind::Dir; - break; + fi->fh = reinterpret_cast(handle.release()); + return 0; + } catch (const std::bad_alloc&) { + return -ENOMEM; + } catch (...) { + return -EIO; } - fi->fh = reinterpret_cast(handle); - return 0; } int Gitmount::cb_read(const char* path_c, char* buf, std::size_t size, off_t offset, struct fuse_file_info* fi) { - Gitmount* fs = self(); - auto* handle = reinterpret_cast(fi->fh); - if (!handle) return -EINVAL; - - const char* data = nullptr; - std::size_t len = 0; - BlobView view; // keeps a cache hit alive while copying - - switch (handle->kind) { - case Handle::Kind::PinnedBlob: - data = handle->data.data(); - len = handle->data.size(); - break; - case Handle::Kind::PinnedCommits: - case Handle::Kind::Synthetic: - data = handle->shared->data(); - len = handle->shared->size(); - break; - case Handle::Kind::Plain: { - // Re-resolve per read; cacheable blobs go through the LRU (§3.5). - std::lock_guard lk(fs->mu_); - Node node; - const int rc = fs->resolve_locked(path_c, &node); - if (rc != 0) return rc; - if (node.type == Node::Type::Symlink) return -EINVAL; - if (node.type != Node::Type::BlobFile) return -EISDIR; - const int rc2 = fs->load_blob_locked(node.blob_oid, &view); - if (rc2 != 0) return -rc2; - data = view.data(); - len = view.size(); - break; + try { + Gitmount* fs = self(); + auto* handle = reinterpret_cast(fi->fh); + if (!handle) return -EINVAL; + + const char* data = nullptr; + std::size_t len = 0; + BlobView view; // keeps a cache hit alive while copying + + switch (handle->kind) { + case Handle::Kind::PinnedBlob: + data = handle->data.data(); + len = handle->data.size(); + break; + case Handle::Kind::PinnedCommits: + case Handle::Kind::Synthetic: + data = handle->shared->data(); + len = handle->shared->size(); + break; + case Handle::Kind::Plain: { + // Re-resolve per read; cacheable blobs go through the LRU (§3.5). + std::lock_guard lk(fs->mu_); + Node node; + const int rc = fs->resolve_locked(path_c, &node); + if (rc != 0) return rc; + if (node.type == Node::Type::Symlink) return -EINVAL; + if (node.type != Node::Type::BlobFile) return -EISDIR; + const int rc2 = fs->load_blob_locked(node.blob_oid, &view); + if (rc2 != 0) return -rc2; + data = view.data(); + len = view.size(); + break; + } + case Handle::Kind::Dir: + return -EISDIR; } - case Handle::Kind::Dir: - return -EISDIR; - } - // Slice [offset, offset+size) with bounds clipping (RFC 0000 §3.3). - if (offset < 0) return -EINVAL; - const std::uint64_t off = static_cast(offset); - if (off >= len) return 0; - const std::size_t copy = static_cast(std::min(size, len - off)); - std::memcpy(buf, data + off, copy); - return static_cast(copy); + // Slice [offset, offset+size) with bounds clipping (RFC 0000 §3.3). + if (offset < 0) return -EINVAL; + const std::uint64_t off = static_cast(offset); + if (off >= len) return 0; + const std::size_t copy = static_cast(std::min(size, len - off)); + std::memcpy(buf, data + off, copy); + return static_cast(copy); + } catch (const std::bad_alloc&) { + return -ENOMEM; + } catch (...) { + return -EIO; + } } int Gitmount::cb_release(const char*, struct fuse_file_info* fi) { @@ -1284,18 +1335,24 @@ int Gitmount::cb_release(const char*, struct fuse_file_info* fi) { } int Gitmount::cb_statfs(const char*, struct statvfs* st) { - Gitmount* fs = self(); - std::lock_guard lk(fs->mu_); - const std::uint64_t bytes = fs->repo_->odb_disk_bytes(); - std::memset(st, 0, sizeof(*st)); - st->f_bsize = 4096; - st->f_frsize = 4096; - st->f_blocks = (bytes + 4095) / 4096; // local ODB usage only (§3.3) - st->f_bfree = 0; // read-only volume convention: df shows 100% used - st->f_bavail = 0; - st->f_files = 0; // exact inode counting would need a full walk (§3.3) - st->f_ffree = 0; - return 0; + try { + Gitmount* fs = self(); + std::lock_guard lk(fs->mu_); + const std::uint64_t bytes = fs->repo_->odb_disk_bytes(); + std::memset(st, 0, sizeof(*st)); + st->f_bsize = 4096; + st->f_frsize = 4096; + st->f_blocks = (bytes + 4095) / 4096; // local ODB usage only (§3.3) + st->f_bfree = 0; // read-only volume convention: df shows 100% used + st->f_bavail = 0; + st->f_files = 0; // exact inode counting would need a full walk (§3.3) + st->f_ffree = 0; + return 0; + } catch (const std::bad_alloc&) { + return -ENOMEM; + } catch (...) { + return -EIO; + } } int Gitmount::cb_erofs() { return -EROFS; } diff --git a/src/gitmount.hpp b/src/gitmount.hpp index 6cf3e61..285f199 100644 --- a/src/gitmount.hpp +++ b/src/gitmount.hpp @@ -13,7 +13,6 @@ // * segmented LRU load (lookup in lock, decompress outside, re-check in) #pragma once -#include #include #include #include @@ -25,6 +24,7 @@ #include "gitrepo.hpp" #include "ino_registry.hpp" +#include "lock_guards.hpp" #include "object_cache.hpp" #include "path_map.hpp" @@ -190,11 +190,9 @@ class Gitmount { MetaLruCache meta_cache_; // Tier-2: raw trees + commit facts (§3.5) InoRegistry inos_; - // /commits single-flight state (RFC 0000 §3.4/§3.5). - std::mutex commits_gen_mu_; // outer lock; never held with mu_ inner-reversed - std::condition_variable commits_cv_; - bool commits_generating_ = false; // guarded by commits_gen_mu_ - std::uint64_t commits_epoch_ = 0; // guarded by commits_gen_mu_ + // /commits single-flight state machine (RFC 0000 §3.4/§3.5). Its internal + // mutex is the outermost lock; never held with mu_ inner-reversed. + SingleFlight commits_flight_; // guarded by mu_: std::shared_ptr commits_buffer_; std::string commits_fingerprint_; diff --git a/src/lock_guards.hpp b/src/lock_guards.hpp new file mode 100644 index 0000000..4b3d414 --- /dev/null +++ b/src/lock_guards.hpp @@ -0,0 +1,141 @@ +// gitmount — read-only git-to-FUSE filesystem (RFC 0000). +// SPDX-FileCopyrightText: 2026 The gitmount authors +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Exception-safety lock guards (RFC 0000 §3.4 concurrency model). +// +// ScopedUnlock replaces the hand-written `mu_.unlock() … mu_.lock()` windows +// of the segmented-loading path: the destructor re-locks during exception +// unwinding BEFORE the surrounding std::lock_guard runs, so the outer guard +// always destructs a locked mutex — an allocation failure inside a window +// (repository-content-sized, e.g. std::bad_alloc from an uncapped object +// read) can no longer turn into unlock-of-unlocked-mutex UB. +// +// SingleFlight owns the /commits first-open generation state machine +// (RFC 0000 §3.4/§3.5): whichever way the generator exits — including an +// exception — the in-flight flag is reset, the epoch advances and riders are +// woken, so a failed generation maps to EIO-and-retry instead of parking +// every later open on the condition variable (and, transitively, exhausting +// the libfuse worker pool). +#pragma once + +#include +#include +#include +#include + +namespace gitmount { + +// Unlocks the given mutex on construction, re-locks it on destruction (the +// normal scope-exit path and the exception-unwinding path alike). Not +// copyable. The mutex must outlive the guard and be locked at construction. +class ScopedUnlock { + public: + explicit ScopedUnlock(std::mutex& m) : m_(m) { m_.unlock(); } + + ScopedUnlock(const ScopedUnlock&) = delete; + ScopedUnlock& operator=(const ScopedUnlock&) = delete; + + ~ScopedUnlock() { m_.lock(); } + + private: + std::mutex& m_; +}; + +// Single-flight state for one idempotent-on-failure generation ("commits"): +// a mutex/condvar pair plus an in-flight flag and a wake-up epoch. The +// caller-visible pattern (see open_commits): +// +// auto g = flight.hold(); +// if (flight.begin_or_wait(g)) { // generator (flag now set) +// GeneratorFinish fin(flight, g); // safety net on every exit path +// g.unlock(); +// … generate (may throw / fail) … +// g.lock(); +// … publish result … +// fin.finish(); // or let ~GeneratorFinish do it +// } else { // rider: generation finished +// … inspect the shared outcome … +// } +// +// Riders wait for the epoch to CHANGE, not for a "success" value: they share +// whatever outcome the generation left behind (a published buffer, or the +// absence of one = failure). finish() bumps the epoch exactly once per +// generation, so each generation's riders wake exactly once. +// +// Lock ordering: the internal mutex is the OUTERMOST lock of the /commits +// path (it never nests inside the filesystem-wide mutex being held while it +// is acquired, only the reverse) — callers must preserve that order. +class SingleFlight { + public: + SingleFlight() = default; + SingleFlight(const SingleFlight&) = delete; + SingleFlight& operator=(const SingleFlight&) = delete; + + // Returns a lock on the internal mutex; required by begin_or_wait/finish. + std::unique_lock hold() { return std::unique_lock(mu_); } + + // g must lock this->mu_ (via hold()) and be held. When no generation is + // in flight: marks one in flight and returns true (caller generates). + // Otherwise waits (releasing g) until the in-flight generation finishes + // and returns false (caller rides along and inspects the shared outcome). + bool begin_or_wait(std::unique_lock& g) { + if (!generating_) { + generating_ = true; + return true; + } + const std::uint64_t observed = epoch_; + cv_.wait(g, [&] { return epoch_ != observed; }); + return false; + } + + // Ends the in-flight generation: flag reset, epoch advanced, riders woken. + // g must lock this->mu_ and be held. Idempotent-safe (a second call only + // bumps the epoch and re-notifies) but each generation must finish exactly + // once — GeneratorFinish's done flag is the single-shot guarantee. + void finish(std::unique_lock&) { + generating_ = false; + ++epoch_; + cv_.notify_all(); + } + + // Current epoch; g must lock this->mu_ and be held. Diagnostics/tests. + std::uint64_t epoch(std::unique_lock&) const { return epoch_; } + + private: + std::mutex mu_; + std::condition_variable cv_; + bool generating_ = false; // guarded by mu_ + std::uint64_t epoch_ = 0; // guarded by mu_; bumped once per generation +}; + +// RAII counterpart of SingleFlight::finish for the generator thread: on +// destruction (any exit path, including exception unwinding) ends the +// generation — re-locking through the SAME unique_lock when it was left +// unlocked for the generation itself (locking the raw mutex here would +// self-deadlock the normal path, where g is already held again). finish() +// marks the generation ended so a manual call followed by the destructor +// finishes exactly once. +class GeneratorFinish { + public: + GeneratorFinish(SingleFlight& flight, std::unique_lock& g) : flight_(flight), g_(g) {} + + GeneratorFinish(const GeneratorFinish&) = delete; + GeneratorFinish& operator=(const GeneratorFinish&) = delete; + + ~GeneratorFinish() { finish(); } + + void finish() { + if (done_) return; + if (!g_.owns_lock()) g_.lock(); + flight_.finish(g_); + done_ = true; + } + + private: + SingleFlight& flight_; + std::unique_lock& g_; + bool done_ = false; +}; + +} // namespace gitmount diff --git a/tests/unit/test_lock_guards.cpp b/tests/unit/test_lock_guards.cpp new file mode 100644 index 0000000..7a696bc --- /dev/null +++ b/tests/unit/test_lock_guards.cpp @@ -0,0 +1,217 @@ +// gitmount unit tests — exception-safety lock guards (issue #4, RFC 0000 §3.4). +// SPDX-FileCopyrightText: 2026 The gitmount authors +// SPDX-License-Identifier: GPL-3.0-or-later +#include + +#include +#include +#include +#include +#include + +#include "lock_guards.hpp" + +using gitmount::GeneratorFinish; +using gitmount::ScopedUnlock; +using gitmount::SingleFlight; + +namespace { + +// try_lock from a fresh thread: true exactly when m is unlocked (avoids the +// same-thread self-try ambiguity of a default mutex). +bool try_lock_from_thread(std::mutex& m) { + bool got = false; + std::thread probe([&] { + if (m.try_lock()) { + got = true; + m.unlock(); + } + }); + probe.join(); + return got; +} + +// Polls flag for up to ~10s; a wedged guard then fails the test instead of +// hanging the suite (the worker threads are detached, so a failure can still +// exit the process cleanly). +bool settled_within_deadline(const std::atomic& flag) { + for (int i = 0; i < 1000; ++i) { + if (flag.load()) return true; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return flag.load(); +} + +} // namespace + +// --------------------------------------------------------------------------- +// ScopedUnlock +// --------------------------------------------------------------------------- + +TEST_CASE("ScopedUnlock leaves the mutex unlocked while alive and relocks at scope exit", + "[guards]") { + std::mutex m; + m.lock(); + { + ScopedUnlock u(m); + CHECK(try_lock_from_thread(m)); // window: another thread can take it + } + CHECK_FALSE(try_lock_from_thread(m)); // scope end: locked again + m.unlock(); // restore for destruction +} + +TEST_CASE("ScopedUnlock relocks during exception unwinding; the outer lock_guard stays safe", + "[guards]") { + std::mutex m; + bool caught = false; + try { + std::lock_guard lk(m); // the production pattern (cb_*) + { + ScopedUnlock u(m); + throw std::runtime_error("allocation failed inside the window"); + } + } catch (const std::runtime_error&) { + caught = true; + // ~ScopedUnlock ran before ~lock_guard, so the guard destructed a LOCKED + // mutex (no unlock-of-unlocked UB). The mutex itself must now be in a + // normally usable state: no deadlock, no double-unlock corruption. + m.lock(); + m.unlock(); + CHECK(try_lock_from_thread(m)); + m.lock(); + m.unlock(); + } + REQUIRE(caught); +} + +// --------------------------------------------------------------------------- +// SingleFlight +// --------------------------------------------------------------------------- +// The rider threads mirror open_commits' rider path: enter while a generation +// is in flight, wait for the epoch to change, then share the published +// outcome. Handshake: `parked` is set while the rider holds the flight mutex, +// so once the generator (re)acquires it the rider is parked on the condvar. + +TEST_CASE("SingleFlight: a throwing generator resets the flight and wakes riders in time", + "[guards]") { + SingleFlight sf; + std::atomic in_flight{false}; + std::atomic parked{false}; + std::atomic generation_ok{true}; // the shared outcome + std::atomic rider_returned{false}; + std::atomic rider_saw_failure{false}; + std::atomic rider_finished{false}; + + std::thread rider([&] { + while (!in_flight.load()) std::this_thread::yield(); + { + auto g = sf.hold(); + parked.store(true); // mutex held: the generator cannot finish yet + const bool generator = sf.begin_or_wait(g); + const bool ok = generation_ok.load(); // share the outcome… + rider_saw_failure = !ok; + rider_returned = !generator; // …then report (ordering is load-bearing) + } + rider_finished = true; + }); + rider.detach(); + + auto g = sf.hold(); + REQUIRE(sf.begin_or_wait(g)); // this thread is the generator + bool threw = false; + try { + GeneratorFinish fin(sf, g); + g.unlock(); + in_flight.store(true); + while (!parked.load()) std::this_thread::yield(); + generation_ok.store(false); // the failure is settled before the flight ends + throw std::runtime_error("bad_alloc during generation"); + } catch (const std::runtime_error&) { + threw = true; + } + REQUIRE(threw); + REQUIRE(g.owns_lock()); // ~GeneratorFinish re-locked through the same unique_lock + + g.unlock(); // let the rider re-acquire inside the condvar wait and wake + REQUIRE(settled_within_deadline(rider_returned)); // rider woke: no wedge + REQUIRE(rider_returned.load()); // …as a rider, not a generator + REQUIRE(rider_saw_failure.load()); // …and saw the failed outcome + REQUIRE(settled_within_deadline(rider_finished)); // rider fully done with sf + + // Flag reset: the next begin_or_wait immediately becomes the generator + // (open_commits' "next open retries" semantics, §3.5). + g.lock(); + REQUIRE(sf.begin_or_wait(g)); + sf.finish(g); + g.unlock(); +} + +TEST_CASE("SingleFlight: a successful generation shares its outcome with the rider", "[guards]") { + SingleFlight sf; + std::atomic in_flight{false}; + std::atomic parked{false}; + std::atomic outcome_ok{false}; // stands in for commits_buffer_ + std::atomic rider_returned{false}; + std::atomic rider_saw_success{false}; + std::atomic rider_finished{false}; + + std::thread rider([&] { + while (!in_flight.load()) std::this_thread::yield(); + { + auto g = sf.hold(); + parked.store(true); + const bool generator = sf.begin_or_wait(g); + const bool ok = outcome_ok.load(); + rider_saw_success = ok; + rider_returned = !generator; + } + rider_finished = true; + }); + rider.detach(); + + auto g = sf.hold(); + REQUIRE(sf.begin_or_wait(g)); // generator + { + GeneratorFinish fin(sf, g); + g.unlock(); + in_flight.store(true); + while (!parked.load()) std::this_thread::yield(); + // g.lock() can only return once the rider has parked on the condvar. + g.lock(); + outcome_ok.store(true); // publish while still in flight + fin.finish(); // normal-path manual finish (done_ set; dtor no-ops) + } + g.unlock(); + + REQUIRE(settled_within_deadline(rider_returned)); + REQUIRE(rider_returned.load()); + REQUIRE(rider_saw_success.load()); + REQUIRE(settled_within_deadline(rider_finished)); + + // Ready for the next generation right away. + auto g2 = sf.hold(); + REQUIRE(sf.begin_or_wait(g2)); + sf.finish(g2); +} + +TEST_CASE("SingleFlight: finish is idempotent-safe and GeneratorFinish fires exactly once", + "[guards]") { + SingleFlight sf; + auto g = sf.hold(); + REQUIRE(sf.begin_or_wait(g)); + const std::uint64_t before = sf.epoch(g); + { + GeneratorFinish fin(sf, g); + fin.finish(); // manual + } // ~GeneratorFinish: already done — must not finish again + CHECK(sf.epoch(g) == before + 1); + CHECK(sf.begin_or_wait(g)); // flag reset, next generation can start + + // A bare double finish is not UB: it only bumps the epoch again and + // re-notifies (no riders are parked in this scenario). + sf.finish(g); + sf.finish(g); + CHECK(sf.epoch(g) == before + 3); + CHECK(sf.begin_or_wait(g)); + sf.finish(g); +}