File indexing completed on 2024-11-10 04:56:24

0001 /*
0002     KWin - the KDE window manager
0003     This file is part of the KDE project.
0004 
0005     SPDX-FileCopyrightText: 2022 MBition GmbH
0006     SPDX-FileContributor: Kai Uwe Broulik <kai_uwe.broulik@mbition.io>
0007 
0008     SPDX-License-Identifier: GPL-2.0-or-later
0009 */
0010 
0011 #include <config-kwin.h>
0012 
0013 #include <sys/mman.h>
0014 #include <unistd.h>
0015 
0016 #include "utils/ramfile.h"
0017 
0018 #include <QTest>
0019 
0020 using namespace KWin;
0021 
0022 class TestUtils : public QObject
0023 {
0024     Q_OBJECT
0025 private Q_SLOTS:
0026     void testRamFile();
0027     void testSealedRamFile();
0028 };
0029 
0030 static const QByteArray s_testByteArray = QByteArrayLiteral("Test Data \0\1\2\3");
0031 static const char s_writeTestArray[] = "test";
0032 
0033 void TestUtils::testRamFile()
0034 {
0035     KWin::RamFile file("test", s_testByteArray.constData(), s_testByteArray.size());
0036     QVERIFY(file.isValid());
0037     QCOMPARE(file.size(), s_testByteArray.size());
0038 
0039     QVERIFY(file.fd() != -1);
0040 
0041     char buf[20];
0042     int num = read(file.fd(), buf, sizeof buf);
0043     QCOMPARE(num, file.size());
0044 
0045     QCOMPARE(qstrcmp(s_testByteArray.constData(), buf), 0);
0046 }
0047 
0048 void TestUtils::testSealedRamFile()
0049 {
0050 #if HAVE_MEMFD
0051     KWin::RamFile file("test", s_testByteArray.constData(), s_testByteArray.size(), KWin::RamFile::Flag::SealWrite);
0052     QVERIFY(file.isValid());
0053     QVERIFY(file.effectiveFlags().testFlag(KWin::RamFile::Flag::SealWrite));
0054 
0055     // Writing should not work.
0056     auto written = write(file.fd(), s_writeTestArray, strlen(s_writeTestArray));
0057     QCOMPARE(written, -1);
0058 
0059     // Cannot use MAP_SHARED on sealed file descriptor.
0060     void *data = mmap(nullptr, file.size(), PROT_WRITE, MAP_SHARED, file.fd(), 0);
0061     QCOMPARE(data, MAP_FAILED);
0062 
0063     data = mmap(nullptr, file.size(), PROT_WRITE, MAP_PRIVATE, file.fd(), 0);
0064     QVERIFY(data != MAP_FAILED);
0065 #else
0066     QSKIP("Sealing requires memfd suport.");
0067 #endif
0068 }
0069 
0070 QTEST_MAIN(TestUtils)
0071 #include "test_utils.moc"