Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions autotests/dfm-io-tests/tst_dfm_io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,17 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include <QTest>

Check warning on line 5 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QTest> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QTemporaryDir>

Check warning on line 6 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QTemporaryDir> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QFile>

Check warning on line 7 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QFile> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QThread>

Check warning on line 8 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QThread> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QDeadlineTimer>

Check warning on line 9 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDeadlineTimer> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QProcess>

Check warning on line 10 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QProcess> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QSignalSpy>

Check warning on line 11 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QSignalSpy> not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <dfm-io/dwatcher.h>

Check warning on line 13 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <dfm-io/dwatcher.h> not found. Please note: Cppcheck does not need standard library headers to get proper results.

USING_IO_NAMESPACE

class tst_DfmIO : public QObject
{
Expand All @@ -12,6 +22,13 @@
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();
void watcherRecoversAfterAllPathsStopped();
};

void tst_DfmIO::initTestCase()
Expand All @@ -30,5 +47,68 @@
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::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");
}

QTEST_MAIN(tst_DfmIO)
#include "tst_dfm_io.moc"

Check warning on line 114 in autotests/dfm-io-tests/tst_dfm_io.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: "tst_dfm_io.moc" not found.
101 changes: 96 additions & 5 deletions src/dfm-io/dfm-io/dwatcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,83 @@

#include "private/dwatcher_p.h"

#include <QDebug>

Check warning on line 10 in src/dfm-io/dfm-io/dwatcher.cpp

View workflow job for this annotation

GitHub Actions / cppcheck

Include file: <QDebug> not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <QHash>
#include <QList>
#include <QMutex>
#include <QMutexLocker>

#include <sys/stat.h>

USING_IO_NAMESPACE

namespace {

// 同一inode经不同路径(多挂载点/bind)监视时,GLib的inotify后端按inode共享
// 内核watch描述符:任一监视器cancel会误删共享订阅,使其它路径的存活监视器永久失聪,
// 且残留的path桶会让后续新建监视器挂到死订阅上。注册表按(st_dev, st_ino)对活跃监视器
// 计数:仍有同inode其它活跃者时,停止方只寄存GFileMonitor而不cancel;最后一个活跃者
// 停止时才统一cancel并析构全部寄存的监视器,此时GLib状态自净。
// key编码将st_dev截断为32位:不同文件系统key冲突只会让监视器延迟清理,不会误删订阅。
class MonitorKeepAliveRegistry
{
public:
static MonitorKeepAliveRegistry &instance()
{
static MonitorKeepAliveRegistry registry;
return registry;
}

void addActive(quint64 key)
{
if (key == 0)
return;
QMutexLocker locker(&mutex);
++refCounts[key];
}

// 停止时调用:同inode仍有其它活跃监视器时寄存monitor(不cancel)并返回true;
// 否则清除计数,并通过doomed交还该inode全部寄存的监视器,由调用方在锁外cancel析构
bool retainOrPark(quint64 key, GFileMonitor *monitor, QList<GFileMonitor *> *doomed)
{
doomed->clear();
if (key == 0)
return false;
QMutexLocker locker(&mutex);
const int remaining = refCounts.value(key) - 1;
if (remaining > 0) {
refCounts[key] = remaining;
parked[key].append(monitor);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Repeated restarts accumulate monitors

When one watcher is repeatedly restarted while another watcher for the same inode stays active, DWatcher::start() first calls stop(), which parks the old monitor whenever another watcher for the inode remains active. Each subsequent restart creates another monitor, so the registry retains one more GFileMonitor per restart until the other watcher stops; a long-lived sibling therefore lets repeated restarts grow retained objects without bound.

Avoid retaining a new parked monitor for every restart, for example by deduplicating or reusing retained monitors for that inode.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 56:

**Repeated restarts accumulate monitors**

When one watcher is repeatedly restarted while another watcher for the same inode stays active, `DWatcher::start()` first calls `stop()`, which parks the old monitor whenever another watcher for the inode remains active. Each subsequent restart creates another monitor, so the registry retains one more `GFileMonitor` per restart until the other watcher stops; a long-lived sibling therefore lets repeated restarts grow retained objects without bound.

Avoid retaining a new parked monitor for every restart, for example by deduplicating or reusing retained monitors for that inode.

return true;
}
refCounts.remove(key);
*doomed = parked.value(key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · New watcher stops receiving events

When a watcher starts while another thread stops the last watcher for the same inode, start() creates or registers its monitor while retainOrPark() has removed the last count and stop() is canceling outside the mutex, so canceling the old monitor disables the shared backend watch and the new watcher stops receiving events.

Serialize start registration and last-monitor cancellation so a new watcher cannot join a watch that is being canceled.

Also at src/dfm-io/dfm-io/dwatcher.cpp:276-278, src/dfm-io/dfm-io/dwatcher.cpp:286-299.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 60:

**New watcher stops receiving events**

When a watcher starts while another thread stops the last watcher for the same inode, `start()` creates or registers its monitor while `retainOrPark()` has removed the last count and `stop()` is canceling outside the mutex, so canceling the old monitor disables the shared backend watch and the new watcher stops receiving events.

Serialize start registration and last-monitor cancellation so a new watcher cannot join a watch that is being canceled.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:276-278`, `src/dfm-io/dfm-io/dwatcher.cpp:286-299`.

parked.remove(key);
return false;
}

private:
QMutex mutex;
QHash<quint64, int> refCounts;
QHash<quint64, QList<GFileMonitor *>> parked;
};

// 从监视目标GFile取(st_dev, st_ino)编码key;非本地路径或stat失败返回0(走直接cancel)
quint64 inodeKeyOf(GFile *gfile)
{
if (!gfile)
return 0;
g_autofree gchar *path = g_file_get_path(gfile);
if (!path)
return 0;
struct stat st;
if (::stat(path, &st) != 0)
return 0;
Comment on lines +80 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Missing files bypass shared registry

When a file watcher successfully monitors a nonexistent local file through one of multiple paths to the same parent directory, inodeKeyOf returns zero for a nonexistent local target, so stop() directly cancels its monitor; when GLib monitors that missing file through its parent directory, canceling one alias also removes the shared inotify watch and the other watcher misses the file’s creation.

For local paths whose target does not exist, key the monitor by the inode of the directory GLib watches, or otherwise coordinate cancellation of monitors sharing that parent watch.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at lines 80-81:

**Missing files bypass shared registry**

When a file watcher successfully monitors a nonexistent local file through one of multiple paths to the same parent directory, `inodeKeyOf` returns zero for a nonexistent local target, so `stop()` directly cancels its monitor; when GLib monitors that missing file through its parent directory, canceling one alias also removes the shared inotify watch and the other watcher misses the file’s creation.

For local paths whose target does not exist, key the monitor by the inode of the directory GLib watches, or otherwise coordinate cancellation of monitors sharing that parent watch.

return (quint64(st.st_dev) << 32) | quint32(st.st_ino);
}
Comment on lines +82 to +83

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Colliding inodes retain monitors

When distinct inodes have the same encoded low 32-bit device and inode values and one watcher remains active, inodeKeyOf() truncates st_dev and st_ino to 32 bits, so distinct inodes share a registry key; stopping one watcher parks its monitor while the unrelated watcher remains active, retaining monitors and kernel watches and potentially exhausting watcher resources.

Use a registry key that preserves the full device and inode values.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at lines 82-83:

**Colliding inodes retain monitors**

When distinct inodes have the same encoded low 32-bit device and inode values and one watcher remains active, `inodeKeyOf()` truncates `st_dev` and `st_ino` to 32 bits, so distinct inodes share a registry key; stopping one watcher parks its monitor while the unrelated watcher remains active, retaining monitors and kernel watches and potentially exhausting watcher resources.

Use a registry key that preserves the full device and inode values.


} // namespace

/************************************************
* DWatcherPrivate
***********************************************/
Expand Down Expand Up @@ -43,7 +116,6 @@
gmonitor = g_file_monitor_file(gfile, flags, cancel, &gerror);
}


if (!gmonitor) {
setErrorFromGError(gerror);

Expand Down Expand Up @@ -104,7 +176,7 @@
watcher->fileRenamed(childUrl, otherUrl);
break;

//case G_FILE_MONITOR_EVENT_MOVED:
// case G_FILE_MONITOR_EVENT_MOVED:
default:
g_assert_not_reached();
break;
Expand Down Expand Up @@ -200,22 +272,41 @@

g_signal_connect(d->gmonitor, "changed", G_CALLBACK(&DWatcherPrivate::watchCallback), this);

// key在start时缓存:stop时目标可能已被删除重建(inode变化),重stat会减错计数
d->inodeKey = inodeKeyOf(d->gfile);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Replacement path cancels active watch

When the watched path is replaced between monitor creation and the subsequent stat(), inodeKeyOf() records the replacement inode's key for a monitor still attached to the original inode, so stopping that watcher can cancel the shared watch used by another watcher of the original inode, which then stops receiving events.

Derive the registry key from the inode actually attached to the monitor rather than statting the path after monitor creation.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 276:

**Replacement path cancels active watch**

When the watched path is replaced between monitor creation and the subsequent `stat()`, `inodeKeyOf()` records the replacement inode's key for a monitor still attached to the original inode, so stopping that watcher can cancel the shared watch used by another watcher of the original inode, which then stops receiving events.

Derive the registry key from the inode actually attached to the monitor rather than statting the path after monitor creation.

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<GFileMonitor *> doomed;
if (MonitorKeepAliveRegistry::instance().retainOrPark(d->inodeKey, d->gmonitor, &doomed)) {
// 同inode仍有其它路径在监视:不cancel(会误删GLib共享订阅使存活者永久失聪),
// 仅断开changed回调静默本对象,监视器交由注册表持有
g_signal_handlers_disconnect_by_data(d->gmonitor, this);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Concurrent stops crash

When two watchers for the same inode are stopped concurrently, retainOrPark() returns a parked monitor without protecting it from a concurrent final stop(), which can cancel and unref it before g_signal_handlers_disconnect_by_data() uses it, crashing the process.

Keep a strong reference to the monitor until its signal handler is disconnected, or serialize disconnection with final removal.

Also at src/dfm-io/dfm-io/dwatcher.cpp:297.

Prompt for AI agents
In `src/dfm-io/dfm-io/dwatcher.cpp` at line 289:

**Concurrent stops crash**

When two watchers for the same inode are stopped concurrently, `retainOrPark()` returns a parked monitor without protecting it from a concurrent final `stop()`, which can cancel and unref it before `g_signal_handlers_disconnect_by_data()` uses it, crashing the process.

Keep a strong reference to the monitor until its signal handler is disconnected, or serialize disconnection with final removal.

Also at `src/dfm-io/dfm-io/dwatcher.cpp:297`.

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) {
g_object_unref(d->gfile);
d->gfile = nullptr;
}

d->inodeKey = 0;

return true;
}

Expand Down
1 change: 1 addition & 0 deletions src/dfm-io/dfm-io/private/dwatcher_p.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class DWatcherPrivate
DWatcher *q { nullptr };
GFileMonitor *gmonitor { nullptr };
GFile *gfile { nullptr };
quint64 inodeKey { 0 }; // start时缓存的(st_dev, st_ino),保证stop与start对同一inode计数

int timeRate { 200 };
DWatcher::WatchType type = DWatcher::WatchType::kAuto;
Expand Down
Loading