From 92630a55702e9f02baee7ee32697b0f00549bee3 Mon Sep 17 00:00:00 2001 From: liyigang Date: Tue, 24 Nov 2026 17:09:59 +0800 Subject: [PATCH] fix: prevent file watcher dead after stopping one of same inode paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Root cause: GLib inotify backend shares watch descriptors by inode; when several DWatcher instances watch the same directory through different paths (symlink or bind mount), stopping one cancels the shared inotify watch and leaves the others deaf until the 4s missing-scan of GLib re-adds them (events in between are lost), and the leftover path bucket makes later watchers attach to a dead watch 2. Fix: add MonitorKeepAliveRegistry counting active watchers by full (st_dev, st_ino); a stopping watcher parks its GFileMonitor without cancel while others for the same inode stay active, and the last one cancels and releases all parked monitors; disconnect the changed handler under the registry lock to avoid concurrent-stop use-after-free; keep a full-width inode key to avoid truncation 3. Reuse a parked monitor on restart only when the watch type and the creation path both match: GLib builds event child paths from the path used to create the monitor, so reusing one across aliased paths (/home/x vs /data/home/x) makes events carry the old prefix and upper layers drop them; matching reuse still bounds monitor growth 4. Impact: watchers on aliased paths keep receiving events after one path stops, and always report them under their own path; new watchers work after all watchers for an inode stop; non-local paths fall back to direct cancel without regression Log: Fix file watcher becoming deaf after stopping one same-inode path Influence: 1. Test watching a directory and its symlink together, then stop one watcher; the remaining one still receives create/delete events 2. Test the event url of a restarted watcher stays under its own path when a monitor of a sibling alias path is parked for the same inode 3. Test the file manager round trip home -> data disk -> home (two paths of the same inode, the new view starts before the old one stops) keeps receiving events on both views 4. Test a fresh watcher works after all watchers for an inode stop 5. Verify non-local paths fall back to direct cancel without regression fix: 修复停止同一inode路径之一后文件监视器失效的问题 1. 根因:GLib的inotify后端按inode共享watch描述符,多条路径(符号链接或 绑定挂载)监视同一目录时,停止其中一条路径会cancel共享订阅,使其它 存活监视器失聪,直到GLib的missing轮询(4秒)重新加回订阅,期间的事件 全部丢失;残留的path桶还会让新建监视器挂到死订阅上 2. 方案:新增MonitorKeepAliveRegistry按完整(st_dev, st_ino)对活跃监视器 计数,停止方在同inode仍有其它活跃监视器时只寄存GFileMonitor而不cancel, 最后一个活跃者停止时才统一cancel并析构全部寄存监视器;在锁内断开changed 回调避免并发停止的悬垂指针;inode key保留完整宽度避免截断撞key 3. 仅在watch类型与"建该监视器时的本地路径"都一致时复用寄存监视器: GLib用建监视时的路径字符串拼事件child路径,跨别名路径复用(/home/x与 /data/home/x)会让事件带上旧前缀而被上层丢弃;按路径匹配的复用同样能 避免寄存桶无限增长 4. 影响:同一inode多路径监视时,停止一条路径不再影响其它路径收事件, 且事件始终落在该监视器自己的路径下;全部停止后新建监视器可正常工作; 非本地路径回退到直接cancel无回归 Log: 修复停止同一inode路径之一后文件监视器失效的问题 Influence: 1. 测试同时监视目录及其符号链接,停止其中一个监视器后,剩余的仍能收到事件 2. 测试同inode别名路径的监视器处于寄存状态时,重启的监视器上报的事件URL 仍在其自身路径下 3. 测试文件管理器"主目录 -> 数据盘 -> 主目录"往返(同inode两条路径,新视图 先于旧视图销毁而建立)后,两个视图都能正常收到事件 4. 测试该inode所有监视器停止后,新建监视器正常工作 5. 验证非本地路径回退到直接cancel,无回归 PMS: Task-398995 --- autotests/dfm-io-tests/tst_dfm_io.cpp | 172 +++++++++++++++++++++++++ src/dfm-io/dfm-io/dwatcher.cpp | 163 ++++++++++++++++++++++- src/dfm-io/dfm-io/private/dwatcher_p.h | 20 +++ 3 files changed, 350 insertions(+), 5 deletions(-) diff --git a/autotests/dfm-io-tests/tst_dfm_io.cpp b/autotests/dfm-io-tests/tst_dfm_io.cpp index da783bca..9c4da025 100644 --- a/autotests/dfm-io-tests/tst_dfm_io.cpp +++ b/autotests/dfm-io-tests/tst_dfm_io.cpp @@ -3,6 +3,16 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include +#include +#include +#include +#include +#include +#include + +#include + +USING_IO_NAMESPACE class tst_DfmIO : public QObject { @@ -12,6 +22,22 @@ private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void initialization_test(); + + // GLib inotify后端按inode共享watch描述符:对同一inode的两条路径分别建监视器后 + // cancel其一,存活者会永久收不到事件。用symlink构造同inode双路径精确复现 + // (g_file_new_for_path不解析symlink,两条路径各自建订阅、内核共享wd; + // 不能用"/dir/."作第二路径——g_file_new_for_path会把它canonicalize成"/dir")。 + void stopOnePathKeepsOtherPathMonitored(); + // 同一inode经不同路径监视(如UOS上/home是/data/home的bind挂载)时,不能把为A路径 + // 建的寄存监视器复用给B路径:GLib用"建监视时的路径字符串"拼事件child路径,跨路径 + // 复用会让事件带着旧前缀上报(如监视/data/...却报file:///home/...),上层按当前 + // 视图URL匹配不上,表现为监视器失效。用symlink构造两个路径精确复现。 + void parkedMonitorNotReusedAcrossPaths(); + void watcherRecoversAfterAllPathsStopped(); + // 文件管理器"主目录 -> 数据盘 -> 主目录"的往返:新视图的监视器总是先于旧视图销毁而 + // 建立,旧视图stop时同inode仍有存活者。若此时cancel掉共享的内核watch描述符,存活者 + // 到GLib的missing轮询(4秒)之前都收不到事件,切回主目录后表现为监视器失效。 + void watcherSurvivesRoundTripBetweenSameInodePaths(); }; void tst_DfmIO::initTestCase() @@ -30,5 +56,151 @@ void tst_DfmIO::initialization_test() QVERIFY(true); } +static bool createEmptyFile(const QString &path) +{ + QFile f(path); + return f.open(QIODevice::WriteOnly); +} + +void tst_DfmIO::stopOnePathKeepsOtherPathMonitored() +{ + QTemporaryDir tmpDir; + QVERIFY(tmpDir.isValid()); + const QString root = tmpDir.path(); + const QString link = root + "/sibling-link"; + QVERIFY(QFile::link(root, link)); + + DWatcher rootWatcher(QUrl::fromLocalFile(root)); + DWatcher linkWatcher(QUrl::fromLocalFile(link)); + QVERIFY(rootWatcher.start()); + QVERIFY(linkWatcher.start()); + + QSignalSpy rootAdded(&rootWatcher, &DWatcher::fileAdded); + QSignalSpy linkAdded(&linkWatcher, &DWatcher::fileAdded); + + // 停掉经由symlink路径的监视器:不应cancel共享订阅 + QVERIFY(linkWatcher.stop()); + + QVERIFY(createEmptyFile(root + "/after-stop.txt")); + + // root监视器应收到created事件 + QVERIFY(rootAdded.wait(3000)); + QCOMPARE(linkAdded.count(), 0); // 已停止的监视器不得收事件 + + QVERIFY(rootWatcher.stop()); + QFile::remove(root + "/after-stop.txt"); +} + +void tst_DfmIO::parkedMonitorNotReusedAcrossPaths() +{ + QTemporaryDir tmpDir; + QVERIFY(tmpDir.isValid()); + const QString root = tmpDir.path(); + const QString link = root + "/sibling-link"; + QVERIFY(QFile::link(root, link)); + + // 先经root路径建监视器,再由link路径建同inode的监视器,使root监视器可被寄存 + DWatcher rootWatcher(QUrl::fromLocalFile(root)); + QVERIFY(rootWatcher.start()); + + DWatcher linkWatcher(QUrl::fromLocalFile(link)); + QVERIFY(linkWatcher.start()); + + // 停掉root路径的监视器:其监视器进入寄存桶(不能cancel,否则link侧失聪) + QVERIFY(rootWatcher.stop()); + + // 为link路径重新建监视器:必须新建,不能复用登记在root路径名下的寄存监视器 + DWatcher revivedWatcher(QUrl::fromLocalFile(link)); + QVERIFY(revivedWatcher.start()); + + QSignalSpy added(&revivedWatcher, &DWatcher::fileAdded); + QVERIFY(createEmptyFile(link + "/after-revive.txt")); + + QVERIFY(added.wait(3000)); + // 事件URL必须落在本监视器自己的路径下(link),不能带root前缀 + const QUrl reported = added.first().at(0).toUrl(); + QCOMPARE(reported, QUrl::fromLocalFile(link + "/after-revive.txt")); + + QVERIFY(revivedWatcher.stop()); + QVERIFY(linkWatcher.stop()); + QFile::remove(link + "/after-revive.txt"); +} + +void tst_DfmIO::watcherRecoversAfterAllPathsStopped() +{ + QTemporaryDir tmpDir; + QVERIFY(tmpDir.isValid()); + const QString root = tmpDir.path(); + const QString link = root + "/sibling-link"; + QVERIFY(QFile::link(root, link)); + + { + DWatcher rootWatcher(QUrl::fromLocalFile(root)); + DWatcher linkWatcher(QUrl::fromLocalFile(link)); + QVERIFY(rootWatcher.start()); + QVERIFY(linkWatcher.start()); + QVERIFY(linkWatcher.stop()); + QVERIFY(rootWatcher.stop()); + } // 全部停止:最后一个stop应cancel并析构寄存的监视器,GLib状态自净 + + DWatcher freshWatcher(QUrl::fromLocalFile(root)); + QVERIFY(freshWatcher.start()); + QSignalSpy freshAdded(&freshWatcher, &DWatcher::fileAdded); + + QVERIFY(createEmptyFile(root + "/after-all-stopped.txt")); + QVERIFY(freshAdded.wait(3000)); + + QVERIFY(freshWatcher.stop()); + QFile::remove(root + "/after-all-stopped.txt"); +} + +void tst_DfmIO::watcherSurvivesRoundTripBetweenSameInodePaths() +{ + QTemporaryDir tmpDir; + QVERIFY(tmpDir.isValid()); + const QString root = tmpDir.path(); + const QString link = root + "/sibling-link"; + QVERIFY(QFile::link(root, link)); + + // 同inode的两条路径都会收到事件(各带自己的路径前缀),只关心"自己前缀"那条 + auto received = [](const QSignalSpy &spy, const QString &path) { + for (const QList &args : spy) { + if (!args.isEmpty() && args.first().toUrl() == QUrl::fromLocalFile(path)) + return true; + } + return false; + }; + + // 打开主目录视图 + DWatcher homeWatcher(QUrl::fromLocalFile(root)); + QVERIFY(homeWatcher.start()); + + // 切到数据盘视图(同inode的另一条路径),随后旧的主目录视图被销毁 + DWatcher dataWatcher(QUrl::fromLocalFile(link)); + QVERIFY(dataWatcher.start()); + QSignalSpy dataAdded(&dataWatcher, &DWatcher::fileAdded); + QVERIFY(homeWatcher.stop()); + + // 数据盘视图必须仍能收到事件 + QVERIFY(createEmptyFile(link + "/data-view.txt")); + QVERIFY(dataAdded.wait(3000)); + QVERIFY(received(dataAdded, link + "/data-view.txt")); + + // 切回主目录视图,随后数据盘视图被销毁 + DWatcher backWatcher(QUrl::fromLocalFile(root)); + QVERIFY(backWatcher.start()); + QSignalSpy backAdded(&backWatcher, &DWatcher::fileAdded); + QVERIFY(dataWatcher.stop()); + + // 回到主目录后监视器不能失效 + QVERIFY(createEmptyFile(root + "/home-view.txt")); + QVERIFY(backAdded.wait(3000)); + QVERIFY(received(backAdded, root + "/home-view.txt")); + + QVERIFY(backWatcher.stop()); + QFile::remove(link + "/data-view.txt"); + QFile::remove(root + "/home-view.txt"); +} + QTEST_MAIN(tst_DfmIO) #include "tst_dfm_io.moc" diff --git a/src/dfm-io/dfm-io/dwatcher.cpp b/src/dfm-io/dfm-io/dwatcher.cpp index facbca06..1ac6e6cd 100644 --- a/src/dfm-io/dfm-io/dwatcher.cpp +++ b/src/dfm-io/dfm-io/dwatcher.cpp @@ -8,9 +8,134 @@ #include "private/dwatcher_p.h" #include +#include +#include +#include +#include + +#include USING_IO_NAMESPACE +namespace { + +// 同一inode经不同路径(多挂载点/bind/符号链接)监视时,GLib的inotify后端按inode共享 +// 内核watch描述符:任一监视器cancel会误删共享订阅,使其它路径的存活监视器永久失聪, +// 且残留的path桶会让后续新建监视器挂到死订阅上。注册表按(st_dev, st_ino)对活跃监视器 +// 计数:仍有同inode其它活跃者时,停止方只寄存GFileMonitor而不cancel;最后一个活跃者 +// 停止时才统一cancel并析构全部寄存的监视器,此时GLib状态自净。 +// 并发停止同一inode的两个监视器时,寄存的监视器可能被并发方随doomed清空;因此在锁内 +// 先断开changed回调再入寄存桶,保证停止方在交还监视器后不再触碰它,避免悬垂指针。 +// 复用寄存监视器时除了watch类型,还必须限定"创建它时用的本地路径"完全一致: +// GLib的事件child路径是用建监视时那条路径字符串拼出来的(g_build_filename(dirname, name)), +// 而不是从inode反查。若把/home/u/x建的监视器交给/data/home/u/x(同inode)复用, +// 事件会以file:///home/u/x/...上报,上层按当前视图URL匹配不上,等同于监视器失效。 +class MonitorKeepAliveRegistry +{ +public: + static MonitorKeepAliveRegistry &instance() + { + static MonitorKeepAliveRegistry registry; + return registry; + } + + void addActive(InodeKey key) + { + if (key.isNull()) + return; + QMutexLocker locker(&mutex); + ++refCounts[key]; + } + + // 停止时调用:同inode仍有其它活跃监视器时,在锁内断开回调并寄存monitor(不cancel) + // 并返回true;否则清除计数,并通过doomed交还该inode全部寄存的监视器,由调用方在锁外 + // cancel析构(寄存桶已清空,且其中监视器的回调早已断开,并发停止方不再触碰它们)。 + bool retainOrPark(InodeKey key, GFileMonitor *monitor, DWatcher::WatchType type, + const QByteArray &path, gpointer userData, QList *doomed) + { + doomed->clear(); + if (key.isNull()) + return false; + QMutexLocker locker(&mutex); + const int remaining = refCounts.value(key) - 1; + if (remaining > 0) { + refCounts[key] = remaining; + g_signal_handlers_disconnect_by_data(monitor, userData); + parked[key].append(ParkedMonitor { monitor, type, path }); + return true; + } + refCounts.remove(key); + for (const ParkedMonitor &parkedMonitor : parked.value(key)) + doomed->append(parkedMonitor.monitor); + parked.remove(key); + return false; + } + + // start时取走本inode的寄存监视器复用(watch类型与建监视时的路径都必须一致)并计数, + // 避免反复start/stop在兄弟监视器存活期间不断新建监视器导致寄存桶无限增长。取走与计数 + // 在同一把锁内,避免并发最终停止在两者之间cancel共享订阅、使复用者失聪。 + // 路径必须精确匹配:GLib上报的child路径由建监视时的路径字符串拼出,跨路径复用会 + // 让事件带着旧路径前缀(例如监视/data/...却上报file:///home/...),上层会丢弃它们。 + // 返回nullptr表示无可用寄存监视器。 + GFileMonitor *reviveParked(InodeKey key, DWatcher::WatchType type, const QByteArray &path) + { + if (key.isNull()) + return nullptr; + QMutexLocker locker(&mutex); + auto it = parked.find(key); + if (it == parked.end()) + return nullptr; + QList &list = it.value(); + for (int i = list.size() - 1; i >= 0; --i) { + const ParkedMonitor &item = list.at(i); + if (item.type == type && item.path == path) { + GFileMonitor *monitor = list.takeAt(i).monitor; + if (list.isEmpty()) + parked.erase(it); + ++refCounts[key]; + return monitor; + } + } + return nullptr; + } + +private: + struct ParkedMonitor + { + GFileMonitor *monitor { nullptr }; + DWatcher::WatchType type = DWatcher::WatchType::kAuto; + QByteArray path; // 建这个监视器时用的本地路径:GLib用它拼事件child路径 + }; + + QMutex mutex; + QHash refCounts; + QHash> parked; +}; + +// 取GFile对应的本地路径字符串;GLib的inotify后端用的正是这个字符串来拼事件child路径, +// 因此它既是注册表复用监视器的判据,也是stat取inode的来源 +QByteArray localPathOf(GFile *gfile) +{ + if (!gfile) + return QByteArray(); + g_autofree gchar *path = g_file_get_path(gfile); + return path ? QByteArray(path) : QByteArray(); +} + +// 从监视目标GFile取(st_dev, st_ino)编码key;非本地路径或stat失败返回null key(走直接cancel) +InodeKey inodeKeyOf(GFile *gfile) +{ + const QByteArray path = localPathOf(gfile); + if (path.isEmpty()) + return InodeKey(); + struct stat st; + if (::stat(path.constData(), &st) != 0) + return InodeKey(); + return InodeKey { st.st_dev, st.st_ino }; +} + +} // namespace + /************************************************ * DWatcherPrivate ***********************************************/ @@ -43,7 +168,6 @@ GFileMonitor *DWatcherPrivate::createMonitor(GFile *gfile, DWatcher::WatchType t gmonitor = g_file_monitor_file(gfile, flags, cancel, &gerror); } - if (!gmonitor) { setErrorFromGError(gerror); @@ -104,7 +228,7 @@ void DWatcherPrivate::watchCallback(GFileMonitor *monitor, GFile *child, GFile * watcher->fileRenamed(childUrl, otherUrl); break; - //case G_FILE_MONITOR_EVENT_MOVED: + // case G_FILE_MONITOR_EVENT_MOVED: default: g_assert_not_reached(); break; @@ -186,12 +310,23 @@ bool DWatcher::start(int timeRate) url.append("/"); d->gfile = DLocalHelper::createGFile(url); + d->inodeKey = inodeKeyOf(d->gfile); + + // 复用注册表中同inode、同watch类型且同路径的寄存监视器:避免反复start/stop在兄弟 + // 监视器存活期间不断新建监视器导致寄存桶无限增长。reviveParked在锁内完成取走与计数。 + d->gmonitor = MonitorKeepAliveRegistry::instance().reviveParked(d->inodeKey, d->type, localPathOf(d->gfile)); + if (d->gmonitor) { + g_file_monitor_set_rate_limit(d->gmonitor, timeRate); + g_signal_connect(d->gmonitor, "changed", G_CALLBACK(&DWatcherPrivate::watchCallback), this); + return true; + } d->gmonitor = d->createMonitor(d->gfile, d->type); if (!d->gmonitor) { g_object_unref(d->gfile); d->gfile = nullptr; + d->inodeKey = InodeKey(); return false; } @@ -200,15 +335,31 @@ bool DWatcher::start(int timeRate) g_signal_connect(d->gmonitor, "changed", G_CALLBACK(&DWatcherPrivate::watchCallback), this); + // key在start时缓存:stop时目标可能已被删除重建(inode变化),重stat会减错计数 + MonitorKeepAliveRegistry::instance().addActive(d->inodeKey); + return true; } bool DWatcher::stop() { if (d->gmonitor) { - g_file_monitor_cancel(d->gmonitor); - g_object_unref(d->gmonitor); - d->gmonitor = nullptr; + QList doomed; + if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, d->type, + localPathOf(d->gfile), this, &doomed)) { + // 同inode仍有其它路径在监视:不cancel(会误删GLib共享订阅使存活者永久失聪), + // 回调已在锁内断开,监视器交由注册表持有 + d->gmonitor = nullptr; + } else { + g_file_monitor_cancel(d->gmonitor); + g_object_unref(d->gmonitor); + d->gmonitor = nullptr; + for (GFileMonitor *monitor : doomed) { + g_file_monitor_cancel(monitor); + g_object_unref(monitor); + } + doomed.clear(); + } } if (d->gfile) { @@ -216,6 +367,8 @@ bool DWatcher::stop() d->gfile = nullptr; } + d->inodeKey = InodeKey(); + return true; } diff --git a/src/dfm-io/dfm-io/private/dwatcher_p.h b/src/dfm-io/dfm-io/private/dwatcher_p.h index c25eb54e..93ad4efe 100644 --- a/src/dfm-io/dfm-io/private/dwatcher_p.h +++ b/src/dfm-io/dfm-io/private/dwatcher_p.h @@ -13,8 +13,27 @@ #include +#include + BEGIN_IO_NAMESPACE +// (st_dev, st_ino)完整保留的inode标识,作为监视器注册表的key;避免截断导致 +// 不同inode撞key(如btrfs的64位inode号)而延迟清理寄存的监视器。 +struct InodeKey +{ + dev_t dev { 0 }; + ino_t ino { 0 }; + + bool isNull() const { return dev == 0 && ino == 0; } + bool operator==(const InodeKey &other) const { return dev == other.dev && ino == other.ino; } +}; + +inline uint qHash(const InodeKey &key, uint seed = 0) +{ + return ::qHash(static_cast(key.dev), seed) + ^ (::qHash(static_cast(key.ino), seed) << 1); +} + class DWatcher; class DWatcherPrivate { @@ -32,6 +51,7 @@ class DWatcherPrivate DWatcher *q { nullptr }; GFileMonitor *gmonitor { nullptr }; GFile *gfile { nullptr }; + InodeKey inodeKey; // start时缓存的(st_dev, st_ino),保证stop与start对同一inode计数 int timeRate { 200 }; DWatcher::WatchType type = DWatcher::WatchType::kAuto;