10#include <private/qcore_unix_p.h>
11#include <private/qlocale_tools_p.h>
12#include <private/qtools_p.h>
14#include <QtCore/qdirlisting.h>
15#include <QtCore/qsystemdetection.h>
21#include <sys/statfs.h>
22#include <sys/syscall.h>
24#include <linux/types.h>
25#include <linux/mount.h>
29# define FSLABEL_MAX 256
31#ifndef FS_IOC_GETFSLABEL
36# define STATX_MNT_ID_UNIQUE 0x4000U
41# define ST_RDONLY 0x0001
44#if defined(Q_OS_ANDROID)
48# undef STATX_BASIC_STATS
53#include <private/qjnihelpers_p.h>
93using namespace Qt::StringLiterals;
100 auto it = devno.cbegin();
101 auto r = qstrntoll(it, devno.size(), 10);
104 int rdevmajor =
int(r.result);
110 r = qstrntoll(++it, devno.size() - r.used + 1, 10);
114 return makedev(rdevmajor, r.result);
127 QByteArray ret(path.size(),
'\0');
128 char *dst = ret.data();
129 const char *src = path.data();
130 const char *srcEnd = path.data() + path.size();
131 while (src != srcEnd) {
139 char c = (*src++ -
'0') << 6;
140 c |= (*src++ -
'0') << 3;
153 ret.resize(dst - ret.data());
173static void tokenizeLine(std::array<QByteArrayView, FieldCount> &fields, QByteArrayView line)
175 size_t fieldIndex = 0;
177 const char *begin = line.data();
178 const qsizetype len = line.size();
179 qsizetype spaceIndex = -1;
180 while ((spaceIndex = line.indexOf(
' ', from)) != -1 && fieldIndex <
FieldCount) {
181 fields[fieldIndex] = QByteArrayView{begin + from, begin + spaceIndex};
186 static constexpr char separatorField[] =
" - ";
187 const qsizetype sepIndex = line.indexOf(separatorField, from);
188 if (sepIndex == -1) {
189 qCWarning(lcStorageInfo,
190 "Malformed line (missing '-' separator field) while parsing '%s':\n%s",
196 from = sepIndex + strlen(separatorField);
210 qCInfo(lcStorageInfo,
211 "Expected %d fields while parsing line from '%s', but found %zu instead:\n%.*s",
223 auto it = mountinfo.cbegin();
224 const auto end = mountinfo.cend();
225 auto nextLine = [&it, &end]() -> QByteArrayView {
226 auto nIt = std::find(it, end,
'\n');
228 QByteArrayView ba(it, nIt);
235 std::vector<MountInfo> infos;
236 std::array<QByteArrayView, FieldCount> fields;
239 auto checkField = [&line](QByteArrayView field) {
240 if (field.isEmpty()) {
241 qDebug(
"Failed to parse line from %s:\n%.*s",
MountInfoPath,
int(line.size()),
249 while (!(line = nextLine()).isEmpty()) {
251 tokenizeLine(fields, line);
254 if (
auto r = qstrntoll(fields[
MountId].data(), fields[
MountId].size(), 10); r.ok()) {
255 info.mntid = r.result;
261 QByteArray mountP = parseMangledPath(fields[MountPoint]);
262 if (!checkField(mountP))
264 info.mountPoint = QFile::decodeName(mountP);
266 if (!checkField(fields[
FsType]))
268 info.fsType = fields[
FsType].toByteArray();
270 if (filter == FilterMountInfo::Filtered
271 && !QStorageInfoPrivate::shouldIncludeFs(info.mountPoint, info.fsType))
274 std::optional<dev_t> devno = deviceNumber(fields[DevNo]);
281 QByteArrayView fsRootView = fields[
FsRoot];
282 if (!checkField(fsRootView))
287 if (fsRootView !=
"/") {
288 info.fsRoot = parseMangledPath(fsRootView);
289 if (!checkField(info.fsRoot))
293 info.device = parseMangledPath(fields[MountSource]);
294 if (!checkField(info.device))
297 infos.push_back(std::move(info));
303struct AutoFileDescriptor
306 explicit AutoFileDescriptor() =
default;
307 AutoFileDescriptor(
const QString &path,
int mode = QT_OPEN_RDONLY)
308 : fd(qt_safe_open(QFile::encodeName(path), mode))
310 ~AutoFileDescriptor() {
if (fd >= 0) qt_safe_close(fd); }
311 operator
int()
const noexcept {
return fd; }
314struct QStorageLabelRetriever
320 QList<Entry> labelMap;
321 bool populated =
false;
322 QString operator()(
const QStorageInfoPrivate &d,
int fd, quint64 devid);
325 static QList<Entry> allLabels();
335 using namespace QtMiscUtils;
336 const qsizetype start = decoded.indexOf(u'\\');
341 auto ptr =
reinterpret_cast<
char16_t *>(decoded.begin());
342 qsizetype in = start;
343 qsizetype out = start;
344 qsizetype size = decoded.size();
347 Q_ASSERT(ptr[in] == u'\\');
348 if (size - in >= 4 && ptr[in + 1] == u'x') {
349 int c = fromHex(ptr[in + 2]) << 4;
350 c |= fromHex(ptr[in + 3]);
351 if (Q_UNLIKELY(c < 0))
352 c = QChar::ReplacementCharacter;
357 for ( ; in < size; ++in) {
358 char16_t c = ptr[in];
371 if (QT_STAT(QFile::encodeName(device), &st) < 0)
380#if defined(STATX_BASIC_STATS
) && defined(STATX_MNT_ID
)
383 if (mountIdType == 0)
384 mountIdType = STATX_MNT_ID;
385 int r = statx(fd,
"", AT_EMPTY_PATH | AT_NO_AUTOMOUNT, mountIdType, &st);
386 if (r == 0 && (st.stx_mask & mountIdType))
387 return st.stx_mnt_id;
389 Q_UNUSED(mountIdType);
403 if (major(deviceId) != 0)
407 if (device.size() < 2 || !device.startsWith(
'/'))
411 if (QT_STAT(device, &st) < 0)
413 if (!S_ISBLK(st.st_mode))
420 static const char pathDiskByLabel[] =
"/dev/disk/by-label";
421 static constexpr auto LabelFileFilter = QDirListing::IteratorFlag::IncludeHidden;
422 return QDirListing(QLatin1StringView(pathDiskByLabel), LabelFileFilter);
425auto QStorageLabelRetriever::allLabels() -> QList<Entry>
429 for (
const auto &dirEntry : devicesByLabel()) {
430 quint64 deviceId = retrieveDeviceId(QFile::encodeName(dirEntry.filePath()));
433 result.emplaceBack(Entry{ decodeFsEncString(dirEntry.fileName()), deviceId });
450 return QString::fromUtf8(label);
455 if (
auto label = retrieveLabelViaIoctl(fd))
458 deviceId = retrieveDeviceId(d.device, deviceId);
462 for (
const auto &dirEntry : devicesByLabel()) {
463 if (retrieveDeviceId(QFile::encodeName(dirEntry.filePath())) == deviceId)
464 return decodeFsEncString(dirEntry.fileName());
469QString QStorageLabelRetriever::operator()(
const QStorageInfoPrivate &d,
int fd, quint64 devid)
471 if (d.fileSystemType ==
"tmpfs")
474 if (
auto label = retrieveLabelViaIoctl(fd))
477 devid = retrieveDeviceId(d.device, devid);
482 labelMap = allLabels();
485 for (
auto &[deviceLabel, deviceId] : std::as_const(labelMap)) {
486 if (devid == deviceId)
492void QStorageInfoPrivate::retrieveVolumeInfo()
494 struct statfs64 statfs_buf;
496 QT_EINTR_LOOP(result, statfs64(QFile::encodeName(rootPath).constData(), &statfs_buf));
497 valid = ready = (result == 0);
499 bytesTotal = statfs_buf.f_blocks * statfs_buf.f_frsize;
500 bytesFree = statfs_buf.f_bfree * statfs_buf.f_frsize;
501 bytesAvailable = statfs_buf.f_bavail * statfs_buf.f_frsize;
502 blockSize =
int(statfs_buf.f_bsize);
503 readOnly = (statfs_buf.f_flags &
ST_RDONLY) != 0;
508doStatMount(QStorageInfoPrivate *d,
const AutoFileDescriptor &fd, quint64 mountid,
509 QStorageLabelRetriever &labelRetriever)
511 enum TriStateResult : qint8 {
519 constexpr int NumStringsInRequest = 4;
521 static constexpr quint64 StatMountRequestParams = 0x23b;
523 static constexpr quint64 StatMountMinParams = StatMountRequestParams;
524# ifdef STATMOUNT_SB_SOURCE
526 constexpr quint64 SymbolicStatMountParams = STATMOUNT_SB_BASIC | STATMOUNT_MNT_BASIC
527 | STATMOUNT_MNT_POINT | STATMOUNT_MNT_ROOT | STATMOUNT_FS_TYPE
528 | STATMOUNT_SB_SOURCE;
529 static_assert(SymbolicStatMountParams == StatMountRequestParams);
532 QVarLengthArray<
char, 1024> smbuf(1024);
533 auto sm =
new (smbuf.data())
struct statmount;
534 struct mnt_id_req req = {};
535 req.size =
sizeof(req);
536 req.mnt_id = mountid;
537 req.param = StatMountRequestParams;
539 int r = syscall(__NR_statmount, &req, sm, smbuf.size(), 0);
540 if (r < 0 && errno == EOVERFLOW) {
542 smbuf.resize(
sizeof(
struct statmount) + NumStringsInRequest * PATH_MAX);
543 sm =
new (smbuf.data())
struct statmount;
544 r = syscall(__NR_statmount, &req, sm, smbuf.size(), 0);
546 if (r == 0 && (sm->mask & StatMountMinParams) == StatMountMinParams) {
547 d->rootPath = QFile::decodeName(sm->str + sm->mnt_point);
548 d->fileSystemType.assign(sm->str + sm->fs_type);
549 if (!QStorageInfoPrivate::shouldIncludeFs(d->rootPath, d->fileSystemType))
552 d->device = QByteArray(sm->str + sm->sb_source);
553 if (QByteArrayView subv(sm->str + sm->mnt_root); subv !=
"/")
554 d->subvolume.assign(subv);
556 d->subvolume.clear();
558 quint64 devid = makedev(sm->sb_dev_major, sm->sb_dev_minor);
560 d->name = labelRetriever(*d, fd, devid);
562 d->name = labelRetriever(*d, AutoFileDescriptor(d->rootPath), devid);
569 Q_UNUSED(labelRetriever);
574static bool doStatMount(QStorageInfoPrivate *d,
const AutoFileDescriptor &fd)
580 QStorageLabelRetriever retriever;
581 return doStatMount(d, fd, mountId, retriever) > 0;
584QList<QStorageInfo> QStorageInfoPrivate::listMounts()
586 QList<QStorageInfo> volumes;
588#if defined(__NR_listmount
) && defined(LSMT_ROOT
)
589 QStorageLabelRetriever labelRetriever;
593 struct mnt_id_req req = {};
594 req.size =
sizeof(req);
595 req.mnt_id = LSMT_ROOT;
596 int r = syscall(__NR_listmount, &req, mounts, std::size(mounts), 0);
600 std::unique_ptr<QStorageInfoPrivate> d;
602 for (quint64 mntid : QSpan(mounts, r)) {
604 d = std::make_unique<QStorageInfoPrivate>();
605 auto shouldAdd = doStatMount(d.get(), AutoFileDescriptor(), mntid, labelRetriever);
612 d->retrieveVolumeInfo();
615 volumes.emplace_back(QStorageInfo(*d.release()));
617 if (r < q20::ssize(mounts))
621 req.param = mounts[r - 1];
622 r = syscall(__NR_listmount, &req, mounts, std::size(mounts), 0);
633 QFile file(u"/proc/self/mountinfo"_s);
634 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
637 QByteArray mountinfo = file.readAll();
640 return doParseMountInfo(mountinfo, filter);
643void QStorageInfoPrivate::doStat()
646 if (QtAndroidPrivate::isUncompressedNativeLibs()) {
648 QString possibleApk = QtAndroidPrivate::resolveApkPath(rootPath);
649 if (!possibleApk.isEmpty())
650 rootPath = possibleApk;
654 retrieveVolumeInfo();
658 AutoFileDescriptor fd(rootPath);
659 if (doStatMount(
this, fd))
662 QFileInfo fileInfo(rootPath);
663 if (QString canonicalPath = fileInfo.canonicalFilePath(); !canonicalPath.isEmpty()) {
664 rootPath = std::move(canonicalPath);
669 rootPath = fileInfo.absoluteFilePath();
672 std::vector<MountInfo> infos = parseMountInfo();
678 MountInfo *best =
nullptr;
679 if (quint64 mntid = mountIdForPath(fd)) {
681 auto it = std::find_if(infos.begin(), infos.end(),
682 [mntid](
const MountInfo &info) {
return info.mntid == mntid; });
683 if (it != infos.end())
684 best = q20::to_address(it);
701 const QString oldRootPath = std::exchange(rootPath, QString());
702 const dev_t rootPathDevId = deviceIdForPath(oldRootPath);
703 for (
auto it = infos.rbegin(); it != infos.rend(); ++it) {
704 if (!isParentOf(it->mountPoint, oldRootPath))
706 if (rootPathDevId == it->stDev) {
708 best = q20::to_address(it);
714 best = q20::to_address(it);
719 auto stDev = best->stDev;
720 setFromMountInfo(std::move(*best));
721 name = retrieveLabel(*
this, fd, stDev);
725QList<QStorageInfo> QStorageInfoPrivate::mountedVolumes()
727 QList<QStorageInfo> volumes = listMounts();
728 if (!volumes.isEmpty())
731 std::vector<MountInfo> infos = parseMountInfo(FilterMountInfo::Filtered);
733 volumes.append(root());
737 QStorageLabelRetriever labelForDevice;
738 volumes.reserve(infos.size());
739 for (
auto it = infos.begin(); it != infos.end(); ++it) {
740 MountInfo &info = *it;
741 AutoFileDescriptor fd(info.mountPoint);
744 quint64 mntid = mountIdForPath(fd);
748 auto isParent = [&info](
const MountInfo &maybeParent) {
749 return isParentOf(maybeParent.mountPoint, info.mountPoint);
751 if (std::find_if(it + 1, infos.end(), isParent) != infos.end())
753 }
else if (mntid != info.mntid) {
757 const auto infoStDev = info.stDev;
758 QStorageInfoPrivate d(std::move(info));
759 d.retrieveVolumeInfo();
760 if (d.bytesTotal <= 0 && d.rootPath != u'/')
762 d.name = labelForDevice(d, fd, infoStDev);
763 volumes.emplace_back(QStorageInfo(*
new QStorageInfoPrivate(std::move(d))));
static QString retrieveLabel(const QStorageInfoPrivate &d, int fd, quint64 deviceId)
static constexpr short MountId
static quint64 retrieveDeviceId(const QByteArray &device, quint64 deviceId=0)
static auto doStatMount(QStorageInfoPrivate *d, const AutoFileDescriptor &fd, quint64 mountid, QStorageLabelRetriever &labelRetriever)
static const char MountInfoPath[]
static constexpr short MountPoint
static constexpr short MountSource
static constexpr short FieldCount
static constexpr short MountOptions
std::vector< MountInfo > doParseMountInfo(const QByteArray &mountinfo, FilterMountInfo filter)
static constexpr short FsType
static std::optional< dev_t > deviceNumber(QByteArrayView devno)
static std::optional< QString > retrieveLabelViaIoctl(int fd)
#define FS_IOC_GETFSLABEL
static constexpr short DevNo
Q_DECLARE_TYPEINFO(QStorageLabelRetriever::Entry, Q_RELOCATABLE_TYPE)
static bool doStatMount(QStorageInfoPrivate *d, const AutoFileDescriptor &fd)
static quint64 mountIdForPath(int fd, unsigned mountIdType=0)
static QByteArray parseMangledPath(QByteArrayView path)
static constexpr short SuperOptions
static QDirListing devicesByLabel()
static constexpr short FsRoot
static std::vector< MountInfo > parseMountInfo(FilterMountInfo filter=FilterMountInfo::All)
static QString decodeFsEncString(QString decoded)
static void tokenizeLine(std::array< QByteArrayView, FieldCount > &fields, QByteArrayView line)
static dev_t deviceIdForPath(const QString &device)
#define STATX_MNT_ID_UNIQUE