Merge pull request #2761 from fastfetch-cli/dev

This commit is contained in:
Carter Li authored and GitHub committed 2026-11-28 13:22:51 +08:00
commit 27b8f8bb21
77 files changed
+2839 -541

No files matched your search

@@ -1,66 +0,0 @@
name: Reusable DragonFly amd64
on:
workflow_call:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
shell: cpa.sh {0}
steps:
- name: checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@82668f1fbd89d9c99487604f822cbf6716f124d3 # v1.7.0
with:
operating_system: dragonflybsd
version: '6.4.2'
shell: bash
cpu_count: 4
- name: Show system info
run: |
uname -a
pkg --version
- name: Update and install dependencies
run: |
sudo pkg update
sudo pkg install -y llvm cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3-tcl egl opencl ocl-icd v4l_compat chafa libelf lua54 libva libvdpau
- name: CMake configuration
run: env CC=clang cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On -DCMAKE_BUILD_TYPE=${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }} -DCMAKE_C_FLAGS="-fno-pie" -DCMAKE_EXE_LINKER_FLAGS="-no-pie" .
- name: CMake build
run: cmake --build . --target package --verbose -j4
- name: List features
run: ./fastfetch --list-features
- name: Run normal
run: time ./fastfetch -c presets/ci.jsonc --stat false
- name: Run json
run: time ./fastfetch -c presets/ci.jsonc --format json
- name: Run flashfetch
run: time ./flashfetch
- name: Run ldd
run: ldd fastfetch
- name: Run tests
run: ctest --output-on-failure
- name: upload artifacts
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: fastfetch-dragonfly-amd64
path: ./fastfetch-*.*
+2 -2
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@82668f1fbd89d9c99487604f822cbf6716f124d3 # v1.7.0
uses: cross-platform-actions/action@30cde56b87a128507bebea9531205087890ee360 # v1.8.0
with:
operating_system: freebsd
version: '15.1'
@@ -34,7 +34,7 @@ jobs:
- name: Update and install dependencies
run: |
sudo pkg update
sudo pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3 egl opencl ocl-icd v4l_compat chafa lua54 libva libvdpau
sudo pkg install -y cmake-core git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3 egl opencl ocl-icd v4l_compat chafa lua54 libva libvdpau
- name: CMake configuration
run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On -DCMAKE_BUILD_TYPE=${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }} -DCMAKE_C_FLAGS="-fno-pie" -DCMAKE_EXE_LINKER_FLAGS="-no-pie" .
+2 -2
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@82668f1fbd89d9c99487604f822cbf6716f124d3 # v1.7.0
uses: cross-platform-actions/action@30cde56b87a128507bebea9531205087890ee360 # v1.8.0
with:
operating_system: haiku
version: 'r1beta6'
@@ -29,7 +29,7 @@ jobs:
run: uname -a
- name: Install dependencies
run: pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_headers vulkan_loader_devel zlib_devel chafa_devel cmake llvm22_clang ninja pkgconfig python3.10 lua || pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_headers vulkan_loader_devel zlib_devel chafa_devel cmake llvm22_clang ninja pkgconfig python3.10 lua
run: pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_headers vulkan_loader_devel zlib_devel cmake llvm23_clang ninja pkgconfig python3.15 lua || pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_headers vulkan_loader_devel zlib_devel cmake llvm23_clang ninja pkgconfig python3.15 lua
- name: CMake configuration
run: CC=clang CXX=clang++ cmake -GNinja -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On -DCMAKE_BUILD_TYPE=${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }} .
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: run VM
uses: uraimo/run-on-arch-action@fa1f3e7de95534497266c7265950b5188355fbfb # v3.2.1
uses: uraimo/run-on-arch-action@9893a0f995e5148dcc313ba661820f3992cffcc1 # v3.3
id: runcmd
with:
arch: armv7
+2 -2
View File
@@ -52,7 +52,7 @@ jobs:
- name: Initialize CodeQL
if: inputs.arch == 'amd64'
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
languages: c
@@ -64,7 +64,7 @@ jobs:
- name: perform CodeQL analysis
if: inputs.arch == 'amd64'
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
- name: list features
run: ./fastfetch --list-features
-60
View File
@@ -1,60 +0,0 @@
name: Reusable Linux loong64
on:
workflow_call:
permissions:
contents: read
env:
CMAKE_BUILD_TYPE: ${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }}
jobs:
build:
runs-on: ubuntu-24.04
steps:
- name: checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: set up QEMU for loong64
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- name: build in loong64 container
run: |
docker run --rm --platform linux/loong64 \
-v ${{ github.workspace }}:/workspace \
-w /workspace \
lcr.loongnix.cn/debian:14 \
bash -c '
set -e
uname -a
cat /etc/os-release || true
apt-get update
apt-get install -y --no-install-recommends \
cmake make gcc g++ \
libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev \
libdconf-dev libdbus-1-dev libmagickcore-dev \
libsqlite3-dev librpm-dev \
libegl-dev libglx-dev ocl-icd-opencl-dev \
libdrm-dev \
libelf-dev libefl-all-dev \
liblua5.4-dev \
libvdpau-dev libva-dev \
rpm
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_C_FLAGS="-fno-pie" -DCMAKE_EXE_LINKER_FLAGS="-no-pie" .
cmake --build . --target package --verbose -j$(nproc)
./fastfetch --list-features
time ./fastfetch -c presets/ci.jsonc --stat false
time ./fastfetch -c presets/ci.jsonc --format json
time ./flashfetch
ldd fastfetch
ctest --output-on-failure
'
- name: upload artifacts
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: fastfetch-linux-loong64
path: ./fastfetch-*.*
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: run VM
uses: uraimo/run-on-arch-action@fa1f3e7de95534497266c7265950b5188355fbfb # v3.2.1
uses: uraimo/run-on-arch-action@9893a0f995e5148dcc313ba661820f3992cffcc1 # v3.3
id: runcmd
with:
arch: ${{ inputs.arch }}
+2 -2
View File
@@ -18,10 +18,10 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@82668f1fbd89d9c99487604f822cbf6716f124d3 # v1.7.0
uses: cross-platform-actions/action@30cde56b87a128507bebea9531205087890ee360 # v1.8.0
with:
operating_system: netbsd
version: '11.0'
version: '11.1'
shell: bash
cpu_count: 4
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@82668f1fbd89d9c99487604f822cbf6716f124d3 # v1.7.0
uses: cross-platform-actions/action@30cde56b87a128507bebea9531205087890ee360 # v1.8.0
with:
operating_system: omnios
version: 'r151058'
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@82668f1fbd89d9c99487604f822cbf6716f124d3 # v1.7.0
uses: cross-platform-actions/action@30cde56b87a128507bebea9531205087890ee360 # v1.8.0
with:
operating_system: openbsd
version: '8.0'
+29 -27
View File
@@ -23,6 +23,31 @@ jobs:
- name: download artifacts
if: inputs.ffversion != steps.get_version_release.outputs.release
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
# Only release assets; benchmark artifacts are uploaded by a separate job.
pattern: fastfetch-*
- name: generate checksums and release notes
if: inputs.ffversion != steps.get_version_release.outputs.release
run: |
# One checksum line per release asset, using the asset's file name.
# Sort for a stable, reproducible file.
for dir in fastfetch-*/; do
(cd "$dir" && sha256sum -- *)
done | sort -k2 > SHA256SUMS.txt
for dir in fastfetch-*/; do
(cd "$dir" && sha512sum -- *)
done | sort -k2 > SHA512SUMS.txt
cat SHA256SUMS.txt
cat SHA512SUMS.txt
cat > fastfetch-release-notes.md <<EOF
Please refer to [CHANGELOG.md](https://github.com/${{ github.repository }}/blob/${{ inputs.ffversion }}/CHANGELOG.md) for details.
SHA256 and SHA512 checksums for all release assets are available in \`SHA256SUMS.txt\` and \`SHA512SUMS.txt\`.
EOF
- name: create release
if: inputs.ffversion != steps.get_version_release.outputs.release
@@ -31,31 +56,8 @@ jobs:
tag: ${{ inputs.ffversion }}
commit: ${{ github.sha }}
artifactErrorsFailBuild: true
artifacts: fastfetch-*/fastfetch-*
body: "Please refer to [CHANGELOG.md](https://github.com/${{ github.repository }}/blob/${{ inputs.ffversion }}/CHANGELOG.md) for details."
- name: download source tarballs
if: inputs.ffversion != steps.get_version_release.outputs.release
run: |
for i in 1 2 3 4 5; do curl -L --remote-name-all --output-dir fastfetch-source --create-dirs https://github.com/${{ github.repository }}/archive/refs/tags/${{ inputs.ffversion }}.{tar.gz,zip} && break || sleep 5; done
ls fastfetch-*/*
- name: generate release notes
if: inputs.ffversion != steps.get_version_release.outputs.release
run: |
echo "Please refer to [CHANGELOG.md](https://github.com/${{ github.repository }}/blob/${{ inputs.ffversion }}/CHANGELOG.md) for details." > fastfetch-release-notes.md
echo -e "\n---\n\n<details><summary>SHA256SUMs</summary><br>\n\n\`\`\`" >> fastfetch-release-notes.md
sha256sum fastfetch-*/* >> fastfetch-release-notes.md
echo -e "\`\`\`\n</details>" >> fastfetch-release-notes.md
echo -e "\n<details><summary>SHA512SUMs</summary><br>\n\n\`\`\`" >> fastfetch-release-notes.md
sha512sum fastfetch-*/* >> fastfetch-release-notes.md
echo -e "\`\`\`\n</details>" >> fastfetch-release-notes.md
- name: update release body
if: inputs.ffversion != steps.get_version_release.outputs.release
uses: ncipollo/release-action@339a81892b84b4eeb0f6e744e4574d79d0d9b8dd # v1.21.0
with:
tag: ${{ inputs.ffversion }}
commit: ${{ github.sha }}
artifacts: fastfetch-*/*,SHA256SUMS.txt,SHA512SUMS.txt
bodyFile: fastfetch-release-notes.md
allowUpdates: true
# Create a draft, upload all assets, then publish. Required for
# immutable releases, which automatically get a release attestation.
immutableCreate: true
-16
View File
@@ -43,13 +43,6 @@ jobs:
contents: read
uses: ./.github/workflows/build-linux-armv7l.yml
linux-loong64:
needs: no-features-test
name: Linux-loong64
permissions:
contents: read
uses: ./.github/workflows/build-linux-loong64.yml
linux-vms:
needs: no-features-test
name: Linux-${{ matrix.arch }}
@@ -129,13 +122,6 @@ jobs:
contents: read
uses: ./.github/workflows/build-netbsd-amd64.yml
dragonfly-amd64:
needs: no-features-test
name: DragonFly-amd64
permissions:
contents: read
uses: ./.github/workflows/build-dragonfly-amd64.yml
haiku-amd64:
needs: no-features-test
name: Haiku-amd64
@@ -192,7 +178,6 @@ jobs:
- linux-hosts
- linux-i686
- linux-armv7l
- linux-loong64
- linux-vms
- musl-amd64
- android
@@ -200,7 +185,6 @@ jobs:
- freebsd-amd64
- openbsd-amd64
- netbsd-amd64
- dragonfly-amd64
- solaris-amd64
- omnios-amd64
- haiku-amd64
+39
View File
@@ -1,3 +1,42 @@
# 2.72.0
Changes:
* DragonFly BSD support is deprecated and will be removed in a future release.
* DF BSD keeps introducing broken packages and breaks fastfetch CI, making it difficult to maintain reliable support. Considering its low usage and the maintenance burden, I have decided to deprecate it.
Features:
* Added glob and environment variable expansion to logo sources on Windows. `%VAR%`, `$VAR` and `${VAR}` are supported, and a glob matching several files picks one randomly. (#2718, Logo, Windows)
* Added opt-in drive health detection for NVMe disks, via udisks2 on Linux (no root required), NVMe SMART on macOS and the NVMe health log on Windows. (#2726, PhysicalDisk, Linux / macOS / Windows)
* Enable it with `"health": true`. The default output appends `Health <100 - percentage used>%` and any critical warnings.
* New format args: `{health}`, `{percent-used}`, `{available-spare}` and `{critical-warning}`.
* ATA disks report the SMART `failing` status as a critical warning (SAS and RAID disks stay unknown). On Windows and macOS, checking them may wake a sleeping HDD.
* Added unprivileged detection of DMI physical memory slots on Linux using udev's DMI database (`/run/udev/data/+dmi:id`, systemd 248+). (PhysicalMemory, Linux)
* Falls back to reading SMBIOS directly when the udev DMI database is unavailable (requires root).
* Added version detection and a `PowerShell Preview` display name for `pwsh-preview`. (Shell, Windows)
* Added CPU temperature detection via PawnIO on Windows. (CPU, Windows)
* Previously CPU temperature was read from the `\_TZ.CPUZ` thermal zone via perflib, which can be unavailable or inaccurate on some systems. The new method reads Intel MSRs directly through the PawnIO driver.
* Requires an x86_64 Intel CPU, the PawnIO driver installed, and administrator privileges; otherwise fastfetch falls back to the thermal zone method. Maximum frequency detection is also improved when PawnIO is available.
* Disclaimer: installing an 3rd-party kernel driver is generally not recommended and may pose security risks. Use it at your own risk.
Changes:
* Improved PCI GPU name resolution by checking udev's hardware database and the NVIDIA driver's procfs before falling back to pci.ids. (GPU, Linux)
* Redhat Virtio GPUs are now reported as integrated instead of discrete. (GPU, Linux)
Bugfixes:
* Fixed libc version detection on FreeBSD without binutils installed, and on DragonFly BSD. (Libc, FreeBSD / DragonFly)
* Fixed CPU cache detection failing entirely when any CPU is offline. (#2736, CPUCache, Linux)
* Fixed the scale factor of rotated monitors on Wayland, e.g. a 1920x1200 monitor rotated by 90 degrees at scale 1 being reported as `@ 1.59x`. (Display, Linux)
* Fixed Linux DRM display detection reading connector information from the wrong sysfs path after the EDID path was appended, and appending the EDID display name to the connector name instead of replacing it. (Display, Linux)
* Fixed the sysfs modes buffer not being NUL-terminated before parsing on Linux. (Display, Linux)
* Fixed out-of-bounds reads when parsing malformed CTA-861 EDID extensions. (General)
* Fixed the init system executable path being truncated on platforms where POSIX `basename()` modifies its argument. (InitSystem, Linux)
* Fixed undefined behavior from passing negative `char` values to ctype functions. (General)
* Fixed OS detection failed when `TARGET_DIR_ETC` is set on FreeBSD. (OS, FreeBSD)
Logos:
* Updated the CuerdOS logo and colors (#2712)
* Removed the Turkmen Linux (`Turkish`) logo
# 2.71.0
Features:
+40 -11
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21.0) # C_STANDARD C17 and C23
project(fastfetch
VERSION 2.71.0
VERSION 2.72.0
LANGUAGES C
DESCRIPTION "Fast neofetch-like system information tool"
HOMEPAGE_URL "https://github.com/fastfetch-cli/fastfetch"
@@ -620,6 +620,7 @@ if(LINUX)
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_linux.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/diskio/diskio_linux.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
@@ -798,7 +799,7 @@ elseif(FreeBSD)
src/detection/disk/disk_bsd.c
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_bsd.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/diskio/diskio_bsd.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
@@ -835,7 +836,7 @@ elseif(FreeBSD)
src/detection/mouse/mouse_bsd.c
src/detection/netio/netio_bsd.c
src/detection/opengl/opengl_linux.c
src/detection/os/os_linux.c
src/detection/os/os_bsd.c
src/detection/packages/packages_bsd.c
src/detection/poweradapter/poweradapter_nosupport.c
src/detection/gtk_qt/qt.c
@@ -897,7 +898,7 @@ elseif(NetBSD)
src/detection/disk/disk_bsd.c
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_nbsd.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/diskio/diskio_nbsd.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
@@ -983,7 +984,7 @@ elseif(OpenBSD)
src/detection/disk/disk_bsd.c
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_obsd.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/diskio/diskio_obsd.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
@@ -1124,7 +1125,7 @@ elseif(APPLE)
src/detection/board/board_windows.c
src/detection/chassis/chassis_windows.c
src/detection/host/host_windows.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
)
else()
list(APPEND LIBFASTFETCH_SRC
@@ -1147,6 +1148,7 @@ elseif(WIN32)
src/common/windows/getline.c
src/common/windows/com.c
src/common/windows/folders.c
src/common/windows/glob.c
src/common/windows/registry.c
src/common/windows/unicode.c
src/common/windows/variant.cpp
@@ -1188,7 +1190,7 @@ elseif(WIN32)
src/detection/media/media_windows.cpp
src/detection/memory/memory_windows.c
src/detection/mouse/mouse_windows.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/netio/netio_windows.c
src/detection/opengl/opengl_windows.c
src/detection/os/os_windows.c
@@ -1244,7 +1246,7 @@ elseif(SunOS)
src/detection/disk/disk_sunos.c
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_sunos.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/diskio/diskio_sunos.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
@@ -1329,7 +1331,7 @@ elseif(Haiku)
src/detection/disk/disk_haiku.cpp
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_haiku.c
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/physicalmemory/physicalmemory_shared.c
src/detection/diskio/diskio_nosupport.c
src/detection/displayserver/displayserver_haiku.cpp
src/detection/font/font_haiku.cpp
@@ -1610,14 +1612,14 @@ if(APPLE AND EXISTS "/usr/bin/otool")
target_compile_definitions(libfastfetch PUBLIC FF_LIBSYSTEM_VERSION="${CMAKE_MATCH_1}")
endif()
endif()
if(MidnightBSD AND EXISTS "/usr/bin/objdump")
if(FreeBSD AND NOT DragonFly AND EXISTS "/usr/bin/objdump")
execute_process(COMMAND /bin/sh -c "/usr/bin/objdump -T /lib/libc.so.* | grep 'FBSD_[0-9][0-9]*\\.[0-9][0-9]*' -o | sort -Vru | head -1"
OUTPUT_VARIABLE OBJDUMP_T_RESULT)
if("${OBJDUMP_T_RESULT}" MATCHES "FBSD_([0-9]+\\.[0-9]+)")
message(STATUS "Found FBSD ${CMAKE_MATCH_1}")
target_compile_definitions(libfastfetch PUBLIC FF_FBSD_VERSION="${CMAKE_MATCH_1}")
endif()
elseif(FreeBSD AND EXISTS "/usr/local/bin/objdump")
elseif(FreeBSD AND NOT DragonFly AND EXISTS "/usr/local/bin/objdump")
execute_process(COMMAND /bin/sh -c "/usr/local/bin/objdump -T /lib/libc.so.* | grep 'FBSD_[0-9][0-9]*\\.[0-9][0-9]*' -o | sort -Vru | head -1"
OUTPUT_VARIABLE OBJDUMP_T_RESULT)
if("${OBJDUMP_T_RESULT}" MATCHES "FBSD_([0-9]+\\.[0-9]+)")
@@ -2293,8 +2295,12 @@ if(WIN32)
"${CMAKE_CURRENT_SOURCE_DIR}/src/common/windows/manifest.xml"
"${CMAKE_CURRENT_SOURCE_DIR}/src/common/windows/logo.ico"
)
set_property(SOURCE src/3rdparty/pawnio/pawnio.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/src/3rdparty/pawnio/IntelMSR.bin"
)
target_sources(fastfetch
PRIVATE src/common/windows/version.rc
PRIVATE src/3rdparty/pawnio/pawnio.rc
)
elseif(APPLE)
target_link_options(fastfetch
@@ -2332,6 +2338,7 @@ if (BUILD_FLASHFETCH)
if(WIN32)
target_sources(flashfetch
PRIVATE src/common/windows/version.rc
PRIVATE src/3rdparty/pawnio/pawnio.rc
)
elseif(APPLE)
# flashfetch embeds its own plist so that its CFBundleIdentifier matches the
@@ -2370,6 +2377,15 @@ if (BUILD_TESTS)
PRIVATE libfastfetch
)
if (WIN32)
add_executable(fastfetch-test-glob
tests/glob.c
)
target_link_libraries(fastfetch-test-glob
PRIVATE libfastfetch
)
endif()
add_executable(fastfetch-test-spin
tests/spin.c
)
@@ -2496,9 +2512,19 @@ if (BUILD_TESTS)
PRIVATE libfastfetch
)
add_executable(fastfetch-test-edid
tests/edid.c
)
target_link_libraries(fastfetch-test-edid
PRIVATE libfastfetch
)
enable_testing()
add_test(NAME test-cache COMMAND fastfetch-test-cache)
add_test(NAME test-logo COMMAND fastfetch-test-logo)
if (WIN32)
add_test(NAME test-glob COMMAND fastfetch-test-glob)
endif()
add_test(NAME test-spin COMMAND fastfetch-test-spin)
add_test(NAME test-strbuf COMMAND fastfetch-test-strbuf)
add_test(NAME test-list COMMAND fastfetch-test-list)
@@ -2517,6 +2543,9 @@ if (BUILD_TESTS)
add_test(NAME test-endian COMMAND fastfetch-test-endian)
add_test(NAME test-endian-bigendian COMMAND fastfetch-test-endian-bigendian)
add_test(NAME test-gpu-pci COMMAND fastfetch-test-gpu-pci)
add_test(NAME test-edid COMMAND fastfetch-test-edid)
# A regression in the EDID parser can turn the scan into an infinite loop.
set_tests_properties(test-edid PROPERTIES TIMEOUT 30)
endif()
##################
+1 -1
View File
@@ -176,7 +176,7 @@
"short": "l",
"long": "logo",
"desc": "Set the logo source. Use \"none\" to disable logo output",
"remark": "Use either a built-in logo name or a path to an image file. See also https://github.com/fastfetch-cli/fastfetch/wiki/Logo-options",
"remark": "Use either a built-in logo name or a path to an image file. Environment variables and glob patterns are expanded; if several files match a glob, one is selected randomly. See also https://github.com/fastfetch-cli/fastfetch/wiki/Logo-options",
"arg": {
"type": "logo"
}
+10 -2
View File
@@ -453,7 +453,7 @@
"type": "string"
},
"physicaldiskFormat": {
"description": "Output format for the `PhysicalDisk` module. See Wiki for formatting syntax\n 1. {size}: Device size (formatted)\n 2. {name}: Device name *\n 3. {interconnect}: Device interconnect type\n 4. {dev-path}: Device raw file path *\n 5. {serial}: Serial number\n 6. {physical-type}: Device kind (SSD or HDD)\n 7. {removable-type}: Device kind (Removable or Fixed)\n 8. {readonly-type}: Device kind (Read-only or Read-write)\n 9. {revision}: Product revision\n 10. {temperature}: Device temperature (formatted)",
"description": "Output format for the `PhysicalDisk` module. See Wiki for formatting syntax\n 1. {size}: Device size (formatted)\n 2. {name}: Device name *\n 3. {interconnect}: Device interconnect type\n 4. {dev-path}: Device raw file path *\n 5. {serial}: Serial number\n 6. {physical-type}: Device kind (SSD or HDD)\n 7. {removable-type}: Device kind (Removable or Fixed)\n 8. {readonly-type}: Device kind (Read-only or Read-write)\n 9. {revision}: Product revision\n 10. {temperature}: Device temperature (formatted)\n 11. {health}: Device health, 100 - percentage used (formatted)\n 12. {percent-used}: Percentage of rated endurance used\n 13. {available-spare}: Remaining spare capacity\n 14. {critical-warning}: Critical warnings (NVMe warnings or ATA SMART failing status)",
"type": "string"
},
"physicalmemoryFormat": {
@@ -665,7 +665,7 @@
},
"source": {
"type": "string",
"description": "Path to the logo source file. For the spin logo: `auto` (the detected OS), any built-in logo name, or a text file in fastfetch logo syntax"
"description": "Path to the logo source file. Environment variables (`%VAR%` on Windows, `$VAR` or `${VAR}`) and glob patterns (`*`, `?`, `[...]`) are expanded. If several files match a glob, one is selected randomly. For the spin logo: `auto` (the detected OS), any built-in logo name, or a text file in fastfetch logo syntax"
},
"spin": {
"type": "object",
@@ -3967,6 +3967,14 @@
"temp": {
"$ref": "#/$defs/temperature"
},
"health": {
"description": "Whether to detect and display drive health (NVMe wear / SMART status), if supported. On Windows and macOS, checking ATA disks may wake them from sleep",
"type": "boolean",
"default": false
},
"percent": {
"$ref": "#/$defs/percent"
},
"key": {
"$ref": "#/$defs/key"
},
+2 -1
View File
@@ -104,7 +104,8 @@
"diskio",
{
"type": "physicaldisk",
"temp": true
"temp": true,
"health": true
},
{
"type": "weather",
+502
View File
@@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
#ifdef RC_INVOKED
#include <winuser.h>
#include "pawnio_resource.h"
// Signed PawnIO module from namazso/PawnIO.Modules 0.2.12 (LGPL-2.1-or-later).
// Source and full license text: src/3rdparty/pawnio/
FF_PAWNIO_INTEL_MSR_RC_ID RCDATA "IntelMSR.bin"
#endif
+3
View File
@@ -0,0 +1,3 @@
#pragma once
#define FF_PAWNIO_INTEL_MSR_RC_ID 1
+1 -1
View File
@@ -567,7 +567,7 @@ static inline bool ffStrbufInitJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
// Not `pure`: the caller-supplied `fn` may have side effects
[[gnu::nonnull(1, 2), nodiscard]] static inline bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) {
return strbuf->length == 0 ? false : fn(strbuf->chars[strbuf->length - 1]);
return strbuf->length == 0 ? false : fn((unsigned char)strbuf->chars[strbuf->length - 1]);
}
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) {
+4
View File
@@ -10,6 +10,9 @@ typedef struct FFDBusLibrary {
FF_LIBRARY_SYMBOL(dbus_bus_get)
FF_LIBRARY_SYMBOL(dbus_message_new_method_call)
FF_LIBRARY_SYMBOL(dbus_message_append_args)
FF_LIBRARY_SYMBOL(dbus_message_iter_init_append)
FF_LIBRARY_SYMBOL(dbus_message_iter_open_container)
FF_LIBRARY_SYMBOL(dbus_message_iter_close_container)
FF_LIBRARY_SYMBOL(dbus_message_iter_init)
FF_LIBRARY_SYMBOL(dbus_message_iter_get_arg_type)
FF_LIBRARY_SYMBOL(dbus_message_iter_get_basic)
@@ -31,6 +34,7 @@ bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result);
bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result);
bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint64_t* result);
DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg1, const char* arg2);
DBusMessage* ffDBusGetMethodReplyEmptyDict(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method);
DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property);
bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result);
bool ffDBusGetInt(FFDBusData* dbus, DBusMessageIter* iter, int64_t* result);
+3 -3
View File
@@ -323,7 +323,7 @@ void ffStrbufTrimLeftSpace(FFstrbuf* strbuf) {
}
uint32_t index = 0;
while (index < strbuf->length && isspace(strbuf->chars[index])) {
while (index < strbuf->length && isspace((unsigned char)strbuf->chars[index])) {
++index;
}
@@ -609,13 +609,13 @@ void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool
void ffStrbufUpperCase(FFstrbuf* strbuf) {
for (uint32_t i = 0; i < strbuf->length; ++i) {
strbuf->chars[i] = (char) toupper(strbuf->chars[i]);
strbuf->chars[i] = (char) toupper((unsigned char) strbuf->chars[i]);
}
}
void ffStrbufLowerCase(FFstrbuf* strbuf) {
for (uint32_t i = 0; i < strbuf->length; ++i) {
strbuf->chars[i] = (char) tolower(strbuf->chars[i]);
strbuf->chars[i] = (char) tolower((unsigned char) strbuf->chars[i]);
}
}
+24
View File
@@ -11,6 +11,9 @@ static bool loadLibSymbols(FFDBusLibrary* lib) {
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_bus_get, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_new_method_call, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_append_args, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_iter_init_append, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_iter_open_container, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_iter_close_container, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_iter_init, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_iter_get_arg_type, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_iter_get_basic, false)
@@ -276,6 +279,27 @@ DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const c
return reply;
}
DBusMessage* ffDBusGetMethodReplyEmptyDict(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method) {
DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, interface, method);
if (message == nullptr) {
return nullptr;
}
DBusMessageIter iter, dictIter;
dbus->lib->ffdbus_message_iter_init_append(message, &iter);
if (!dbus->lib->ffdbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &dictIter) ||
!dbus->lib->ffdbus_message_iter_close_container(&iter, &dictIter)) {
dbus->lib->ffdbus_message_unref(message);
return nullptr;
}
DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, nullptr);
dbus->lib->ffdbus_message_unref(message);
return reply;
}
DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property) {
DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, "org.freedesktop.DBus.Properties", "Get");
if (message == nullptr) {
+8 -4
View File
@@ -122,10 +122,12 @@ bool ffEdidGetSerial(const uint8_t edid[128], FFstrbuf* result) {
}
bool ffEdidGetHdrCompatible(const uint8_t* edid, uint32_t length) {
if (length <= 128) {
if (length < 256) {
return false;
}
for (const uint8_t* cta = &edid[128]; cta < &edid[length]; cta += 128) {
// Only complete 128-byte extension blocks may be inspected.
for (uint32_t base = 128; base <= length - 128; base += 128) {
const uint8_t* cta = edid + base;
// https://en.wikipedia.org/wiki/Extended_Display_Identification_Data#CTA_EDID_Timing_Extension_Block
if (cta[0] != 0x02 /* CTA EDID */) {
continue;
@@ -137,7 +139,9 @@ bool ffEdidGetHdrCompatible(const uint8_t* edid, uint32_t length) {
if (offset <= 4) {
continue;
}
for (uint8_t i = 4; i < offset;) {
// Byte 2 is an offset inside this block; byte 127 is the checksum.
const uint32_t end = offset > 127 ? 127 : offset;
for (uint32_t i = 4; i + 1 < end;) {
uint8_t blkLen = cta[i] & 0x1f;
if (blkLen > 0) {
uint8_t blkTag = (cta[i] & 0xe0) >> 5;
@@ -148,7 +152,7 @@ bool ffEdidGetHdrCompatible(const uint8_t* edid, uint32_t length) {
}
}
}
i += (uint8_t) (blkLen + 1);
i += (uint32_t) blkLen + 1;
}
}
return false;
+1 -1
View File
@@ -91,7 +91,7 @@ void ffFontInitQt(FFfont* font, const char* data) {
goto exit;
}
data++;
if (isalpha(*data)) {
if (isalpha((unsigned char) *data)) {
do {
FFstrbuf* style = FF_LIST_ADD(FFstrbuf, font->styles);
ffStrbufInit(style);
+7 -20
View File
@@ -3,6 +3,7 @@
#include "common/io.h"
#include "common/strutil.h"
#include "common/time.h"
#include "common/windows/glob.h"
#include "common/windows/nt.h"
#include "common/windows/unicode.h"
@@ -284,28 +285,14 @@ HANDLE openat(HANDLE dfd, const char* fileName, int oflag) {
}
bool ffPathExpandEnv(const char* in, FFstrbuf* out) {
if (in[0] == '~') {
if ((in[1] == '/' || in[1] == '\\' || in[1] == '\0') && !ffStrContainsC(in, '%')) {
ffStrbufSet(out, &instance.state.platform.homeDir);
ffStrbufAppendS(out, in + 1);
return true;
}
if (in[0] == '~' && (in[1] == '/' || in[1] == '\\' || in[1] == '\0')) {
FF_STRBUF_AUTO_DESTROY expanded = ffStrbufCreate();
ffStrbufSet(&expanded, &instance.state.platform.homeDir);
ffStrbufAppendS(&expanded, in + 1);
return ffGlobWindows(expanded.chars, out);
}
wchar_t pathInW[MAX_PATH], pathOutW[MAX_PATH];
ULONG len = (ULONG) strlen(in);
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(pathInW, (ULONG) sizeof(pathInW), &len, in, len))) {
return false;
}
len /= sizeof(wchar_t); // convert from bytes to characters
SIZE_T outLen; // in characters, including null terminator
if (!NT_SUCCESS(RtlExpandEnvironmentStrings(nullptr, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) {
return false;
}
ffStrbufSetNWS(out, (uint32_t) outLen - 1, pathOutW);
return true;
return ffGlobWindows(in, out);
}
bool ffSuppressIO(bool suppress) {
+1 -1
View File
@@ -34,7 +34,7 @@ bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buff
}
// Line doesn't match start, skip it
if (tolower(**line) != tolower(*start) || **line == '\0') {
if (tolower((unsigned char) **line) != tolower((unsigned char) *start) || **line == '\0') {
return false;
}
+1 -1
View File
@@ -28,7 +28,7 @@ static inline bool ffStrSet(const char* str) {
return false;
}
while (isspace(*str)) {
while (isspace((unsigned char)*str)) {
str++;
}
+2 -1
View File
@@ -58,7 +58,8 @@ static inline bool ffTimeSleep(uint32_t msec) {
interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals
return NT_SUCCESS(NtDelayExecution(TRUE, &interval));
#else
return nanosleep(&(struct timespec) { msec / 1000, (long) (msec % 1000) * 1000000 }, nullptr) == 0;
struct timespec interval = { msec / 1000, (long) (msec % 1000) * 1000000 };
return nanosleep(&interval, nullptr) == 0;
#endif
}
+393
View File
@@ -0,0 +1,393 @@
#include "common/windows/glob.h"
#include "common/FFlist.h"
#include "common/mallocHelper.h"
#include "common/time.h"
#include "common/windows/nt.h"
#include "common/windows/unicode.h"
#include <wchar.h>
#include <windows.h>
// Windows has no glob(3). FindFirstFileW() accepts wildcards only in the last component, and its
// wildcard matching follows the old DOS rules (a `?` can match a zero-length suffix, and `*.ext`
// matches files whose 8.3 short name has that extension). Enumerating a directory with `*` and
// applying our own matcher gives the same semantics as glob(3) on Unix, including character classes
// and wildcards in intermediate components.
//
// Everything below works on UTF-16 so that names outside the ANSI code page survive, and so that
// `?` matches one Unicode character instead of one UTF-8 byte.
static bool isEnvNameStart(wchar_t value) {
return (value >= L'A' && value <= L'Z') || (value >= L'a' && value <= L'z') || value == L'_';
}
static bool isEnvNameChar(wchar_t value) {
return isEnvNameStart(value) || (value >= L'0' && value <= L'9');
}
// Appends the value of the environment variable whose name is `name[0 .. nameLength)`.
// Returns false when the variable is not defined, so the caller can leave the original
// `%NAME%` / `$NAME` text in place.
static bool appendEnvValue(const wchar_t* name, uint32_t nameLength, FFWStrbuf* out) {
if (nameLength == 0 || nameLength > 0x7FFF) {
return false;
}
wchar_t stackName[128];
wchar_t* nameBuffer = nameLength < ARRAY_SIZE(stackName)
? stackName
: (wchar_t*) malloc(((size_t) nameLength + 1) * sizeof(wchar_t));
if (nameBuffer == nullptr) {
return false;
}
memcpy(nameBuffer, name, (size_t) nameLength * sizeof(wchar_t));
nameBuffer[nameLength] = L'\0';
// An empty variable is reported as a required length of zero; the last error tells it apart
// from a variable that does not exist at all.
SetLastError(ERROR_SUCCESS);
DWORD needed = GetEnvironmentVariableW(nameBuffer, nullptr, 0);
bool found = false;
if (needed == 0) {
found = GetLastError() == ERROR_SUCCESS;
} else {
FF_AUTO_FREE wchar_t* value = (wchar_t*) malloc((size_t) needed * sizeof(wchar_t));
if (value != nullptr) {
DWORD written = GetEnvironmentVariableW(nameBuffer, value, needed);
if (written > 0) {
ffWStrbufAppendNS(out, (uint32_t) written, value);
found = true;
}
}
}
if (nameBuffer != stackName) {
free(nameBuffer);
}
return found;
}
// Expands `%NAME%`, `$NAME` and `${NAME}` in one pass. Values inserted by the expansion are not
// expanded again.
static void expandEnv(const wchar_t* in, FFWStrbuf* out) {
for (const wchar_t* p = in; *p != L'\0';) {
if (*p == L'%') {
const wchar_t* end = wcschr(p + 1, L'%');
if (end != nullptr && end != p + 1 && appendEnvValue(p + 1, (uint32_t) (end - p - 1), out)) {
p = end + 1;
continue;
}
ffWStrbufAppendC(out, *p++);
} else if (*p == L'$') {
const wchar_t* name = p + 1;
const wchar_t* after = nullptr;
if (*name == L'{') {
const wchar_t* end = wcschr(name + 1, L'}');
if (end != nullptr && end != name + 1) {
++name;
after = end + 1;
if (appendEnvValue(name, (uint32_t) (end - name), out)) {
p = after;
continue;
}
}
} else if (isEnvNameStart(*name)) {
const wchar_t* end = name + 1;
while (isEnvNameChar(*end)) {
++end;
}
after = end;
if (appendEnvValue(name, (uint32_t) (end - name), out)) {
p = after;
continue;
}
}
ffWStrbufAppendC(out, *p++);
} else {
ffWStrbufAppendC(out, *p++);
}
}
}
static bool isSeparator(wchar_t value) {
return value == L'\\' || value == L'/';
}
static const wchar_t* findSeparator(const wchar_t* value) {
while (*value != L'\0' && !isSeparator(*value)) {
++value;
}
return *value == L'\0' ? nullptr : value;
}
static void appendPathComponent(FFWStrbuf* path, const wchar_t* component, uint32_t length) {
// `C:` is drive-relative: `C:foo`, not `C:\foo`.
if (path->length > 0 && !isSeparator(path->chars[path->length - 1]) &&
!(path->length == 2 && path->chars[1] == L':')) {
ffWStrbufAppendC(path, L'\\');
}
ffWStrbufAppendNS(path, length, component);
}
static bool componentHasWildcard(const wchar_t* value, uint32_t length) {
for (uint32_t i = 0; i < length; ++i) {
if (value[i] == L'*' || value[i] == L'?' || value[i] == L'[') {
return true;
}
}
return false;
}
// Returns -1 if the pattern is not a valid bracket expression, 0 if it is valid but does not
// match `value`, and 1 if it matches.
static int matchBracket(wchar_t value, const wchar_t* pattern, uint32_t length, uint32_t* consumed) {
assert(length > 0 && pattern[0] == L'[');
uint32_t i = 1;
bool negate = false;
if (i < length && (pattern[i] == L'!' || pattern[i] == L'^')) {
negate = true;
++i;
}
bool matched = false;
bool first = true;
uint32_t closing = UINT32_MAX;
wchar_t upperValue = (wchar_t) RtlUpcaseUnicodeChar(value);
while (i < length) {
if (pattern[i] == L']' && !first) {
closing = i;
break;
}
first = false;
wchar_t start = pattern[i];
wchar_t end = start;
uint32_t next = i + 1;
if (next + 1 < length && pattern[next] == L'-' && pattern[next + 1] != L']') {
end = pattern[next + 1];
next += 2;
}
wchar_t upperStart = (wchar_t) RtlUpcaseUnicodeChar(start);
wchar_t upperEnd = (wchar_t) RtlUpcaseUnicodeChar(end);
if (upperValue >= upperStart && upperValue <= upperEnd) {
matched = true;
}
i = next;
}
if (closing == UINT32_MAX) {
return -1;
}
*consumed = closing + 1;
return negate ? !matched : matched;
}
// Matches one character, and reports how many pattern characters were consumed.
static bool matchOne(wchar_t value, const wchar_t* pattern, uint32_t length, uint32_t* consumed) {
if (pattern[0] == L'?') {
*consumed = 1;
return true;
}
if (pattern[0] == L'[') {
int result = matchBracket(value, pattern, length, consumed);
if (result >= 0) {
return result != 0;
}
// Not a valid bracket expression: treat '[' as a literal character.
}
*consumed = 1;
return RtlUpcaseUnicodeChar(value) == RtlUpcaseUnicodeChar(pattern[0]);
}
static bool wildcardMatch(const wchar_t* name, uint32_t nameLength, const wchar_t* pattern, uint32_t patternLength) {
uint32_t nameIndex = 0;
uint32_t patternIndex = 0;
uint32_t starPattern = UINT32_MAX;
uint32_t starName = 0;
while (nameIndex < nameLength) {
if (patternIndex < patternLength && pattern[patternIndex] == L'*') {
while (patternIndex < patternLength && pattern[patternIndex] == L'*') {
++patternIndex;
}
if (patternIndex == patternLength) {
return true;
}
starPattern = patternIndex;
starName = nameIndex;
continue;
}
uint32_t consumed = 0;
if (patternIndex < patternLength &&
matchOne(name[nameIndex], pattern + patternIndex, patternLength - patternIndex, &consumed)) {
++nameIndex;
patternIndex += consumed;
continue;
}
if (starPattern == UINT32_MAX) {
return false;
}
patternIndex = starPattern;
nameIndex = ++starName;
}
while (patternIndex < patternLength && pattern[patternIndex] == L'*') {
++patternIndex;
}
return patternIndex == patternLength;
}
// Splits the volume / root prefix from `pattern` and appends it to `path`.
static const wchar_t* parseRoot(FFWStrbuf* path, const wchar_t* pattern) {
if (isSeparator(pattern[0]) && isSeparator(pattern[1])) {
// UNC path: \\server\share\...
const wchar_t* server = pattern + 2;
const wchar_t* serverEnd = findSeparator(server);
if (serverEnd == nullptr) {
uint32_t length = (uint32_t) wcslen(pattern);
ffWStrbufAppendNS(path, length, pattern);
return pattern + length;
}
const wchar_t* shareEnd = findSeparator(serverEnd + 1);
if (shareEnd == nullptr) {
uint32_t length = (uint32_t) wcslen(pattern);
ffWStrbufAppendNS(path, length, pattern);
return pattern + length;
}
uint32_t prefixLength = (uint32_t) (shareEnd + 1 - pattern);
ffWStrbufAppendNS(path, prefixLength, pattern);
return shareEnd + 1;
}
if (((pattern[0] >= L'A' && pattern[0] <= L'Z') || (pattern[0] >= L'a' && pattern[0] <= L'z')) &&
pattern[1] == L':') {
ffWStrbufAppendNS(path, 2, pattern);
if (isSeparator(pattern[2])) {
ffWStrbufAppendC(path, L'\\');
return pattern + 3;
}
return pattern + 2;
}
if (isSeparator(pattern[0])) {
ffWStrbufAppendC(path, L'\\');
return pattern + 1;
}
return pattern;
}
static void globRecurse(FFWStrbuf* path, const wchar_t* pattern, FFlist* results) {
while (isSeparator(*pattern)) {
++pattern;
}
if (*pattern == L'\0') {
if (GetFileAttributesW(path->chars) == INVALID_FILE_ATTRIBUTES) {
return;
}
FFstrbuf* result = FF_LIST_ADD(FFstrbuf, *results);
ffStrbufInitNWS(result, path->length, path->chars);
return;
}
const wchar_t* end = pattern;
while (*end != L'\0' && !isSeparator(*end)) {
++end;
}
uint32_t componentLength = (uint32_t) (end - pattern);
uint32_t savedLength = path->length;
if (!componentHasWildcard(pattern, componentLength)) {
appendPathComponent(path, pattern, componentLength);
globRecurse(path, end, results);
path->length = savedLength;
path->chars[savedLength] = L'\0';
return;
}
appendPathComponent(path, L"*", 1);
WIN32_FIND_DATAW entry;
HANDLE handle = FindFirstFileW(path->chars, &entry);
path->length = savedLength;
path->chars[savedLength] = L'\0';
if (handle == INVALID_HANDLE_VALUE) {
return;
}
do {
// Like glob(3), a wildcard does not match entries whose name starts with a dot unless the
// pattern itself starts with one. `.` and `..` are never returned as glob results.
if (entry.cFileName[0] == L'.' && pattern[0] != L'.') {
continue;
}
if (entry.cFileName[0] == L'.' &&
(entry.cFileName[1] == L'\0' || (entry.cFileName[1] == L'.' && entry.cFileName[2] == L'\0'))) {
continue;
}
uint32_t nameLength = (uint32_t) wcslen(entry.cFileName);
if (!wildcardMatch(entry.cFileName, nameLength, pattern, componentLength)) {
continue;
}
uint32_t lengthBeforeEntry = path->length;
appendPathComponent(path, entry.cFileName, nameLength);
globRecurse(path, end, results);
path->length = lengthBeforeEntry;
path->chars[lengthBeforeEntry] = L'\0';
} while (FindNextFileW(handle, &entry));
FindClose(handle);
}
bool ffGlobWindows(const char* in, FFstrbuf* out) {
FF_WSTRBUF_AUTO_DESTROY wide = ffWStrbufCreateUtf8(in);
if (wide.chars == nullptr) {
return false;
}
FF_WSTRBUF_AUTO_DESTROY expanded = ffWStrbufCreate();
expandEnv(wide.chars, &expanded);
if (wcspbrk(expanded.chars, L"*?[") == nullptr) {
ffStrbufSetNWS(out, expanded.length, expanded.chars);
return true;
}
FF_WSTRBUF_AUTO_DESTROY path = ffWStrbufCreate();
const wchar_t* components = parseRoot(&path, expanded.chars);
FF_LIST_AUTO_DESTROY results = ffListCreate();
globRecurse(&path, components, &results);
bool found = results.length > 0;
if (found) {
uint32_t index = results.length > 1 ? (uint32_t) (ffTimeGetNow() % results.length) : 0;
ffStrbufSet(out, FF_LIST_GET(FFstrbuf, results, index));
}
if (results.length > 0) {
FF_LIST_FOR_EACH (FFstrbuf, result, results) {
ffStrbufDestroy(result);
}
}
return found;
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include "common/FFstrbuf.h"
// Expands environment variables and glob patterns in a Windows path.
//
// Environment variables may be written as `%NAME%` for compatibility with existing
// configurations, or as `$NAME` / `${NAME}`. A variable that is not defined is left
// untouched, so paths that legitimately contain a `$` or `%` keep working.
//
// Glob patterns support `*`, `?` and `[...]` character classes. Both `/` and `\` are
// accepted as path separators. If more than one path matches, one is chosen
// pseudo-randomly, mirroring the Unix implementation in io_unix.c.
//
// Returns false if a wildcard pattern matches nothing.
[[gnu::nonnull(1, 2)]] bool ffGlobWindows(const char* in, FFstrbuf* out);
+7 -1
View File
@@ -66,7 +66,10 @@ typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX {
} PROCESS_DEVICEMAP_INFORMATION_EX, *PPROCESS_DEVICEMAP_INFORMATION_EX;
#ifndef NtCurrentProcess
#define NtCurrentProcess() ((HANDLE) (LONG_PTR) - 1)
#define NtCurrentProcess() ((HANDLE) (LONG_PTR) -1)
#endif
#ifndef NtCurrentThread
#define NtCurrentThread() ((HANDLE) (LONG_PTR) -2)
#endif
typedef struct _CURDIR {
@@ -778,6 +781,9 @@ NTSYSAPI NTSTATUS NTAPI RtlUTF8ToUnicodeN(
_In_reads_bytes_(UTF8StringByteCount) PCCH UTF8StringSource,
_In_ ULONG UTF8StringByteCount);
NTSYSAPI WCHAR NTAPI RtlUpcaseUnicodeChar(
_In_ WCHAR SourceCharacter);
#define RTL_MAX_DRIVE_LETTERS 32
typedef struct _RTL_DRIVE_LETTER_CURDIR {
USHORT Flags;
+23
View File
@@ -2,6 +2,29 @@
#include "common/windows/nt.h"
FFWStrbuf ffWStrbufCreateUtf8(const char* in) {
FFWStrbuf strbuf = { .chars = nullptr, .length = 0, .capacity = 0 };
ULONG inputLength = (ULONG) strlen(in) + 1;
ULONG size = 0;
(void) RtlUTF8ToUnicodeN(nullptr, 0, &size, in, inputLength);
if (size == 0) {
return strbuf;
}
wchar_t* result = (wchar_t*) malloc(size);
ULONG written = 0;
if (!result || !NT_SUCCESS(RtlUTF8ToUnicodeN(result, size, &written, in, inputLength))) {
free(result);
return strbuf;
}
strbuf.chars = result;
strbuf.capacity = (uint32_t) (size / sizeof(wchar_t));
strbuf.length = (uint32_t) wcslen(result);
return strbuf;
}
void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) {
if (!length) {
ffStrbufClear(result);
+77
View File
@@ -3,6 +3,83 @@
#include "common/FFstrbuf.h"
#include <wchar.h>
// ---------------------------------------------------------------------------------------------
// A wide-character string buffer for building UTF-16 paths. It follows the FFstrbuf
// Init / Create / Destroy / Append* conventions, but is always heap allocated: `capacity`
// counts wchar_t slots including the null terminator. A destroyed buffer (or the result of a
// failed conversion) is zeroed with `chars == nullptr`, which is safe to destroy again.
// ---------------------------------------------------------------------------------------------
#define FASTFETCH_WSTRBUF_DEFAULT_ALLOC 64
typedef struct FFWStrbuf {
wchar_t* chars;
uint32_t length;
uint32_t capacity;
} FFWStrbuf;
[[gnu::nonnull(1)]] static inline void ffWStrbufEnsureFree(FFWStrbuf* strbuf, uint32_t free) {
uint64_t required = (uint64_t) strbuf->length + free + 1; // +1 for the null terminator
if (required <= strbuf->capacity) {
return;
}
uint32_t capacity = strbuf->capacity == 0 ? FASTFETCH_WSTRBUF_DEFAULT_ALLOC : strbuf->capacity;
while (capacity < required) {
if (capacity > UINT32_MAX / 2) {
capacity = (uint32_t) required;
break;
}
capacity *= 2;
}
strbuf->chars = (wchar_t*) realloc(strbuf->chars, (size_t) capacity * sizeof(wchar_t));
strbuf->capacity = capacity;
}
[[gnu::nonnull(1)]] static inline void ffWStrbufInit(FFWStrbuf* strbuf) {
strbuf->chars = nullptr;
strbuf->length = 0;
strbuf->capacity = 0;
ffWStrbufEnsureFree(strbuf, 0);
strbuf->chars[0] = L'\0';
}
// Despite the name, resets the buffer to the initial, unallocated state
[[gnu::nonnull(1)]] static inline void ffWStrbufDestroy(FFWStrbuf* strbuf) {
free(strbuf->chars);
strbuf->chars = nullptr;
strbuf->length = 0;
strbuf->capacity = 0;
}
[[gnu::nonnull(1)]] static inline void ffWStrbufAppendNS(FFWStrbuf* strbuf, uint32_t length, const wchar_t* value) {
ffWStrbufEnsureFree(strbuf, length);
if (length > 0) {
memcpy(strbuf->chars + strbuf->length, value, (size_t) length * sizeof(wchar_t));
}
strbuf->length += length;
strbuf->chars[strbuf->length] = L'\0';
}
[[gnu::nonnull(1)]] static inline void ffWStrbufAppendC(FFWStrbuf* strbuf, wchar_t value) {
ffWStrbufEnsureFree(strbuf, 1);
strbuf->chars[strbuf->length++] = value;
strbuf->chars[strbuf->length] = L'\0';
}
[[nodiscard]] static inline FFWStrbuf ffWStrbufCreate(void) {
FFWStrbuf strbuf;
ffWStrbufInit(&strbuf);
return strbuf;
}
// Converts a null-terminated UTF-8 string into a new UTF-16 buffer. `chars` is nullptr if the
// conversion failed; the returned value is always safe to pass to ffWStrbufDestroy.
[[gnu::nonnull(1), nodiscard]] FFWStrbuf ffWStrbufCreateUtf8(const char* in);
#define FF_WSTRBUF_AUTO_DESTROY [[gnu::cleanup(ffWStrbufDestroy)]] FFWStrbuf
void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source);
void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source);
+1 -1
View File
@@ -33,7 +33,7 @@ const char* ffDetectChassis(FFChassisResult* result) {
}
} else if (ffReadFileBuffer("/sys/firmware/devicetree/base/chassis-type", &result->type) && result->type.length > 0) {
ffStrbufTrimRight(&result->type, '\0');
result->type.chars[0] = (char) toupper(result->type.chars[0]);
result->type.chars[0] = (char) toupper((unsigned char) result->type.chars[0]);
}
}
return nullptr;
+4 -4
View File
@@ -465,7 +465,7 @@ static void detectAndroid(FFCPUResult* cpu) {
} else if (ffStrbufIgnCaseEqualS(&cpu->vendor, "MediaTek")) { // sometimes "Mediatek"
ffStrbufSetStatic(&cpu->vendor, "MediaTek");
} else if (cpu->vendor.length > 0) {
cpu->vendor.chars[0] = (char) toupper(cpu->vendor.chars[0]);
cpu->vendor.chars[0] = (char) toupper((unsigned char) cpu->vendor.chars[0]);
}
if (ffStrbufEqualS(&cpu->vendor, "Qualcomm") && ffStrbufStartsWithS(&cpu->name, "SM")) {
@@ -1032,18 +1032,18 @@ static const char* detectPhysicalCores(FFCPUResult* cpu) {
// Raspberry Pi
ffStrbufSetStatic(&cpu->vendor, "Broadcom");
for (const char* p = model; *p; ++p) {
ffStrbufAppendC(&cpu->name, (char) toupper(*p));
ffStrbufAppendC(&cpu->name, (char) toupper((unsigned char) *p));
}
} else if (ffStrEquals(vendor, "thead")) {
// Lichee Pi?
ffStrbufSetStatic(&cpu->vendor, "T-Head");
for (const char* p = model; *p; ++p) {
ffStrbufAppendC(&cpu->name, (char) toupper(*p));
ffStrbufAppendC(&cpu->name, (char) toupper((unsigned char) *p));
}
} else {
ffStrbufSetS(&cpu->name, model);
ffStrbufSetS(&cpu->vendor, vendor);
cpu->vendor.chars[0] = (char) toupper(vendor[0]);
cpu->vendor.chars[0] = (char) toupper((unsigned char) vendor[0]);
}
}
+177 -1
View File
@@ -7,10 +7,173 @@
#include "common/smbios.h"
#include <windows.h>
#include <winioctl.h>
#include "common/windows/perflib_.h"
#include "common/windows/nt.h"
#include "common/time.h"
#include "3rdparty/pawnio/pawnio_resource.h"
#include <wchar.h>
#if defined(__x86_64__)
// The signed IntelMSR module is embedded as an RCDATA resource (see pawnio.rc).
// It comes from PawnIO.Modules 0.2.12, LGPL-2.1-or-later; its source and license text
// are shipped in src/3rdparty/pawnio/.
#define FF_PAWNIO_DEVICE_TYPE 41394
#define FF_PAWNIO_IOCTL_LOAD ((DWORD) CTL_CODE(FF_PAWNIO_DEVICE_TYPE, 0x821, METHOD_BUFFERED, FILE_ANY_ACCESS))
#define FF_PAWNIO_IOCTL_EXECUTE ((DWORD) CTL_CODE(FF_PAWNIO_DEVICE_TYPE, 0x841, METHOD_BUFFERED, FILE_ANY_ACCESS))
#define FF_PAWNIO_FN_NAME_LENGTH 32
enum : uint32_t {
MSR_IA32_THERM_STATUS = 0x0000019c,
MSR_IA32_TEMPERATURE_TARGET = 0x000001a2,
MSR_TURBO_RATIO_LIMIT = 0x000001ad,
MSR_IA32_PACKAGE_THERM_STATUS = 0x000001b1,
};
// Open the driver directly so we can log the exact failure reason.
static HANDLE pawnIoOpenDevice(void) {
const HANDLE handle = CreateFileW(L"\\\\.\\PawnIO", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, 0, nullptr);
if (handle != INVALID_HANDLE_VALUE) {
return handle;
}
#ifndef NDEBUG
const DWORD error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) {
FF_DEBUG("PawnIO device not found; the driver is probably not installed");
} else if (error == ERROR_ACCESS_DENIED) {
FF_DEBUG("PawnIO device access denied; elevation is required");
} else {
FF_DEBUG("Failed to open PawnIO device: %s", ffDebugWin32Error(error));
}
#endif
return INVALID_HANDLE_VALUE;
}
static bool pawnIoLoadModule(HANDLE handle) {
const HRSRC resource = FindResourceW(nullptr, MAKEINTRESOURCEW(FF_PAWNIO_INTEL_MSR_RC_ID), RT_RCDATA);
if (!resource) {
FF_DEBUG("PawnIO module resource not found: %s", ffDebugWin32Error(GetLastError()));
return false;
}
const HGLOBAL global = LoadResource(nullptr, resource);
if (!global) {
FF_DEBUG("LoadResource(PawnIO module) failed: %s", ffDebugWin32Error(GetLastError()));
return false;
}
const DWORD blobSize = SizeofResource(nullptr, resource);
const void* const blob = LockResource(global);
if (blobSize == 0 || !blob) {
FF_DEBUG("PawnIO module resource is empty");
return false;
}
DWORD bytesReturned = 0;
if (!DeviceIoControl(handle, FF_PAWNIO_IOCTL_LOAD, (void*) blob, blobSize, nullptr, 0, &bytesReturned, nullptr)) {
FF_DEBUG("PawnIO module load failed: %s", ffDebugWin32Error(GetLastError()));
return false;
}
return true;
}
static bool pawnIoExecute(HANDLE handle, const char* name, uint64_t msr, uint64_t* value) {
if (strlen(name) >= FF_PAWNIO_FN_NAME_LENGTH) {
return false;
}
char input[FF_PAWNIO_FN_NAME_LENGTH + sizeof(uint64_t)] = {};
memcpy(input, name, strlen(name));
memcpy(input + FF_PAWNIO_FN_NAME_LENGTH, &msr, sizeof(msr));
DWORD bytesReturned = 0;
if (!DeviceIoControl(handle, FF_PAWNIO_IOCTL_EXECUTE, input, sizeof(input), value, sizeof(*value), &bytesReturned, nullptr)) {
FF_DEBUG("PawnIO %s() failed: %s", name, ffDebugWin32Error(GetLastError()));
return false;
}
return bytesReturned == sizeof(*value);
}
static double pawnIoReadCoreTemp(HANDLE handle, uint16_t tjmax) {
KAFFINITY newMask = 0b11;
NTSTATUS status = NtSetInformationThread(NtCurrentThread(), ThreadAffinityMask, &newMask, sizeof(newMask));
if (!NT_SUCCESS(status)) {
FF_DEBUG("Failed to set thread affinity mask: %s", ffDebugNtStatus(status));
}
// Changing the affinity mask does not migrate an already running thread immediately.
ffTimeSleep(0);
uint64_t value = 0;
const bool success = pawnIoExecute(handle, "ioctl_read_msr", MSR_IA32_THERM_STATUS, &value);
if (!success || !(value & (UINT64_C(1) << 31))) {
return FF_CPU_TEMP_UNSET;
}
const uint32_t dts = (uint32_t) ((value >> 16) & 0x7f);
if (dts >= 0x7f) {
return FF_CPU_TEMP_UNSET;
}
return (double) tjmax - dts;
}
static bool detectTemperatureByPawnIo(HANDLE handle, const FFCPUResult* cpu, double* result) {
if (!ffStrbufEqualS(&cpu->vendor, "GenuineIntel")) {
return false;
}
uint64_t target = 0, package = 0;
if (!pawnIoExecute(handle, "ioctl_read_msr", MSR_IA32_TEMPERATURE_TARGET, &target) ||
!pawnIoExecute(handle, "ioctl_read_msr", MSR_IA32_PACKAGE_THERM_STATUS, &package)) {
return false;
}
uint16_t tjmax = (uint16_t) ((target >> 16) & 0xff);
if (tjmax < 40 || tjmax > 125) {
tjmax = 100;
}
double temperature = pawnIoReadCoreTemp(handle, tjmax);
if (temperature == FF_CPU_TEMP_UNSET && package & (UINT64_C(1) << 31)) {
const uint32_t dts = (uint32_t) ((package >> 16) & 0x7f);
if (dts < 0x7f) {
temperature = (double) tjmax - dts;
}
}
if (temperature == FF_CPU_TEMP_UNSET) {
return false;
}
*result = temperature;
FF_DEBUG("PawnIO CPU temperature: %.1f C (tjmax %u, core 0)", temperature, tjmax);
return true;
}
// IA32_TURBO_RATIO_LIMIT[7:0] is the 1-core P-core turbo ratio. Intel uses a 100 MHz bus clock.
static bool detectFrequencyMaxByPawnIo(HANDLE handle, FFCPUResult* cpu) {
uint64_t value = 0;
if (!pawnIoExecute(handle, "ioctl_read_msr", MSR_TURBO_RATIO_LIMIT, &value)) {
return false;
}
const uint32_t ratio = (uint32_t) (value & 0xff);
if (ratio < 4 || ratio > 128) {
return false;
}
cpu->frequencyMax = ratio * 100;
FF_DEBUG("PawnIO CPU max frequency: %u MHz (MSR 0x1AD ratio %u)", cpu->frequencyMax, ratio);
return true;
}
#endif
static inline void ffPerfCloseQueryHandle(HANDLE* phQuery) {
if (*phQuery != nullptr) {
PerfCloseQueryHandle(*phQuery);
@@ -343,7 +506,20 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) {
detectMaxSpeedBySmbios(cpu);
}
if (options->temp) {
bool pawnIoTemperature = false;
#ifdef __x86_64__
if (ffStrbufEqualS(&cpu->vendor, "GenuineIntel")) {
FF_AUTO_CLOSE_FD HANDLE hPawnIo = pawnIoOpenDevice();
if (hPawnIo != INVALID_HANDLE_VALUE && pawnIoLoadModule(hPawnIo)) {
detectFrequencyMaxByPawnIo(hPawnIo, cpu);
if (options->temp) {
pawnIoTemperature = detectTemperatureByPawnIo(hPawnIo, cpu, &cpu->temperature);
}
}
}
#endif
if (options->temp && !pawnIoTemperature) {
detectThermalTemp(options, &cpu->temperature);
}
+2 -1
View File
@@ -133,9 +133,10 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) {
}
ffStrbufAppendS(&path, pathCpuEntry->d_name);
// Skip a CPU whose cache can't be read, e.g. an offline one: the kernel removes its `cache/`
const char* error = parseCpuCache(&path, result, &buffer, &added);
if (error) {
return error;
FF_DEBUG("Skipping \"%s\": %s", pathCpuEntry->d_name, error);
}
ffStrbufSubstrBefore(&path, baseLen);
}
+7 -4
View File
@@ -48,9 +48,6 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) {
double preferredRefreshRate = 0;
FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate();
ffStrbufSubstrBefore(&drmDir, drmDirWithDnameLength);
ffStrbufAppendS(&drmDir, "/edid");
const char* plainName = entry->d_name;
if (ffStrStartsWith(plainName, "card")) {
const char* tmp = strchr(plainName + strlen("card"), '-');
@@ -63,15 +60,21 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) {
ffStrbufAppendS(&drmDir, "/modes");
char modes[32];
if (ffReadFileData(drmDir.chars, ARRAY_SIZE(modes), modes) >= 3) {
ssize_t modesLength = ffReadFileData(drmDir.chars, ARRAY_SIZE(modes) - 1, modes);
if (modesLength >= 3) {
modes[modesLength] = '\0'; // sscanf requires a NUL-terminated string
// This is actually preferred resolution
sscanf(modes, "%ux%u", &width, &height);
ffStrbufAppendS(&name, plainName);
}
ffStrbufSubstrBefore(&drmDir, drmDirWithDnameLength);
ffStrbufAppendS(&drmDir, "/edid");
uint8_t edidData[1024];
ssize_t edidLength = ffReadFileData(drmDir.chars, ARRAY_SIZE(edidData), edidData);
if (edidLength > 0 && ffEdidIsValid(edidData, (uint32_t) edidLength)) {
ffStrbufClear(&name);
ffEdidGetName(edidData, &name);
ffEdidGetPreferredResolutionAndRefreshRate(edidData, &preferredWidth, &preferredHeight, &preferredRefreshRate);
ffEdidGetPhysicalSize(edidData, &physicalWidth, &physicalHeight);
@@ -48,9 +48,11 @@ static void waylandOutputGeometryListener(void* data,
static void handleXdgLogicalSize(void* data, [[maybe_unused]] struct zxdg_output_v1* _, int32_t width, [[maybe_unused]] int32_t height) {
WaylandDisplay* display = data;
// The logical size is already transformed, but the mode is not swapped until ffWaylandHandleRotation()
int32_t modeWidth = display->transform & WL_OUTPUT_TRANSFORM_90 ? display->height : display->width;
// Seems the values are only useful when ractional scale is enabled
if (width < display->width) {
display->dpi = (uint32_t) (display->width * 96 / width);
if (width < modeWidth) {
display->dpi = (uint32_t) (modeWidth * 96 / width);
}
}
@@ -391,7 +391,7 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) {
}
// We successfully connected to wayland and detected the display.
// So we can set set the session type to wayland.
// So we can set the session type to wayland.
// This is used as an indicator that we are running wayland by the x11 backends.
ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND);
return nullptr;
+1 -1
View File
@@ -341,7 +341,7 @@ bool ffGPUDetectTypeByVendorAndName(FFGPUResult* gpu) {
} else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL) {
// 0000:00:02.0 is reserved for Intel integrated graphics
gpu->type = gpu->deviceId == ffGPUPciAddr2Id(0, 0, 2, 0) ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE;
} else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_VMWARE || gpu->vendor.chars == FF_GPU_VENDOR_NAME_PARALLELS) {
} else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_VMWARE || gpu->vendor.chars == FF_GPU_VENDOR_NAME_PARALLELS || gpu->vendor.chars == FF_GPU_VENDOR_NAME_REDHAT) {
// Virtualized GPUs
gpu->type = FF_GPU_TYPE_INTEGRATED;
}
+65 -4
View File
@@ -1,12 +1,10 @@
#include "detection/gpu/gpu.h"
#include "common/debug.h"
#include "common/io.h"
#include "common/FFstrbuf.h"
#include "common/properties.h"
#include "common/strutil.h"
#include "modules/gpu/option.h"
#include <inttypes.h>
#include <stdint.h>
static bool detectDriverFromSysfs(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* buffer, [[maybe_unused]] const char* drmKey) {
uint32_t pciDirLength = pciDir->length;
@@ -337,6 +335,64 @@ static inline uint16_t pcieWidthToLanes(const FFstrbuf* buffer) {
return FF_GPU_PCIE_SPEED_UNSET;
}
static bool parseModelName(const char* data, const char* key, bool stripVendorPrefix, FFstrbuf* name) {
ffStrbufClear(name);
if (!ffParsePropLines(data, key, name) || !name->length) {
return false;
}
ffStrbufDecodeHexEscapeSequences(name); // udev hex-escapes characters that are not allowed in property values
ffStrbufTrimSpace(name);
// hwdb names have the form `Codename [Marketing Name]`. Reduce them exactly like
// ffGPUParsePciIdsFile() does, so displaying the name does not change with the source.
if (name->length > 1 && name->chars[name->length - 1] == ']') {
const char* openingBracket = memrchr(name->chars, '[', name->length - 1);
if (openingBracket) {
ffStrbufSubstrAfter(name, (uint32_t) (openingBracket - name->chars));
ffStrbufSubstrBefore(name, name->length - 1);
}
}
// The driver repeats the vendor in its own model line. Dropping it keeps the pci.ids
// shape and lets ffGPUDetectTypeByVendorAndName() see the product family prefix.
if (stripVendorPrefix && ffStrbufStartsWithIgnCaseS(name, "NVIDIA ")) {
ffStrbufSubstrAfter(name, (uint32_t) strlen("NVIDIA ") - 1); // excludes the index itself
}
ffStrbufTrimSpace(name);
return name->length > 0;
}
static bool nameFromFile(const FFstrbuf* path, const char* key, bool stripVendorPrefix, FFstrbuf* buffer, FFstrbuf* name) {
if (!ffReadFileBuffer(path->chars, buffer) || !parseModelName(buffer->chars, key, stripVendorPrefix, name)) {
return false;
}
FF_DEBUG("GPU name resolved from %s: %s", path->chars, name->chars);
return true;
}
// The driver and udev already resolved the model name at probe / boot time. Only `Model:` is
// consumed: the sibling `power` file goes through the RM and can wake a GPU suspended in runtime D3.
static bool resolveNameFromFiles(const char* pciPath, bool isNvidia, FFstrbuf* buffer, FFstrbuf* name) {
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateA(128);
if (isNvidia) {
ffStrbufSetF(&path, "/proc/driver/nvidia/gpus/%s/information", pciPath);
if (nameFromFile(&path, "Model:", true, buffer, name)) {
return true;
}
}
ffStrbufSetF(&path, "/run/udev/data/+pci:%s", pciPath);
if (nameFromFile(&path, "E:ID_MODEL_FROM_DATABASE=", false, buffer, name)) {
return true;
}
ffStrbufClear(name);
return false;
}
static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf* buffer, FFstrbuf* deviceDir, const char* drmKey) {
const uint32_t drmDirPathLength = deviceDir->length;
uint32_t vendorId, deviceId, subVendorId, subDeviceId;
@@ -465,7 +521,12 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf
}
if (gpu->name.length == 0) {
ffGPUFillVendorAndName(subclassId, (uint16_t) vendorId, (uint16_t) deviceId, gpu);
// Stop at the first hit; unknown vendors are left to pci.ids, which also fills in `vendor`.
bool resolved = gpu->vendor.length > 0 &&
resolveNameFromFiles(pPciPath, gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA, buffer, &gpu->name);
if (!resolved) {
ffGPUFillVendorAndName(subclassId, (uint16_t) vendorId, (uint16_t) deviceId, gpu);
}
}
ffGPUDetectTypeByVendorAndName(gpu);
+3 -1
View File
@@ -39,8 +39,10 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) {
// In some old system, /sbin/init is a symlink
char buf[PATH_MAX];
if (realpath(result->exe.chars, buf)) {
char baseBuf[PATH_MAX];
ffStrCopy(baseBuf, buf, sizeof(baseBuf));
ffStrbufSetS(&result->name, basename(baseBuf));
ffStrbufSetS(&result->exe, buf);
ffStrbufSetS(&result->name, basename(result->exe.chars));
}
}
+27
View File
@@ -0,0 +1,27 @@
#include "os.h"
#include "common/properties.h"
#include "common/strutil.h"
void ffDetectOSImpl(FFOSResult* result) {
ffParsePropFileValues(
#ifdef FF_CUSTOM_OS_RELEASE_PATH
FF_STR(FF_CUSTOM_OS_RELEASE_PATH)
#else
"/etc/os-release"
#endif
,
11,
(FFpropquery[]){
{ "PRETTY_NAME =", &result->prettyName },
{ "NAME =", &result->name },
{ "ID =", &result->id },
{ "ID_LIKE =", &result->idLike },
{ "VARIANT =", &result->variant },
{ "VARIANT_ID =", &result->variantID },
{ "VERSION =", &result->version },
{ "VERSION_ID =", &result->versionID },
{ "VERSION_CODENAME =", &result->codename },
{ "CODENAME =", &result->codename },
{ "BUILD_ID =", &result->buildID },
});
}
-2
View File
@@ -403,7 +403,6 @@ static void detectOS(FFOSResult* os) {
void ffDetectOSImpl(FFOSResult* os) {
detectOS(os);
#if __linux__ || __GNU__
if (ffStrbufEqualS(&os->id, "ubuntu")) {
if (!getUbuntuFlavour(os)) {
if (!ffStrbufEndsWithS(&os->prettyName, " (development branch)")) {
@@ -426,5 +425,4 @@ void ffDetectOSImpl(FFOSResult* os) {
} else if (ffStrbufEqualS(&os->id, "astra")) {
detectAstraVersion(os);
}
#endif
}
+18
View File
@@ -2,6 +2,21 @@
#include "modules/physicaldisk/option.h"
#define FF_PHYSICALDISK_TEMP_UNSET (-DBL_MAX)
#define FF_PHYSICALDISK_PERCENT_UNSET UINT8_MAX
// Bits 0-5 match NVMe Critical Warning
typedef enum FFPhysicalDiskWarning: uint8_t {
FF_PHYSICALDISK_WARNING_NONE = 0,
FF_PHYSICALDISK_WARNING_SPARE = 1 << 0,
FF_PHYSICALDISK_WARNING_TEMPERATURE = 1 << 1,
FF_PHYSICALDISK_WARNING_RELIABILITY = 1 << 2,
FF_PHYSICALDISK_WARNING_READONLY = 1 << 3,
FF_PHYSICALDISK_WARNING_BACKUP = 1 << 4,
FF_PHYSICALDISK_WARNING_PMR_READONLY = 1 << 5,
FF_PHYSICALDISK_WARNING_FAILING = 1 << 6,
FF_PHYSICALDISK_WARNING_UNSET = UINT8_MAX,
} FFPhysicalDiskWarning;
static_assert(sizeof(FFPhysicalDiskWarning) == sizeof(uint8_t), "");
typedef struct FFPhysicalDiskResult {
FFstrbuf name;
@@ -12,6 +27,9 @@ typedef struct FFPhysicalDiskResult {
FFPhysicalDiskType type;
uint64_t size;
double temperature;
uint8_t percentUsed;
uint8_t availableSpare;
FFPhysicalDiskWarning criticalWarning;
} FFPhysicalDiskResult;
const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options);
@@ -8,20 +8,19 @@
#include <IOKit/storage/IOBlockStorageDriver.h>
#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
#include <IOKit/storage/IOStorageProtocolCharacteristics.h>
#include <IOKit/storage/ata/ATASMARTLib.h>
#ifdef MAC_OS_X_VERSION_10_15
#include <IOKit/storage/nvme/NVMeSMARTLibExternal.h>
#endif
#ifdef MAC_OS_X_VERSION_10_15
static inline void wrapIoDestroyPlugInInterface(IOCFPlugInInterface*** pluginInf) {
assert(pluginInf);
if (*pluginInf) {
IODestroyPlugInInterface(*pluginInf);
}
}
#endif
static const char* detectSsdTemp(io_service_t entryPhysical, double* temp) {
static const char* detectNvmeSmart(io_service_t entryPhysical, FFPhysicalDiskResult* device, FFPhysicalDiskOptions* options) {
#ifdef MAC_OS_X_VERSION_10_15
[[gnu::cleanup(wrapIoDestroyPlugInInterface)]] IOCFPlugInInterface** pluginInf = nullptr;
int32_t score;
@@ -39,7 +38,14 @@ static const char* detectSsdTemp(io_service_t entryPhysical, double* temp) {
NVMeSMARTData smartData;
const char* error = nullptr;
if ((*smartInf)->SMARTReadData(smartInf, &smartData) == kIOReturnSuccess) {
*temp = smartData.TEMPERATURE - 273;
if (options->temp) {
device->temperature = smartData.TEMPERATURE - 273;
}
if (options->health) {
device->percentUsed = (uint8_t) (smartData.PERCENTAGE_USED > 254 ? 254 : smartData.PERCENTAGE_USED);
device->availableSpare = (uint8_t) (smartData.AVAILABLE_SPARE > 100 ? 100 : smartData.AVAILABLE_SPARE);
device->criticalWarning = (FFPhysicalDiskWarning) (smartData.CRITICAL_WARNING & 0x3F);
}
} else {
error = "SMARTReadData() failed";
}
@@ -47,11 +53,43 @@ static const char* detectSsdTemp(io_service_t entryPhysical, double* temp) {
(*pluginInf)->Release(smartInf);
return error;
#else
FF_DEBUG("SSD temperature detection needs macOS 10.15 or newer");
FF_DEBUG("NVMe SMART detection needs macOS 10.15 or newer");
return "No support for old MacOS version";
#endif
}
static const char* detectAtaSmart(io_service_t entryPhysical, FFPhysicalDiskResult* device) {
[[gnu::cleanup(wrapIoDestroyPlugInInterface)]] IOCFPlugInInterface** pluginInf = nullptr;
int32_t score;
if (IOCreatePlugInInterfaceForService(entryPhysical, kIOATASMARTUserClientTypeID, kIOCFPlugInInterfaceID, &pluginInf, &score) != kIOReturnSuccess) {
FF_DEBUG("IOCreatePlugInInterfaceForService(kIOATASMARTUserClientTypeID) failed");
return "IOCreatePlugInInterfaceForService() failed";
}
IOATASMARTInterface** smartInf = nullptr;
if ((*pluginInf)->QueryInterface(pluginInf, CFUUIDGetUUIDBytes(kIOATASMARTInterfaceID), (LPVOID) &smartInf) != kIOReturnSuccess) {
FF_DEBUG("QueryInterface(kIOATASMARTInterfaceID) failed");
return "QueryInterface() failed";
}
Boolean exceeded = false;
const char* error = nullptr;
if ((*smartInf)->SMARTReturnStatus(smartInf, &exceeded) == kIOReturnSuccess) {
if (device->criticalWarning == FF_PHYSICALDISK_WARNING_UNSET) {
device->criticalWarning = FF_PHYSICALDISK_WARNING_NONE;
}
if (exceeded) {
device->criticalWarning |= FF_PHYSICALDISK_WARNING_FAILING;
}
} else {
FF_DEBUG("SMARTReturnStatus() failed");
error = "SMARTReturnStatus() failed";
}
(*pluginInf)->Release(smartInf);
return error;
}
const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) {
FF_IOOBJECT_AUTO_RELEASE io_iterator_t iterator = 0;
if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching(kIOBlockStorageDriverClass), &iterator) != KERN_SUCCESS) {
@@ -144,6 +182,9 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options)
device->type = type;
device->size = size;
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
if (entryMedia != IO_OBJECT_NULL) {
FF_CFTYPE_AUTO_RELEASE CFBooleanRef removable = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaRemovableKey), nullptr, kNilOptions);
@@ -183,13 +224,20 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options)
}
#ifdef MAC_OS_X_VERSION_10_15
if (!(device->type & FF_PHYSICALDISK_TYPE_VIRTUAL) && options->temp) {
if (!(device->type & FF_PHYSICALDISK_TYPE_VIRTUAL) && (options->temp || options->health)) {
FF_CFTYPE_AUTO_RELEASE CFBooleanRef nvmeSMARTCapable = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyNVMeSMARTCapableKey), nullptr, kNilOptions);
if (nvmeSMARTCapable && CFBooleanGetValue(nvmeSMARTCapable)) {
detectSsdTemp(entryPhysical, &device->temperature);
detectNvmeSmart(entryPhysical, device, options);
}
}
#endif
if (!(device->type & FF_PHYSICALDISK_TYPE_VIRTUAL) && options->health) {
FF_CFTYPE_AUTO_RELEASE CFBooleanRef ataSMARTCapable = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertySMARTCapableKey), nullptr, kNilOptions);
if (ataSMARTCapable && CFBooleanGetValue(ataSMARTCapable)) {
detectAtaSmart(entryPhysical, device);
}
}
}
return nullptr;
@@ -90,6 +90,9 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options)
ffStrbufInitMove(&device->name, &name);
device->size = size;
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
switch (snapIter->device_type & DEVSTAT_TYPE_IF_MASK) {
case DEVSTAT_TYPE_IF_SCSI:
@@ -71,6 +71,9 @@ static const char* searchRawDeviceFile(FFstrbuf* path, const char* diskType, FFl
ffStrbufInit(&device->revision);
ffStrbufInitS(&device->interconnect, diskType);
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
device->type = type |
(geometry.read_only ? FF_PHYSICALDISK_TYPE_READONLY : FF_PHYSICALDISK_TYPE_READWRITE) |
(geometry.removable ? FF_PHYSICALDISK_TYPE_REMOVABLE : FF_PHYSICALDISK_TYPE_FIXED);
@@ -9,6 +9,210 @@
#include <unistd.h>
#include <fcntl.h>
#ifdef FF_HAVE_DBUS
#include "common/dbus.h"
#define FF_UDISKS_BUS "org.freedesktop.UDisks2"
#define FF_UDISKS_NVME_CONTROLLER "org.freedesktop.UDisks2.NVMe.Controller"
#define FF_UDISKS_DRIVE_ATA "org.freedesktop.UDisks2.Drive.Ata"
static bool hasUDisks(FFDBusData* dbus) {
DBusMessage* reply = ffDBusGetMethodReply(dbus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", FF_UDISKS_BUS, nullptr);
if (reply == nullptr) {
return false;
}
bool result = false;
DBusMessageIter iter;
if (dbus->lib->ffdbus_message_iter_init(reply, &iter)) {
ffDBusGetBool(dbus, &iter, &result);
}
dbus->lib->ffdbus_message_unref(reply);
return result;
}
static FFPhysicalDiskWarning parseCriticalWarning(FFDBusData* dbus, DBusMessage* reply) {
DBusMessageIter iter;
if (!dbus->lib->ffdbus_message_iter_init(reply, &iter) || dbus->lib->ffdbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT) {
return FF_PHYSICALDISK_WARNING_UNSET;
}
DBusMessageIter arrayIter;
dbus->lib->ffdbus_message_iter_recurse(&iter, &arrayIter);
if (dbus->lib->ffdbus_message_iter_get_arg_type(&arrayIter) != DBUS_TYPE_ARRAY) {
return FF_PHYSICALDISK_WARNING_UNSET;
}
FFPhysicalDiskWarning result = FF_PHYSICALDISK_WARNING_NONE;
DBusMessageIter stringIter;
dbus->lib->ffdbus_message_iter_recurse(&arrayIter, &stringIter);
while (dbus->lib->ffdbus_message_iter_get_arg_type(&stringIter) == DBUS_TYPE_STRING) {
const char* value;
dbus->lib->ffdbus_message_iter_get_basic(&stringIter, &value);
if (ffStrEquals(value, "spare")) {
result |= FF_PHYSICALDISK_WARNING_SPARE;
} else if (ffStrEquals(value, "temperature")) {
result |= FF_PHYSICALDISK_WARNING_TEMPERATURE;
} else if (ffStrEquals(value, "degraded")) {
result |= FF_PHYSICALDISK_WARNING_RELIABILITY;
} else if (ffStrEquals(value, "readonly")) {
result |= FF_PHYSICALDISK_WARNING_READONLY;
} else if (ffStrEquals(value, "volatile_mem")) {
result |= FF_PHYSICALDISK_WARNING_BACKUP;
} else if (ffStrEquals(value, "pmr_readonly")) {
result |= FF_PHYSICALDISK_WARNING_PMR_READONLY;
}
dbus->lib->ffdbus_message_iter_next(&stringIter);
}
return result;
}
static void parseSmartAttributes(FFDBusData* dbus, DBusMessage* reply, FFPhysicalDiskResult* device) {
DBusMessageIter iter;
if (!dbus->lib->ffdbus_message_iter_init(reply, &iter) || dbus->lib->ffdbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) {
return;
}
DBusMessageIter dictIter;
dbus->lib->ffdbus_message_iter_recurse(&iter, &dictIter);
while (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) == DBUS_TYPE_DICT_ENTRY) {
DBusMessageIter entryIter;
dbus->lib->ffdbus_message_iter_recurse(&dictIter, &entryIter);
if (dbus->lib->ffdbus_message_iter_get_arg_type(&entryIter) != DBUS_TYPE_STRING) {
break;
}
const char* key;
dbus->lib->ffdbus_message_iter_get_basic(&entryIter, &key);
dbus->lib->ffdbus_message_iter_next(&entryIter);
uint64_t value;
if (ffStrEquals(key, "percent_used")) {
if (ffDBusGetUint(dbus, &entryIter, &value)) {
device->percentUsed = (uint8_t) (value > 254 ? 254 : value);
}
} else if (ffStrEquals(key, "avail_spare")) {
if (ffDBusGetUint(dbus, &entryIter, &value)) {
device->availableSpare = (uint8_t) (value > 100 ? 100 : value);
}
}
dbus->lib->ffdbus_message_iter_next(&dictIter);
}
}
static void detectNvmeHealth(FFDBusData* dbus, const char* drivePath, FFPhysicalDiskResult* device) {
uint64_t smartUpdated = 0;
if (!ffDBusGetPropertyUint(dbus, FF_UDISKS_BUS, drivePath, FF_UDISKS_NVME_CONTROLLER, "SmartUpdated", &smartUpdated)) {
FF_DEBUG("%s has no NVMe controller interface", drivePath);
return;
}
if (smartUpdated == 0) {
FF_DEBUG("udisks has not collected SMART data of %s yet", drivePath);
return;
}
DBusMessage* reply = ffDBusGetProperty(dbus, FF_UDISKS_BUS, drivePath, FF_UDISKS_NVME_CONTROLLER, "SmartCriticalWarning");
if (reply == nullptr) {
FF_DEBUG("Failed to get SmartCriticalWarning of %s", drivePath);
return;
}
device->criticalWarning = parseCriticalWarning(dbus, reply);
dbus->lib->ffdbus_message_unref(reply);
reply = ffDBusGetMethodReplyEmptyDict(dbus, FF_UDISKS_BUS, drivePath, FF_UDISKS_NVME_CONTROLLER, "SmartGetAttributes");
if (reply == nullptr) {
FF_DEBUG("SmartGetAttributes failed for %s", drivePath);
return;
}
parseSmartAttributes(dbus, reply, device);
dbus->lib->ffdbus_message_unref(reply);
}
static void detectAtaHealth(FFDBusData* dbus, const char* drivePath, FFPhysicalDiskResult* device) {
DBusMessage* reply = ffDBusGetAllProperties(dbus, FF_UDISKS_BUS, drivePath, FF_UDISKS_DRIVE_ATA);
if (reply == nullptr) {
FF_DEBUG("%s has no ATA interface", drivePath);
return;
}
bool smartFailing = false;
uint64_t smartUpdated = 0;
DBusMessageIter iter;
if (dbus->lib->ffdbus_message_iter_init(reply, &iter) && dbus->lib->ffdbus_message_iter_get_arg_type(&iter) == DBUS_TYPE_ARRAY) {
DBusMessageIter dictIter;
dbus->lib->ffdbus_message_iter_recurse(&iter, &dictIter);
while (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) == DBUS_TYPE_DICT_ENTRY) {
DBusMessageIter entryIter;
dbus->lib->ffdbus_message_iter_recurse(&dictIter, &entryIter);
if (dbus->lib->ffdbus_message_iter_get_arg_type(&entryIter) != DBUS_TYPE_STRING) {
break;
}
const char* key;
dbus->lib->ffdbus_message_iter_get_basic(&entryIter, &key);
dbus->lib->ffdbus_message_iter_next(&entryIter);
if (ffStrEquals(key, "SmartUpdated")) {
ffDBusGetUint(dbus, &entryIter, &smartUpdated);
} else if (ffStrEquals(key, "SmartFailing")) {
ffDBusGetBool(dbus, &entryIter, &smartFailing);
}
dbus->lib->ffdbus_message_iter_next(&dictIter);
}
}
dbus->lib->ffdbus_message_unref(reply);
if (smartUpdated == 0) {
FF_DEBUG("udisks has not collected SMART data of %s yet", drivePath);
return;
}
if (device->criticalWarning == FF_PHYSICALDISK_WARNING_UNSET) {
device->criticalWarning = FF_PHYSICALDISK_WARNING_NONE;
}
if (smartFailing) {
device->criticalWarning |= FF_PHYSICALDISK_WARNING_FAILING;
}
}
static void detectHealth(FFlist* result) {
FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {};
const char* error = ffDBusLoadData(DBUS_BUS_SYSTEM, &dbus);
if (error) {
FF_DEBUG("%s", error);
return;
}
if (!hasUDisks(&dbus)) {
FF_DEBUG("udisks2 is not running");
return;
}
FF_LIST_FOR_EACH (FFPhysicalDiskResult, device, *result) {
if (device->type & FF_PHYSICALDISK_TYPE_VIRTUAL) {
continue;
}
char blockPath[128];
snprintf(blockPath, ARRAY_SIZE(blockPath), "/org/freedesktop/UDisks2/block_devices/%s", device->devPath.chars + strlen("/dev/"));
FF_STRBUF_AUTO_DESTROY drivePath = ffStrbufCreate();
if (!ffDBusGetPropertyString(&dbus, FF_UDISKS_BUS, blockPath, "org.freedesktop.UDisks2.Block", "Drive", &drivePath) || drivePath.length <= 1) {
FF_DEBUG("Failed to get udisks drive of %s", device->devPath.chars);
continue;
}
if (ffStrbufStartsWithS(&device->devPath, "/dev/nvme")) {
detectNvmeHealth(&dbus, drivePath.chars, device);
} else {
detectAtaHealth(&dbus, drivePath.chars, device);
}
}
}
#endif
static double detectNvmeTemp(int devfd) {
char pathHwmon[] = "hwmon$/temp1_input";
@@ -107,6 +311,9 @@ static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOption
device->type = type;
device->size = size;
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
bool isVirtio = false;
if (devfd > 0) {
@@ -200,5 +407,11 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options)
}
}
#ifdef FF_HAVE_DBUS
if (options->health) {
detectHealth(result);
}
#endif
return nullptr;
}
@@ -220,6 +220,9 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options)
device->type = type;
device->size = size;
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
FF_DEBUG("Added disk entry: name='%s', devPath='%s', interconnect='%s', size=%llu",
device->name.chars,
device->devPath.chars,
@@ -187,6 +187,9 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options)
device->type = type;
device->size = size;
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
FF_DEBUG("Added disk entry: name='%s', devPath='%s', interconnect='%s', size=%llu",
device->name.chars,
device->devPath.chars,
@@ -51,6 +51,9 @@ static int walkDevTree(di_node_t node, di_minor_t minor, struct FFWalkTreeBundle
ffStrbufInit(&device->revision);
ffStrbufInit(&device->interconnect);
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
device->type = type;
device->size = size;
@@ -8,6 +8,7 @@
#include <windows.h>
#include <winioctl.h>
#include <cfgmgr32.h>
#include <nvme.h>
static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* szDevice, FFlist* result, FFPhysicalDiskOptions* options) {
FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
@@ -214,6 +215,9 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s
device->type = type;
device->size = size;
device->temperature = FF_PHYSICALDISK_TEMP_UNSET;
device->percentUsed = FF_PHYSICALDISK_PERCENT_UNSET;
device->availableSpare = FF_PHYSICALDISK_PERCENT_UNSET;
device->criticalWarning = FF_PHYSICALDISK_WARNING_UNSET;
ffStrbufSetWS(&device->devPath, szDevice);
@@ -299,6 +303,67 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s
device->temperature = stdd.TemperatureInfo[0].Temperature;
}
}
if (options->health && sdd && sdd->BusType == BusTypeNvme) {
alignas(STORAGE_PROPERTY_QUERY) uint8_t buffer[offsetof(STORAGE_PROPERTY_QUERY, AdditionalParameters) + sizeof(STORAGE_PROTOCOL_SPECIFIC_DATA) + sizeof(NVME_HEALTH_INFO_LOG)] = {};
STORAGE_PROPERTY_QUERY* query = (STORAGE_PROPERTY_QUERY*) buffer;
query->PropertyId = StorageDeviceProtocolSpecificProperty;
query->QueryType = PropertyStandardQuery;
*(STORAGE_PROTOCOL_SPECIFIC_DATA*) query->AdditionalParameters = (STORAGE_PROTOCOL_SPECIFIC_DATA) {
.ProtocolType = ProtocolTypeNvme,
.DataType = NVMeDataTypeLogPage,
.ProtocolDataRequestValue = NVME_LOG_PAGE_HEALTH_INFO,
.ProtocolDataOffset = sizeof(STORAGE_PROTOCOL_SPECIFIC_DATA),
.ProtocolDataLength = sizeof(NVME_HEALTH_INFO_LOG),
};
if (DeviceIoControl(
hDevice,
IOCTL_STORAGE_QUERY_PROPERTY,
buffer,
sizeof(buffer),
buffer,
sizeof(buffer),
&retSize,
nullptr)) {
const STORAGE_PROTOCOL_DATA_DESCRIPTOR* spdd = (const STORAGE_PROTOCOL_DATA_DESCRIPTOR*) buffer;
if (spdd->ProtocolSpecificData.ProtocolDataOffset == sizeof(STORAGE_PROTOCOL_SPECIFIC_DATA) &&
spdd->ProtocolSpecificData.ProtocolDataLength >= sizeof(NVME_HEALTH_INFO_LOG) &&
retSize == sizeof(buffer)) {
const NVME_HEALTH_INFO_LOG* log = (const NVME_HEALTH_INFO_LOG*) ((const uint8_t*) &spdd->ProtocolSpecificData + sizeof(STORAGE_PROTOCOL_SPECIFIC_DATA));
device->percentUsed = (uint8_t) (log->PercentageUsed > 254 ? 254 : log->PercentageUsed);
device->availableSpare = (uint8_t) (log->AvailableSpare > 100 ? 100 : log->AvailableSpare);
device->criticalWarning = (FFPhysicalDiskWarning) (log->CriticalWarning.AsUchar & 0x3F);
}
} else {
FF_DEBUG("Failed to query NVMe health log: %s", ffDebugWin32Error(GetLastError()));
}
}
}
if (options->health && sdd && !(device->type & FF_PHYSICALDISK_TYPE_VIRTUAL) && (sdd->BusType == BusTypeAta || sdd->BusType == BusTypeSata)) {
STORAGE_PREDICT_FAILURE spf = {};
if (DeviceIoControl(
hDevice,
IOCTL_STORAGE_PREDICT_FAILURE,
nullptr,
0,
&spf,
sizeof(spf),
&retSize,
nullptr)) {
if (retSize >= sizeof(spf)) {
if (device->criticalWarning == FF_PHYSICALDISK_WARNING_UNSET) {
device->criticalWarning = FF_PHYSICALDISK_WARNING_NONE;
}
if (spf.PredictFailure) {
device->criticalWarning |= FF_PHYSICALDISK_WARNING_FAILING;
}
} else {
FF_DEBUG("ATA failure prediction reply too short: %u bytes", (unsigned) retSize);
}
} else {
FF_DEBUG("Failed to query ATA failure prediction: %s", ffDebugWin32Error(GetLastError()));
}
}
return nullptr;
@@ -1,244 +1,225 @@
#include "physicalmemory.h"
#include "common/debug.h"
#include "common/endian.h"
#include "common/io.h"
#include "common/smbios.h"
#include "common/strutil.h"
// 7.18
typedef struct [[gnu::packed]] FFSmbiosMemoryDevice {
FFSmbiosHeader Header;
// systemd >= 248 decodes SMBIOS Type 16 / 17 into udev properties of the `dmi:id` device
// (see systemd's src/udev/dmi_memory_id/dmi_memory_id.c). The database is world readable,
// while /sys/firmware/dmi/tables/DMI and /dev/mem are root-only, so try it first.
#define FF_UDEV_DMI_ID_DB "/run/udev/data/+dmi:id"
#define FF_UDEV_MEMORY_DEVICE_PREFIX "E:MEMORY_DEVICE_"
#define FF_UDEV_MAX_MEMORY_DEVICES 256
// 2.1+
uint16_t PhysicalMemoryArrayHandle; // varies
uint16_t MemoryErrorInformationHandle; // varies
uint16_t TotalWidth; // varies
uint16_t DataWidth; // varies
uint16_t Size; // varies
uint8_t FormFactor; // enum
uint8_t DeviceSet; // varies
uint8_t DeviceLocator; // string
uint8_t BankLocator; // string
uint8_t MemoryType; // enum
uint16_t TypeDetail; // bit field
static void ffUdevResultAdd(FFlist* result) {
*FF_LIST_ADD(FFPhysicalMemoryResult, *result) = (FFPhysicalMemoryResult){
// Doubles as parse-time state: absent PRESENT / SIZE means "present, unknown
// size", so it starts true and is only ever cleared by PRESENT=0 or SIZE=0.
.installed = true,
.type = ffStrbufCreate(),
.formFactor = ffStrbufCreate(),
.locator = ffStrbufCreate(),
.partNumber = ffStrbufCreate(),
.vendor = ffStrbufCreate(),
.serial = ffStrbufCreate(),
};
}
// 2.3+
uint16_t Speed; // varies
uint8_t Manufacturer; // string
uint8_t SerialNumber; // string
uint8_t AssetTag; // string
uint8_t PartNumber; // string
static void ffUdevResultDestroy(FFPhysicalMemoryResult* device) {
ffStrbufDestroy(&device->type);
ffStrbufDestroy(&device->formFactor);
ffStrbufDestroy(&device->locator);
ffStrbufDestroy(&device->partNumber);
ffStrbufDestroy(&device->vendor);
ffStrbufDestroy(&device->serial);
}
// 2.6+
uint8_t Attributes; // varies
// udev hex-escapes characters that are not allowed in property values (\xHH).
// Also drop the placeholder strings ("Unknown", "0x0000...", "<OUT OF SPEC>", ...).
static void ffUdevSetString(FFstrbuf* strbuf, const char* value) {
ffStrbufSetS(strbuf, value);
ffStrbufDecodeHexEscapeSequences(strbuf);
// Older systemd versions print an empty value, newer ones "<OUT OF SPEC>".
if (ffStrbufStartsWithS(strbuf, "<OUT OF SPEC>")) {
ffStrbufClear(strbuf);
}
ffCleanUpSmbiosValue(strbuf);
}
// 2.7+
uint32_t ExtendedSize; // varies
uint16_t ConfiguredMemorySpeed; // varies
// `locator` is the "bank/device" join, but the two properties arrive in no guaranteed
// order. Prepending the bank and appending the device yields the same result either way.
// systemd emits each property at most once per device.
static void ffUdevAppendLocator(FFPhysicalMemoryResult* device, const char* value, bool bank) {
FF_STRBUF_AUTO_DESTROY part = ffStrbufCreate();
ffUdevSetString(&part, value);
if (part.length == 0) {
return;
}
// 2.8+
uint16_t MinimumVoltage; // varies
uint16_t MaximumVoltage; // varies
uint16_t ConfiguredVoltage; // varies
if (device->locator.length > 0) {
if (bank) {
ffStrbufPrependC(&device->locator, '/');
} else {
ffStrbufAppendC(&device->locator, '/');
}
}
if (bank) {
ffStrbufPrepend(&device->locator, &part);
} else {
ffStrbufAppend(&device->locator, &part);
}
}
// 3.2+
uint8_t MemoryTechnology; // varies
uint16_t MemoryOperatingMode; // bit field
uint8_t FirmwareVersion; // string
uint16_t ModuleManufacturerID; // varies
uint16_t ModuleProductID; // varies
uint16_t MemorySubsystemControllerManufacturerID; // vaies
uint16_t MemorySubsystemControllerProductID; // varies
uint64_t NonVolatileSize; // varies
uint64_t VolatileSize; // varies
uint64_t CacheSize; // varies
uint64_t LogicalSize; // varies
// Splits a line like "E:MEMORY_DEVICE_0_SIZE=4294967296" in place. Returns the field
// name, or nullptr when the line is unrelated or has an out-of-range device index.
// The mere presence of such a line means the udev database describes the memory devices
// completely, whether or not its field is recognized or its value is a placeholder.
static const char* ffUdevParseHeader(char* line, uint32_t* index, const char** value) {
if (!ffStrStartsWith(line, FF_UDEV_MEMORY_DEVICE_PREFIX)) {
return nullptr;
}
// 3.3+
uint32_t ExtendedSpeed; // varies
uint32_t ExtendedConfiguredSpeed; // varies
char* eq = strchr(line, '=');
if (!eq) {
return nullptr;
}
// 3.7+
uint16_t Pmic0ManufacturerID; // varies
uint16_t Pmic0RevisionNumber; // varies
uint16_t RcdManufacturerID; // varies
uint16_t RcdRevisionNumber; // varies
} FFSmbiosMemoryDevice;
const char* p = line + sizeof(FF_UDEV_MEMORY_DEVICE_PREFIX) - 1;
char* end = nullptr;
unsigned long n = strtoul(p, &end, 10);
if (end == p || *end != '_' || n >= FF_UDEV_MAX_MEMORY_DEVICES) {
return nullptr;
}
static_assert(offsetof(FFSmbiosMemoryDevice, RcdRevisionNumber) == 0x62,
"FFSmbiosMemoryDevice: Wrong struct alignment");
*eq = '\0';
*index = (uint32_t) n;
*value = eq + 1;
return end + 1;
}
// The udev database is authoritative: as soon as it contains any MEMORY_DEVICE_*
// property, the set of memory devices it describes is considered complete and the
// caller must not fall back to SMBIOS -- even when every slot is empty, all values
// are placeholders, or showEmptySlots filters everything out of `result`.
static bool ffDetectPhysicalMemoryFromUdev(FFPhysicalMemoryOptions* options, FFlist* result) {
FF_STRBUF_AUTO_DESTROY db = ffStrbufCreate();
if (!ffReadFileBuffer(FF_UDEV_DMI_ID_DB, &db)) {
FF_DEBUG("Failed to read %s", FF_UDEV_DMI_ID_DB);
return false;
}
// The udev index addresses `result` directly: MEMORY_DEVICE_n_* maps to entry
// `base + n`. Entries are therefore naturally sorted and can be updated in place,
// without a staging list, a comparator or any result copying. FFstrbuf holds no
// pointer into itself, so FF_LIST_ADD may relocate existing entries freely.
// Sparse indices leave placeholder entries behind; they are removed below.
bool seen[FF_UDEV_MAX_MEMORY_DEVICES] = { false };
uint16_t totalWidths[FF_UDEV_MAX_MEMORY_DEVICES] = { 0 };
uint16_t dataWidths[FF_UDEV_MAX_MEMORY_DEVICES] = { 0 };
const uint32_t base = result->length;
bool found = false;
char* line = nullptr;
size_t len = 0;
while (ffStrbufGetline(&line, &len, &db)) {
// `len` must stay intact: the next ffStrbufGetline call advances the cursor by it.
if (len > 0 && line[len - 1] == '\r') {
line[len - 1] = '\0';
}
uint32_t index;
const char* value;
const char* field = ffUdevParseHeader(line, &index, &value);
if (!field) {
continue;
}
while (base + index >= result->length) {
ffUdevResultAdd(result);
}
found = true;
seen[index] = true;
FFPhysicalMemoryResult* device = FF_LIST_GET(FFPhysicalMemoryResult, *result, base + index);
if (ffStrEquals(field, "SIZE")) {
device->size = strtoull(value, nullptr, 10);
if (device->size == 0) {
device->installed = false;
}
} else if (ffStrEquals(field, "PRESENT")) {
if (strtoul(value, nullptr, 10) == 0) {
device->installed = false;
}
} else if (ffStrEquals(field, "TOTAL_WIDTH")) {
totalWidths[index] = (uint16_t) strtoul(value, nullptr, 10);
} else if (ffStrEquals(field, "DATA_WIDTH")) {
dataWidths[index] = (uint16_t) strtoul(value, nullptr, 10);
} else if (ffStrEquals(field, "SPEED_MTS")) {
device->maxSpeed = (uint32_t) strtoul(value, nullptr, 10);
} else if (ffStrEquals(field, "CONFIGURED_SPEED_MTS")) {
device->runningSpeed = (uint32_t) strtoul(value, nullptr, 10);
} else if (ffStrEquals(field, "FORM_FACTOR")) {
ffUdevSetString(&device->formFactor, value);
} else if (ffStrEquals(field, "BANK_LOCATOR")) {
ffUdevAppendLocator(device, value, true);
} else if (ffStrEquals(field, "LOCATOR")) {
ffUdevAppendLocator(device, value, false);
} else if (ffStrEquals(field, "TYPE")) {
ffUdevSetString(&device->type, value);
} else if (ffStrEquals(field, "MANUFACTURER")) {
ffUdevSetString(&device->vendor, value);
} else if (ffStrEquals(field, "SERIAL_NUMBER")) {
ffUdevSetString(&device->serial, value);
} else if (ffStrEquals(field, "PART_NUMBER")) {
ffUdevSetString(&device->partNumber, value);
}
}
if (!found) {
FF_DEBUG("No MEMORY_DEVICE_* properties in %s", FF_UDEV_DMI_ID_DB);
return false;
}
// Finalize and drop sparse / empty slots. `i` tracks the current list position
// while `index` tracks the original udev index, which survives the removals.
uint32_t i = base;
for (uint32_t index = 0; i < result->length; ++index) {
FFPhysicalMemoryResult* device = FF_LIST_GET(FFPhysicalMemoryResult, *result, i);
if (!seen[index] || (!device->installed && !options->showEmptySlots)) {
ffUdevResultDestroy(device);
FF_LIST_REMOVE_AT(FFPhysicalMemoryResult, *result, i);
continue;
}
device->ecc = totalWidths[index] > 0 && dataWidths[index] > 0 &&
totalWidths[index] > dataWidths[index];
if (!device->installed) {
device->maxSpeed = device->runningSpeed = 0;
ffStrbufSetStatic(&device->type, "Empty");
ffStrbufClear(&device->vendor);
ffStrbufClear(&device->serial);
ffStrbufClear(&device->partNumber);
} else {
if (device->type.length == 0) {
ffStrbufSetStatic(&device->type, "Unknown");
}
FFPhysicalMemoryUpdateVendorString(device);
}
++i;
}
return true;
}
const char* ffDetectPhysicalMemory(FFPhysicalMemoryOptions* options, FFlist* result) {
const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable();
if (!smbiosTable) {
FF_DEBUG("Failed to get SMBIOS data");
return "Failed to get SMBIOS data";
if (ffDetectPhysicalMemoryFromUdev(options, result)) {
FF_DEBUG("Physical memory detected from %s", FF_UDEV_DMI_ID_DB);
return nullptr;
}
const FFSmbiosMemoryDevice* data = (const FFSmbiosMemoryDevice*) (*smbiosTable)[FF_SMBIOS_TYPE_MEMORY_DEVICE];
if (!data) {
FF_DEBUG("Memory device is not found in SMBIOS data");
return "Memory device is not found in SMBIOS data";
}
const FFSmbiosMemoryDevice* endOfTable = (const FFSmbiosMemoryDevice*) (*smbiosTable)[FF_SMBIOS_TYPE_END_OF_TABLE];
for (; data != endOfTable; data = (const FFSmbiosMemoryDevice*) ffSmbiosNextEntry(&data->Header)) {
if (data->Header.Type != FF_SMBIOS_TYPE_MEMORY_DEVICE) {
continue;
}
const char* strings = (const char*) data + data->Header.Length;
uint16_t size = FF_READ_LE(data->Size);
bool installed = size != 0;
if (!installed && !options->showEmptySlots) {
continue;
}
FFPhysicalMemoryResult* device = FF_LIST_ADD(FFPhysicalMemoryResult, *result);
ffStrbufInit(&device->type);
ffStrbufInit(&device->formFactor);
ffStrbufInit(&device->locator);
ffStrbufInit(&device->vendor);
ffStrbufInit(&device->serial);
ffStrbufInit(&device->partNumber);
device->size = 0;
device->maxSpeed = 0;
device->runningSpeed = 0;
device->installed = installed;
device->ecc = false;
uint16_t totalWidth = FF_READ_LE(data->TotalWidth);
uint16_t dataWidth = FF_READ_LE(data->DataWidth);
if (installed && totalWidth != 0xFFFF && dataWidth != 0xFFFF) {
device->ecc = totalWidth > dataWidth;
}
if (installed && size != 0xFFFF) {
if (size == 0x7FFF) {
device->size = (FF_READ_LE(data->ExtendedSize) & ~(1ULL << 31)) * 1024ULL * 1024ULL;
} else if (size & (1 << 15)) {
// in kB
device->size = (size & ~(1ULL << 15)) * 1024ULL;
} else {
// in MB
device->size = size * 1024ULL * 1024ULL;
}
}
// https://github.com/fastfetch-cli/fastfetch/issues/1051#issuecomment-2206687345
const char* lbank = ffSmbiosLocateString(strings, data->BankLocator);
const char* ldevice = ffSmbiosLocateString(strings, data->DeviceLocator);
if (lbank && ldevice) {
ffStrbufSetF(&device->locator, "%s/%s", lbank, ldevice);
} else if (lbank) {
ffStrbufSetS(&device->locator, lbank);
} else if (ldevice) {
ffStrbufSetS(&device->locator, ldevice);
}
const char* formFactorNames[] = {
nullptr, // 0x00 (Placeholder for indexing)
"Other", // 0x01
"Unknown", // 0x02
"SIMM", // 0x03
"SIP", // 0x04
"Chip", // 0x05
"DIP", // 0x06
"ZIP", // 0x07
"Proprietary Card", // 0x08
"DIMM", // 0x09
"TSOP", // 0x0A
"Row of chips", // 0x0B
"RIMM", // 0x0C
"SODIMM", // 0x0D
"SRIMM", // 0x0E
"FBDIMM", // 0x0F
"Die", // 0x10
"CAMM", // 0x11
"CUDIMM", // 0x12
"CSODIMM", // 0x13
};
if (data->FormFactor > 0 && data->FormFactor < ARRAY_SIZE(formFactorNames)) {
ffStrbufSetS(&device->formFactor, formFactorNames[data->FormFactor]);
} else {
ffStrbufSetF(&device->formFactor, "Unknown (%d)", (int) data->FormFactor);
}
const char* memoryTypeNames[] = {
nullptr, // 0x00 (Placeholder for indexing)
"Other", // 0x01
"Unknown", // 0x02
"DRAM", // 0x03
"EDRAM", // 0x04
"VRAM", // 0x05
"SRAM", // 0x06
"RAM", // 0x07
"ROM", // 0x08
"FLASH", // 0x09
"EEPROM", // 0x0A
"FEPROM", // 0x0B
"EPROM", // 0x0C
"CDRAM", // 0x0D
"3DRAM", // 0x0E
"SDRAM", // 0x0F
"SGRAM", // 0x10
"RDRAM", // 0x11
"DDR", // 0x12
"DDR2", // 0x13
"DDR2 FB-DIMM", // 0x14
"Reserved", // 0x15
"Reserved", // 0x16
"Reserved", // 0x17
"DDR3", // 0x18
"FBD2", // 0x19
"DDR4", // 0x1A
"LPDDR", // 0x1B
"LPDDR2", // 0x1C
"LPDDR3", // 0x1D
"LPDDR4", // 0x1E
"Logical non-volatile device", // 0x1F
"HBM", // 0x20
"HBM2", // 0x21
"DDR5", // 0x22
"LPDDR5", // 0x23
"HBM3", // 0x24
"MRDIMM", // 0x25
};
if (!installed) {
ffStrbufSetStatic(&device->type, "Empty");
} else if (data->MemoryType > 0 && data->MemoryType < ARRAY_SIZE(memoryTypeNames)) {
ffStrbufSetStatic(&device->type, memoryTypeNames[data->MemoryType]);
} else {
ffStrbufSetF(&device->type, "Unknown (%d)", (int) data->MemoryType);
}
if (installed && data->Header.Length > offsetof(FFSmbiosMemoryDevice, Speed)) // 2.3+
{
uint16_t speed = FF_READ_LE(data->Speed);
if (speed) {
device->maxSpeed = speed == 0xFFFF ? FF_READ_LE(data->ExtendedSpeed) : speed;
}
ffStrbufSetStatic(&device->vendor, ffSmbiosLocateString(strings, data->Manufacturer));
ffCleanUpSmbiosValue(&device->vendor);
FFPhysicalMemoryUpdateVendorString(device);
ffStrbufSetStatic(&device->serial, ffSmbiosLocateString(strings, data->SerialNumber));
ffCleanUpSmbiosValue(&device->serial);
ffStrbufSetStatic(&device->partNumber, ffSmbiosLocateString(strings, data->PartNumber));
ffCleanUpSmbiosValue(&device->partNumber);
}
if (installed && data->Header.Length > offsetof(FFSmbiosMemoryDevice, ConfiguredMemorySpeed)) // 2.7+
{
uint16_t configuredSpeed = FF_READ_LE(data->ConfiguredMemorySpeed);
if (configuredSpeed) {
device->runningSpeed = configuredSpeed == 0xFFFF
? FF_READ_LE(data->ExtendedConfiguredSpeed)
: configuredSpeed;
}
}
}
return nullptr;
FF_DEBUG("Falling back to reading SMBIOS directly");
// Implemented in physicalmemory_shared.c. On Linux it is used as a fallback when udev data
// is unavailable; on other SMBIOS capable platforms it backs ffDetectPhysicalMemory directly.
const char* ffDetectPhysicalMemoryFromSmbios(FFPhysicalMemoryOptions * options, FFlist * result);
return ffDetectPhysicalMemoryFromSmbios(options, result);
}
@@ -0,0 +1,252 @@
#include "physicalmemory.h"
#include "common/debug.h"
#include "common/endian.h"
#include "common/smbios.h"
// 7.18
typedef struct [[gnu::packed]] FFSmbiosMemoryDevice {
FFSmbiosHeader Header;
// 2.1+
uint16_t PhysicalMemoryArrayHandle; // varies
uint16_t MemoryErrorInformationHandle; // varies
uint16_t TotalWidth; // varies
uint16_t DataWidth; // varies
uint16_t Size; // varies
uint8_t FormFactor; // enum
uint8_t DeviceSet; // varies
uint8_t DeviceLocator; // string
uint8_t BankLocator; // string
uint8_t MemoryType; // enum
uint16_t TypeDetail; // bit field
// 2.3+
uint16_t Speed; // varies
uint8_t Manufacturer; // string
uint8_t SerialNumber; // string
uint8_t AssetTag; // string
uint8_t PartNumber; // string
// 2.6+
uint8_t Attributes; // varies
// 2.7+
uint32_t ExtendedSize; // varies
uint16_t ConfiguredMemorySpeed; // varies
// 2.8+
uint16_t MinimumVoltage; // varies
uint16_t MaximumVoltage; // varies
uint16_t ConfiguredVoltage; // varies
// 3.2+
uint8_t MemoryTechnology; // varies
uint16_t MemoryOperatingMode; // bit field
uint8_t FirmwareVersion; // string
uint16_t ModuleManufacturerID; // varies
uint16_t ModuleProductID; // varies
uint16_t MemorySubsystemControllerManufacturerID; // vaies
uint16_t MemorySubsystemControllerProductID; // varies
uint64_t NonVolatileSize; // varies
uint64_t VolatileSize; // varies
uint64_t CacheSize; // varies
uint64_t LogicalSize; // varies
// 3.3+
uint32_t ExtendedSpeed; // varies
uint32_t ExtendedConfiguredSpeed; // varies
// 3.7+
uint16_t Pmic0ManufacturerID; // varies
uint16_t Pmic0RevisionNumber; // varies
uint16_t RcdManufacturerID; // varies
uint16_t RcdRevisionNumber; // varies
} FFSmbiosMemoryDevice;
static_assert(offsetof(FFSmbiosMemoryDevice, RcdRevisionNumber) == 0x62,
"FFSmbiosMemoryDevice: Wrong struct alignment");
const char* ffDetectPhysicalMemoryFromSmbios(FFPhysicalMemoryOptions* options, FFlist* result) {
const FFSmbiosHeaderTable* smbiosTable = ffGetSmbiosHeaderTable();
if (!smbiosTable) {
FF_DEBUG("Failed to get SMBIOS data");
return "Failed to get SMBIOS data";
}
const FFSmbiosMemoryDevice* data = (const FFSmbiosMemoryDevice*) (*smbiosTable)[FF_SMBIOS_TYPE_MEMORY_DEVICE];
if (!data) {
FF_DEBUG("Memory device is not found in SMBIOS data");
return "Memory device is not found in SMBIOS data";
}
const FFSmbiosMemoryDevice* endOfTable = (const FFSmbiosMemoryDevice*) (*smbiosTable)[FF_SMBIOS_TYPE_END_OF_TABLE];
for (; data != endOfTable; data = (const FFSmbiosMemoryDevice*) ffSmbiosNextEntry(&data->Header)) {
if (data->Header.Type != FF_SMBIOS_TYPE_MEMORY_DEVICE) {
continue;
}
const char* strings = (const char*) data + data->Header.Length;
uint16_t size = FF_READ_LE(data->Size);
bool installed = size != 0;
if (!installed && !options->showEmptySlots) {
continue;
}
FFPhysicalMemoryResult* device = FF_LIST_ADD(FFPhysicalMemoryResult, *result);
*device = (FFPhysicalMemoryResult) {
.installed = installed,
.type = ffStrbufCreate(),
.formFactor = ffStrbufCreate(),
.locator = ffStrbufCreate(),
.partNumber = ffStrbufCreate(),
.vendor = ffStrbufCreate(),
.serial = ffStrbufCreate(),
};
uint16_t totalWidth = FF_READ_LE(data->TotalWidth);
uint16_t dataWidth = FF_READ_LE(data->DataWidth);
if (installed && totalWidth != 0xFFFF && dataWidth != 0xFFFF) {
device->ecc = totalWidth > dataWidth;
}
if (installed && size != 0xFFFF) {
if (size == 0x7FFF) {
device->size = (FF_READ_LE(data->ExtendedSize) & ~(1ULL << 31)) * 1024ULL * 1024ULL;
} else if (size & (1 << 15)) {
// in kB
device->size = (size & ~(1ULL << 15)) * 1024ULL;
} else {
// in MB
device->size = size * 1024ULL * 1024ULL;
}
}
// https://github.com/fastfetch-cli/fastfetch/issues/1051#issuecomment-2206687345
const char* lbank = ffSmbiosLocateString(strings, data->BankLocator);
const char* ldevice = ffSmbiosLocateString(strings, data->DeviceLocator);
if (lbank) {
ffStrbufSetS(&device->locator, lbank);
}
if (lbank && ldevice) {
ffStrbufAppendC(&device->locator, '/');
}
if (ldevice) {
ffStrbufAppendS(&device->locator, ldevice);
}
const char* formFactorNames[] = {
nullptr, // 0x00 (Placeholder for indexing)
"Other", // 0x01
"Unknown", // 0x02
"SIMM", // 0x03
"SIP", // 0x04
"Chip", // 0x05
"DIP", // 0x06
"ZIP", // 0x07
"Proprietary Card", // 0x08
"DIMM", // 0x09
"TSOP", // 0x0A
"Row of chips", // 0x0B
"RIMM", // 0x0C
"SODIMM", // 0x0D
"SRIMM", // 0x0E
"FBDIMM", // 0x0F
"Die", // 0x10
"CAMM", // 0x11
"CUDIMM", // 0x12
"CSODIMM", // 0x13
};
if (data->FormFactor > 0 && data->FormFactor < ARRAY_SIZE(formFactorNames)) {
ffStrbufSetS(&device->formFactor, formFactorNames[data->FormFactor]);
} else {
ffStrbufSetF(&device->formFactor, "Unknown (%d)", (int) data->FormFactor);
}
const char* memoryTypeNames[] = {
nullptr, // 0x00 (Placeholder for indexing)
"Other", // 0x01
"Unknown", // 0x02
"DRAM", // 0x03
"EDRAM", // 0x04
"VRAM", // 0x05
"SRAM", // 0x06
"RAM", // 0x07
"ROM", // 0x08
"FLASH", // 0x09
"EEPROM", // 0x0A
"FEPROM", // 0x0B
"EPROM", // 0x0C
"CDRAM", // 0x0D
"3DRAM", // 0x0E
"SDRAM", // 0x0F
"SGRAM", // 0x10
"RDRAM", // 0x11
"DDR", // 0x12
"DDR2", // 0x13
"DDR2 FB-DIMM", // 0x14
"Reserved", // 0x15
"Reserved", // 0x16
"Reserved", // 0x17
"DDR3", // 0x18
"FBD2", // 0x19
"DDR4", // 0x1A
"LPDDR", // 0x1B
"LPDDR2", // 0x1C
"LPDDR3", // 0x1D
"LPDDR4", // 0x1E
"Logical non-volatile device", // 0x1F
"HBM", // 0x20
"HBM2", // 0x21
"DDR5", // 0x22
"LPDDR5", // 0x23
"HBM3", // 0x24
"MRDIMM", // 0x25
};
if (!installed) {
ffStrbufSetStatic(&device->type, "Empty");
} else if (data->MemoryType > 0 && data->MemoryType < ARRAY_SIZE(memoryTypeNames)) {
ffStrbufSetStatic(&device->type, memoryTypeNames[data->MemoryType]);
} else {
ffStrbufSetF(&device->type, "Unknown (%d)", (int) data->MemoryType);
}
if (installed && data->Header.Length > offsetof(FFSmbiosMemoryDevice, Speed)) // 2.3+
{
uint16_t speed = FF_READ_LE(data->Speed);
if (speed) {
device->maxSpeed = speed == 0xFFFF ? FF_READ_LE(data->ExtendedSpeed) : speed;
}
ffStrbufSetStatic(&device->vendor, ffSmbiosLocateString(strings, data->Manufacturer));
ffCleanUpSmbiosValue(&device->vendor);
FFPhysicalMemoryUpdateVendorString(device);
ffStrbufSetStatic(&device->serial, ffSmbiosLocateString(strings, data->SerialNumber));
ffCleanUpSmbiosValue(&device->serial);
ffStrbufSetStatic(&device->partNumber, ffSmbiosLocateString(strings, data->PartNumber));
ffCleanUpSmbiosValue(&device->partNumber);
}
if (installed && data->Header.Length > offsetof(FFSmbiosMemoryDevice, ConfiguredMemorySpeed)) // 2.7+
{
uint16_t configuredSpeed = FF_READ_LE(data->ConfiguredMemorySpeed);
if (configuredSpeed) {
device->runningSpeed = configuredSpeed == 0xFFFF
? FF_READ_LE(data->ExtendedConfiguredSpeed)
: configuredSpeed;
}
}
}
return nullptr;
}
// On Linux ffDetectPhysicalMemory is provided by physicalmemory_linux.c, which prefers udev
// data and only falls back to the SMBIOS parser above. Every other platform uses it directly.
#ifndef __linux__
const char* ffDetectPhysicalMemory(FFPhysicalMemoryOptions* options, FFlist* result) {
return ffDetectPhysicalMemoryFromSmbios(options, result);
}
#endif
+1 -1
View File
@@ -414,7 +414,7 @@ bool fftsGetShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version)
if (ffStrEqualsIgnCase(exeName, "fish")) {
return getShellVersionFish(exe, version);
}
if (ffStrEqualsIgnCase(exeName, "pwsh")) {
if (ffStrEqualsIgnCase(exeName, "pwsh") || ffStrEqualsIgnCase(exeName, "pwsh-preview")) {
return getShellVersionPwsh(exe, version);
}
if (ffStrEqualsIgnCase(exeName, "csh") || ffStrEqualsIgnCase(exeName, "tcsh")) {
@@ -63,6 +63,8 @@ static uint32_t getShellInfo(FFShellResult* result, uint32_t pid) {
static void setShellInfoDetails(FFShellResult* result) {
if (ffStrbufIgnCaseEqualS(&result->prettyName, "pwsh")) {
ffStrbufSetS(&result->prettyName, "PowerShell");
} else if (ffStrbufIgnCaseEqualS(&result->prettyName, "pwsh-preview")) {
ffStrbufSetS(&result->prettyName, "PowerShell Preview");
} else if (ffStrbufIgnCaseEqualS(&result->prettyName, "powershell")) {
ffStrbufSetS(&result->prettyName, "Windows PowerShell");
} else if (ffStrbufIgnCaseEqualS(&result->prettyName, "powershell_ise")) {
+1 -1
View File
@@ -71,7 +71,7 @@ const char* ffDetectWMPlugin(FFstrbuf* pluginName) {
}
ffStrbufAppendS(pluginName, comm);
pluginName->chars[0] = (char) toupper(pluginName->chars[0]);
pluginName->chars[0] = (char) toupper((unsigned char) pluginName->chars[0]);
break;
}
+2 -2
View File
@@ -117,8 +117,8 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError) {
if (ffRegReadStrbuf(hKey, L"CurrentTheme", &theme, nullptr)) {
ffStrbufSubstrBeforeLastC(&theme, '.');
ffStrbufSubstrAfterLastC(&theme, '\\');
if (isalpha(theme.chars[0])) {
theme.chars[0] = (char) toupper(theme.chars[0]);
if (isalpha((unsigned char) theme.chars[0])) {
theme.chars[0] = (char) toupper((unsigned char) theme.chars[0]);
}
ffStrbufAppend(themeOrError, &theme);
+2 -2
View File
@@ -496,11 +496,11 @@ static const FFlogo C[] = {
.names = { "CuerdOS", "CuerdOS GNU/Linux" },
.lines = FASTFETCH_DATATEXT_LOGO_CUERDOS,
.colors = {
FF_COLOR_FG_YELLOW,
FF_COLOR_FG_GREEN,
FF_COLOR_FG_LIGHT_GREEN,
},
.colorKeys = FF_COLOR_FG_GREEN,
.colorTitle = FF_COLOR_FG_YELLOW,
.colorTitle = FF_COLOR_FG_LIGHT_GREEN,
},
#endif
#ifdef FASTFETCH_DATATEXT_LOGO_CUTEFISHOS
+14 -13
View File
@@ -1,13 +1,14 @@
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣶⣾⣿⣿⣿⣶⣦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣶⣿⣿⣿⡇
⠀⠀⡄⢀⣤⣤⣤⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣤⣤⣤⣤⣤⣄⠀⣿⣿⣿⣿⣿⡇
⠀⠀⡇⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⠁
⠀⠀⣧⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃
⠀⠀⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠋⠁
⠀⠀⠇⠘⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠿⠿⠿⠿⠛⠛⠋⠉
⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⡇
⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉
____________________________________
| Optimizado hasta el último pixel |
************************************
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⣴⣶⣿⣷
⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⣤⣤⣤⣤⣤⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿
⢠⠀⠀⠀⠀⠀⢀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣀⠀⠀⠀⠀⣀⣠⣤⣤⣸⣿⣿⣿⣿⣿⡏
⢸⠀⢠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁
⢸⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁⠀
⢾⣿⣿⣿⣿⣿⡟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀
⢸⠉⣿⣿⣿⣿⣷⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣠⣼⣿⣿⣿⣿⣿⣿⠿⠟⠉⠀⠀⠀⠀⠀
⢸⠀⠹⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠟⠛⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠘⠀⠀⠀⠈⠉⠉⣽⣿⣍⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠈⢿⣿⠟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
╭─────────────────────────────────╮
│ Filling The Void │
╰─────────────────────────────────╯
-12
View File
@@ -133,18 +133,6 @@ static const FFlogo T[] = {
.colorTitle = FF_COLOR_FG_256 "32",
},
#endif
#ifdef FASTFETCH_DATATEXT_LOGO_TURKISH
// Turkish
{
.names = { "Turkish", },
.lines = FASTFETCH_DATATEXT_LOGO_TURKISH,
.colors = {
FF_COLOR_FG_DEFAULT,
},
.colorKeys = FF_COLOR_FG_BLUE,
.colorTitle = FF_COLOR_FG_RED,
},
#endif
#ifdef FASTFETCH_DATATEXT_LOGO_TUXEDO_OS
// TuxedoOS
{
-20
View File
@@ -1,20 +0,0 @@
@@@@@@@@@
@@@@@@ @@
@@@@@
@@@@@
@@@@@@
@@@@@ @@@@@
@@@@@@ @@@@@@@@@@@@@
@@@@@@@ @@ @@@@@@ @
@@@@@@@@@@@ @@@@@
@@@@
@@@@
@@@@@@@@@@ @@@@@
@@@@@@@ @@ @@@@@@ @
@@@@@@ @@@@@@@@@@@@@
@@@@@ @@@@@@@
@@@@@@
@@@@@
@@@@@
@@@@@@ @@
@@@@@@@@@@
+2 -2
View File
@@ -366,11 +366,11 @@ static bool logoHasName(const FFlogo* logo, const FFstrbuf* name, bool small) {
}
static const FFlogo* logoGetBuiltin(const FFstrbuf* name, FFLogoSize size) {
if (name->length == 0 || !isalpha(name->chars[0])) {
if (name->length == 0 || !isalpha((unsigned char) name->chars[0])) {
return nullptr;
}
for (const FFlogo* logo = ffLogoBuiltins[toupper(name->chars[0]) - 'A']; *logo->names; ++logo) {
for (const FFlogo* logo = ffLogoBuiltins[toupper((unsigned char) name->chars[0]) - 'A']; *logo->names; ++logo) {
switch (size) {
// Never use alternate logos
case FF_LOGO_SIZE_NORMAL:
+2 -2
View File
@@ -7,7 +7,7 @@
#include <ctype.h>
static inline bool shouldIgnoreChar(char c) {
return isblank(c) || c == '-' || c == '.';
return isblank((unsigned char) c) || c == '-' || c == '.';
}
static bool artistInSongTitle(const FFstrbuf* song, const FFstrbuf* artist) {
@@ -31,7 +31,7 @@ static bool artistInSongTitle(const FFstrbuf* song, const FFstrbuf* artist) {
return false;
}
if (tolower(song->chars[songIndex]) != tolower(artist->chars[artistIndex])) {
if (tolower((unsigned char) song->chars[songIndex]) != tolower((unsigned char) artist->chars[artistIndex])) {
return false;
}
+1 -1
View File
@@ -243,7 +243,7 @@ void ffParsePackagesJsonObject(FFPackagesOptions* options, yyjson_val* module) {
else if (ffStrEqualsIgnCase(flag, #name)) { \
options->disabled |= FF_PACKAGES_FLAG_##name##_BIT; \
}
switch (toupper(flag[0])) {
switch (toupper((unsigned char) flag[0])) {
case 'A':
if (false)
;
+3
View File
@@ -1,6 +1,7 @@
#pragma once
#include "common/option.h"
#include "common/percent.h"
typedef enum FFPhysicalDiskType: uint8_t {
FF_PHYSICALDISK_TYPE_NONE = 0,
@@ -27,6 +28,8 @@ typedef struct FFPhysicalDiskOptions {
FFPhysicalDiskType hideType;
bool temp;
FFColorRangeConfig tempConfig;
bool health;
FFPercentageModuleConfig percent;
} FFPhysicalDiskOptions;
static_assert(sizeof(FFPhysicalDiskOptions) <= FF_OPTION_MAX_SIZE, "FFPhysicalDiskOptions size exceeds maximum allowed size");
+111
View File
@@ -1,6 +1,7 @@
#include "common/printing.h"
#include "common/jsonconfig.h"
#include "common/temps.h"
#include "common/percent.h"
#include "common/size.h"
#include "detection/physicaldisk/physicaldisk.h"
#include "modules/physicaldisk/physicaldisk.h"
@@ -9,6 +10,20 @@ static int sortDevices(const FFPhysicalDiskResult* left, const FFPhysicalDiskRes
return ffStrbufComp(&left->name, &right->name);
}
static const char* const warningNames[] = {
"spare below threshold",
"temperature",
"reliability degraded",
"read-only",
"backup failed",
"pmr read-only",
"failing",
};
static inline double getHealth(const FFPhysicalDiskResult* dev) {
return dev->percentUsed >= 100 ? 0 : 100 - dev->percentUsed;
}
static void formatKey(const FFPhysicalDiskOptions* options, FFPhysicalDiskResult* dev, uint32_t index, FFstrbuf* key) {
if (options->moduleArgs.key.length == 0) {
ffStrbufSetF(key, "%s (%s)", FF_MODULE_GET_DISPLAY_NAME(PhysicalDisk), dev->name.length ? dev->name.chars : dev->devPath.chars);
@@ -35,6 +50,8 @@ bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) {
ffListSort(&result, sizeof(FFPhysicalDiskResult), (const void*) sortDevices);
FFPercentageTypeFlags percentType = options->percent.type == 0 ? instance.config.display.percentType : options->percent.type;
uint32_t index = 0;
FF_STRBUF_AUTO_DESTROY key = ffStrbufCreate();
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
@@ -90,10 +107,55 @@ bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) {
ffTempsAppendNum(dev->temperature, &buffer, options->tempConfig, &options->moduleArgs);
}
if (dev->percentUsed != FF_PHYSICALDISK_PERCENT_UNSET && (percentType & (FF_PERCENTAGE_TYPE_NUM_BIT | FF_PERCENTAGE_TYPE_BAR_BIT))) {
ffStrbufAppendS(&buffer, " - Health ");
bool hasBar = percentType & FF_PERCENTAGE_TYPE_BAR_BIT;
if (hasBar) {
ffPercentAppendBar(&buffer, getHealth(dev), options->percent, &options->moduleArgs);
}
if (percentType & FF_PERCENTAGE_TYPE_NUM_BIT) {
if (hasBar) {
ffStrbufAppendC(&buffer, ' ');
}
ffPercentAppendNum(&buffer, getHealth(dev), options->percent, hasBar, &options->moduleArgs);
}
}
if (dev->criticalWarning != FF_PHYSICALDISK_WARNING_UNSET) {
const char* separator = " - Warning: ";
for (uint32_t i = 0; i < ARRAY_SIZE(warningNames); ++i) {
if (dev->criticalWarning & (1 << i)) {
ffStrbufAppendS(&buffer, separator);
ffStrbufAppendS(&buffer, warningNames[i]);
separator = ", ";
}
}
}
ffStrbufPutTo(&buffer, stdout);
} else {
FF_STRBUF_AUTO_DESTROY tempStr = ffStrbufCreate();
ffTempsAppendNum(dev->temperature, &tempStr, options->tempConfig, &options->moduleArgs);
FF_STRBUF_AUTO_DESTROY healthStr = ffStrbufCreate();
FF_STRBUF_AUTO_DESTROY percentUsedStr = ffStrbufCreate();
if (dev->percentUsed != FF_PHYSICALDISK_PERCENT_UNSET) {
ffPercentAppendNum(&healthStr, getHealth(dev), options->percent, false, &options->moduleArgs);
ffStrbufAppendF(&percentUsedStr, "%u%%", (unsigned) dev->percentUsed);
}
FF_STRBUF_AUTO_DESTROY spareStr = ffStrbufCreate();
if (dev->availableSpare != FF_PHYSICALDISK_PERCENT_UNSET) {
ffStrbufAppendF(&spareStr, "%u%%", (unsigned) dev->availableSpare);
}
FF_LIST_AUTO_DESTROY warnings = ffListCreate();
if (dev->criticalWarning != FF_PHYSICALDISK_WARNING_UNSET) {
for (uint32_t i = 0; i < ARRAY_SIZE(warningNames); ++i) {
if (dev->criticalWarning & (1 << i)) {
ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, warnings), warningNames[i]);
}
}
}
if (dev->type & FF_PHYSICALDISK_TYPE_READWRITE) {
readOnlyType = "Read-write";
}
@@ -108,6 +170,10 @@ bool ffPrintPhysicalDisk(FFPhysicalDiskOptions* options) {
FF_ARG(readOnlyType, "readonly-type"),
FF_ARG(dev->revision, "revision"),
FF_ARG(tempStr, "temperature"),
FF_ARG(healthStr, "health"),
FF_ARG(percentUsedStr, "percent-used"),
FF_ARG(spareStr, "available-spare"),
FF_ARG(warnings, "critical-warning"),
}));
}
++index;
@@ -167,6 +233,19 @@ void ffParsePhysicalDiskJsonObject(FFPhysicalDiskOptions* options, yyjson_val* m
continue;
}
if (unsafe_yyjson_equals_str(key, "health")) {
if (!yyjson_is_bool(val)) {
ffPrintError(FF_MODULE_GET_DISPLAY_NAME(PhysicalDisk), 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "health must be a boolean");
} else {
options->health = unsafe_yyjson_is_true(val);
}
continue;
}
if (ffPercentParseJsonObject(key, val, &options->percent)) {
continue;
}
ffPrintError(FF_MODULE_GET_DISPLAY_NAME(PhysicalDisk), 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown JSON key %s", unsafe_yyjson_get_str(key));
}
}
@@ -179,6 +258,9 @@ void ffGeneratePhysicalDiskJsonConfig(FFPhysicalDiskOptions* options, yyjson_mut
ffTempsGenerateJsonConfig(doc, module, options->temp, options->tempConfig);
yyjson_mut_obj_add_bool(doc, module, "health", options->health);
ffPercentGenerateJsonConfig(doc, module, options->percent);
yyjson_mut_obj_add_bool(doc, module, "hideVirtual", !!(options->hideType & FF_PHYSICALDISK_TYPE_VIRTUAL));
yyjson_mut_obj_add_bool(doc, module, "hideUnused", !!(options->hideType & FF_PHYSICALDISK_TYPE_UNUSED));
}
@@ -237,6 +319,29 @@ bool ffGeneratePhysicalDiskJsonResult(FFPhysicalDiskOptions* options, yyjson_mut
} else {
yyjson_mut_obj_add_null(doc, obj, "temperature");
}
if (dev->percentUsed != FF_PHYSICALDISK_PERCENT_UNSET) {
yyjson_mut_obj_add_uint(doc, obj, "percentUsed", dev->percentUsed);
} else {
yyjson_mut_obj_add_null(doc, obj, "percentUsed");
}
if (dev->availableSpare != FF_PHYSICALDISK_PERCENT_UNSET) {
yyjson_mut_obj_add_uint(doc, obj, "availableSpare", dev->availableSpare);
} else {
yyjson_mut_obj_add_null(doc, obj, "availableSpare");
}
if (dev->criticalWarning != FF_PHYSICALDISK_WARNING_UNSET) {
yyjson_mut_val* warnings = yyjson_mut_obj_add_arr(doc, obj, "criticalWarning");
for (uint32_t i = 0; i < ARRAY_SIZE(warningNames); ++i) {
if (dev->criticalWarning & (1 << i)) {
yyjson_mut_arr_add_str(doc, warnings, warningNames[i]);
}
}
} else {
yyjson_mut_obj_add_null(doc, obj, "criticalWarning");
}
}
FF_LIST_FOR_EACH (FFPhysicalDiskResult, dev, result) {
@@ -256,6 +361,8 @@ void ffInitPhysicalDiskOptions(FFPhysicalDiskOptions* options) {
ffStrbufInit(&options->namePrefix);
options->temp = false;
options->tempConfig = (FFColorRangeConfig) { 50, 70 };
options->health = false;
options->percent = (FFPercentageModuleConfig) { 50, 20, 0 };
options->hideType = FF_PHYSICALDISK_TYPE_UNUSED;
}
@@ -307,6 +414,10 @@ FFModuleBaseInfo ffPhysicalDiskModuleInfo = {
{ "Device kind (Read-only or Read-write)", "readonly-type" },
{ "Product revision", "revision" },
{ "Device temperature (formatted)", "temperature" },
{ "Device health, 100 - percentage used (formatted)", "health" },
{ "Percentage of rated endurance used", "percent-used" },
{ "Remaining spare capacity", "available-spare" },
{ "Critical warnings (NVMe warnings or ATA SMART failing status)", "critical-warning" },
})),
.defaultOrder = 69,
};
+1 -1
View File
@@ -49,7 +49,7 @@ bool ffPrintPlayer(FFPlayerOptions* options) {
// If we don't have subdomains, it is usually more pretty to capitalize the first letter.
if (playerPrettyIsCustom && ffStrbufFirstIndexC(&playerPretty, '.') == playerPretty.length) {
playerPretty.chars[0] = (char) toupper(playerPretty.chars[0]);
playerPretty.chars[0] = (char) toupper((unsigned char) playerPretty.chars[0]);
}
if (playerPrettyIsCustom) {
+173
View File
@@ -0,0 +1,173 @@
#include "common/edidHelper.h"
#include "common/textModifier.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void verify(bool expression, const char* expressionStr, int lineNo) {
if (expression) {
return;
}
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "[%d] %s\n" FASTFETCH_TEXT_MODIFIER_RESET, lineNo, expressionStr);
exit(1);
}
#define VERIFY(expression) verify((expression), #expression, __LINE__)
// Build a zeroed EDID with a valid base block. The buffer is allocated with the
// exact EDID length, so an ASan build also catches reads past the end of it.
static uint8_t* newEdid(uint32_t length) {
uint8_t* edid = (uint8_t*) calloc(length, 1);
VERIFY(edid != NULL);
static const uint8_t header[] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00 };
memcpy(edid, header, sizeof(header));
edid[126] = (uint8_t) (length / 128 - 1);
uint8_t sum = 0;
for (uint32_t i = 0; i < 127; ++i) {
sum += edid[i];
}
edid[127] = (uint8_t) (0u - sum);
return edid;
}
static uint8_t* addCta(uint8_t* edid, uint32_t base, uint8_t revision, uint8_t dtdOffset) {
uint8_t* cta = edid + base;
cta[0] = 0x02;
cta[1] = revision;
cta[2] = dtdOffset;
return cta;
}
static void testNoExtension(void) {
uint8_t* edid = newEdid(128);
VERIFY(!ffEdidGetHdrCompatible(edid, 128));
free(edid);
}
static void testPartialBlocks(void) {
// A trailing block shorter than 128 bytes must be ignored entirely; even
// reading its tag / revision / DTD offset used to be out of bounds.
const uint32_t lengths[] = { 129, 130, 200, 255, 257, 300 };
for (uint32_t i = 0; i < sizeof(lengths) / sizeof(lengths[0]); ++i) {
uint32_t length = lengths[i];
uint8_t* edid = newEdid(length);
uint8_t* cta = edid + 128;
cta[0] = 0x02;
if (length >= 130) {
cta[1] = 0x03;
}
if (length >= 131) {
cta[2] = 0xFF;
}
VERIFY(!ffEdidGetHdrCompatible(edid, length));
free(edid);
}
}
static void testHdrDetection(void) {
uint8_t* edid = newEdid(256);
uint8_t* cta = addCta(edid, 128, 3, 7);
cta[4] = 0xE2; // extended tag, length 2
cta[5] = 0x06; // HDR SMDB
cta[6] = 0x00;
VERIFY(ffEdidGetHdrCompatible(edid, 256));
cta[5] = 0x07; // HDR DMDB
VERIFY(ffEdidGetHdrCompatible(edid, 256));
cta[5] = 0x01; // unrelated extended tag
VERIFY(!ffEdidGetHdrCompatible(edid, 256));
cta[5] = 0x06;
cta[1] = 0x02; // data block collection requires CTA revision 3
VERIFY(!ffEdidGetHdrCompatible(edid, 256));
cta[1] = 0x03;
cta[0] = 0x70; // not a CTA extension
VERIFY(!ffEdidGetHdrCompatible(edid, 256));
free(edid);
}
static void testMultipleExtensions(void) {
uint8_t* edid = newEdid(384);
edid[128] = 0x70; // some other extension type
uint8_t* cta = addCta(edid, 256, 3, 7);
cta[4] = 0xE2;
cta[5] = 0x06;
VERIFY(ffEdidGetHdrCompatible(edid, 384));
free(edid);
}
static void testEmptyDataBlockCollection(void) {
// CTA-861 version 3: d == 0 means neither DTDs nor data blocks are present,
// and d == 4 means the data block collection is empty.
uint8_t* edid = newEdid(256);
uint8_t* cta = addCta(edid, 128, 3, 0);
cta[4] = 0xE2;
cta[5] = 0x06;
VERIFY(!ffEdidGetHdrCompatible(edid, 256));
cta[2] = 4;
VERIFY(!ffEdidGetHdrCompatible(edid, 256));
free(edid);
}
static void testOutOfRangeOffset(void) {
// An out-of-range DTD offset must be clamped to the CTA block. A valid HDR
// block inside that block is still detected.
uint8_t* edid = newEdid(256);
uint8_t* cta = addCta(edid, 128, 3, 0xFF);
cta[4] = 0xE2;
cta[5] = 0x06;
VERIFY(ffEdidGetHdrCompatible(edid, 256));
// ... but bytes past the block must not be used as data blocks. These two
// bytes live in the next extension block, 44 bytes into it.
uint8_t* large = newEdid(512);
addCta(large, 128, 3, 0xFF);
large[300] = 0xE2;
large[301] = 0x06;
VERIFY(!ffEdidGetHdrCompatible(large, 512));
free(large);
free(edid);
}
static void testExtendedTagReadBounded(void) {
// A block header at i == d - 1 has no room for its extended tag inside the
// collection; byte d is the first DTD byte and must not be read as a tag.
uint8_t* edid = newEdid(256);
uint8_t* cta = addCta(edid, 128, 3, 10);
cta[9] = 0xE2;
cta[10] = 0x06;
VERIFY(!ffEdidGetHdrCompatible(edid, 256));
free(edid);
}
static void testNoCounterWrap(void) {
// The old loop counter was uint8_t: at i == 254 a block length of 1 wrapped
// it back to 0, making the scan loop forever.
uint8_t* edid = newEdid(512);
addCta(edid, 128, 3, 0xFF);
edid[382] = 0x01; // cta[254] of the first extension
VERIFY(!ffEdidGetHdrCompatible(edid, 512));
free(edid);
}
int main(void) {
testNoExtension();
testPartialBlocks();
testHdrDetection();
testMultipleExtensions();
testEmptyDataBlockCollection();
testOutOfRangeOffset();
testExtendedTagReadBounded();
testNoCounterWrap();
puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET);
return 0;
}
+181
View File
@@ -0,0 +1,181 @@
#include "common/windows/glob.h"
#include "common/windows/unicode.h"
#include "common/textModifier.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>
#include <string.h>
#include <wchar.h>
noreturn static void testFailed(const char* expression, int lineNo) {
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "[%d] %s\n" FASTFETCH_TEXT_MODIFIER_RESET, lineNo, expression);
exit(1);
}
#define VERIFY(expression) \
if (!(expression)) testFailed(#expression, __LINE__)
static void joinPath(wchar_t* result, size_t capacity, const wchar_t* base, const wchar_t* name) {
if (swprintf(result, capacity, L"%ls\\%ls", base, name) < 0) {
testFailed("swprintf", __LINE__);
}
}
static void writeFile(const wchar_t* path) {
HANDLE handle = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle == INVALID_HANDLE_VALUE) {
testFailed("CreateFileW", __LINE__);
}
CloseHandle(handle);
}
static void createDirectory(const wchar_t* path) {
if (!CreateDirectoryW(path, nullptr)) {
testFailed("CreateDirectoryW", __LINE__);
}
}
static void createFileIn(const wchar_t* directory, const wchar_t* name) {
wchar_t path[MAX_PATH];
joinPath(path, MAX_PATH, directory, name);
writeFile(path);
}
static void expectGlob(const wchar_t* pattern, const wchar_t* expected) {
FF_STRBUF_AUTO_DESTROY patternUtf8 = ffStrbufCreateWS(pattern);
FF_STRBUF_AUTO_DESTROY expectedUtf8 = ffStrbufCreateWS(expected);
FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate();
if (!ffGlobWindows(patternUtf8.chars, &result) || !ffStrbufEqual(&result, &expectedUtf8)) {
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "glob mismatch for %ls: expected %ls, got %s\n" FASTFETCH_TEXT_MODIFIER_RESET, pattern, expected, result.chars ? result.chars : "(null)");
exit(1);
}
}
static void expectNoGlob(const wchar_t* pattern) {
FF_STRBUF_AUTO_DESTROY patternUtf8 = ffStrbufCreateWS(pattern);
FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate();
if (ffGlobWindows(patternUtf8.chars, &result)) {
fprintf(stderr, FASTFETCH_TEXT_MODIFIER_ERROR "glob unexpectedly matched %ls: %s\n" FASTFETCH_TEXT_MODIFIER_RESET, pattern, result.chars);
exit(1);
}
}
int main(void) {
wchar_t tempPath[MAX_PATH];
DWORD tempLength = GetTempPathW(MAX_PATH, tempPath);
VERIFY(tempLength > 0 && tempLength < MAX_PATH);
wchar_t root[MAX_PATH];
VERIFY(swprintf(root, MAX_PATH, L"%lsfastfetch-glob-%lu-%lu", tempPath, GetCurrentProcessId(), GetTickCount()) > 0);
createDirectory(root);
wchar_t sub[MAX_PATH], dot[MAX_PATH], weirdDollar[MAX_PATH], weirdPercent[MAX_PATH];
joinPath(sub, MAX_PATH, root, L"sub");
joinPath(dot, MAX_PATH, root, L"dot");
joinPath(weirdDollar, MAX_PATH, root, L"$weird");
joinPath(weirdPercent, MAX_PATH, root, L"%weird%");
createDirectory(sub);
createDirectory(dot);
createDirectory(weirdDollar);
createDirectory(weirdPercent);
createFileIn(root, L"a.txt");
createFileIn(root, L"b.txt");
createFileIn(root, L"c.log");
createFileIn(root, L"d.pngx");
createFileIn(root, L".hidden.txt");
createFileIn(sub, L"x.txt");
createFileIn(dot, L"only.txt");
createFileIn(dot, L".hidden.txt");
createFileIn(weirdDollar, L"z.txt");
createFileIn(weirdPercent, L"w.txt");
wchar_t pattern[MAX_PATH], expected[MAX_PATH];
// Plain paths are returned as they are.
joinPath(pattern, MAX_PATH, root, L"a.txt");
expectGlob(pattern, pattern);
// `?`, character classes and negated classes.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\?.log", root) > 0);
joinPath(expected, MAX_PATH, root, L"c.log");
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\[a].txt", root) > 0);
joinPath(expected, MAX_PATH, root, L"a.txt");
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\[!a].txt", root) > 0);
joinPath(expected, MAX_PATH, root, L"b.txt");
expectGlob(pattern, expected);
// Wildcards work in intermediate components too.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\*\\x.txt", root) > 0);
joinPath(expected, MAX_PATH, sub, L"x.txt");
expectGlob(pattern, expected);
// Dot files are excluded unless the pattern starts with a dot.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\dot\\*.txt", root) > 0);
joinPath(expected, MAX_PATH, dot, L"only.txt");
expectGlob(pattern, expected);
// `%NAME%`, `$NAME` and `${NAME}` are all accepted.
joinPath(expected, MAX_PATH, sub, L"x.txt");
VERIFY(SetEnvironmentVariableW(L"FASTFETCH_TEST_GLOB_DIR", sub));
VERIFY(swprintf(pattern, MAX_PATH, L"%%FASTFETCH_TEST_GLOB_DIR%%\\x.txt") > 0);
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"$FASTFETCH_TEST_GLOB_DIR\\x.txt") > 0);
expectGlob(pattern, expected);
VERIFY(swprintf(pattern, MAX_PATH, L"${FASTFETCH_TEST_GLOB_DIR}\\x.txt") > 0);
expectGlob(pattern, expected);
VERIFY(SetEnvironmentVariableW(L"FASTFETCH_TEST_GLOB_DIR", nullptr));
// Undefined variables are literal, so paths containing `$` or `%` still work.
VERIFY(SetEnvironmentVariableW(L"weird", nullptr));
joinPath(pattern, MAX_PATH, weirdDollar, L"z.txt");
expectGlob(pattern, pattern);
joinPath(pattern, MAX_PATH, weirdPercent, L"w.txt");
expectGlob(pattern, pattern);
// No match is reported as such. `*.png` must not fall back to the 8.3 short name of `d.pngx`,
// and `?` must not match an empty suffix.
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\nope*.txt", root) > 0);
expectNoGlob(pattern);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\*.png", root) > 0);
expectNoGlob(pattern);
VERIFY(swprintf(pattern, MAX_PATH, L"%ls\\c?.log", root) > 0);
expectNoGlob(pattern);
wchar_t path[MAX_PATH];
const wchar_t* files[] = { L"a.txt", L"b.txt", L"c.log", L"d.pngx", L".hidden.txt" };
for (uint32_t i = 0; i < ARRAY_SIZE(files); ++i) {
joinPath(path, MAX_PATH, root, files[i]);
DeleteFileW(path);
}
const wchar_t* subFiles[] = { L"x.txt" };
for (uint32_t i = 0; i < ARRAY_SIZE(subFiles); ++i) {
joinPath(path, MAX_PATH, sub, subFiles[i]);
DeleteFileW(path);
}
const wchar_t* dotFiles[] = { L"only.txt", L".hidden.txt" };
for (uint32_t i = 0; i < ARRAY_SIZE(dotFiles); ++i) {
joinPath(path, MAX_PATH, dot, dotFiles[i]);
DeleteFileW(path);
}
joinPath(path, MAX_PATH, weirdDollar, L"z.txt");
DeleteFileW(path);
joinPath(path, MAX_PATH, weirdPercent, L"w.txt");
DeleteFileW(path);
RemoveDirectoryW(sub);
RemoveDirectoryW(dot);
RemoveDirectoryW(weirdDollar);
RemoveDirectoryW(weirdPercent);
RemoveDirectoryW(root);
puts("\033[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET);
return 0;
}
+8
View File
@@ -397,6 +397,14 @@ int main(void) {
VERIFY(ffStrbufEqualS(&strbuf, "TEST"));
ffStrbufDestroy(&strbuf);
// ffStrbufUpperCase & ffStrbufLowerCase
ffStrbufInitS(&strbuf, "Hello, World! \x80\xff");
ffStrbufUpperCase(&strbuf);
VERIFY(ffStrbufEqualS(&strbuf, "HELLO, WORLD! \x80\xff"));
ffStrbufLowerCase(&strbuf);
VERIFY(ffStrbufEqualS(&strbuf, "hello, world! \x80\xff"));
ffStrbufDestroy(&strbuf);
// ffStrbufEnsureFixedLengthFree / empty buffer
ffStrbufInit(&strbuf);
ffStrbufEnsureFixedLengthFree(&strbuf, 10);
+2
View File
@@ -26,6 +26,8 @@ int main(void) {
VERIFY(ffStrSet("a"));
VERIFY(ffStrSet(" a"));
VERIFY(ffStrSet("a "));
VERIFY(ffStrSet("\x80"));
VERIFY(ffStrSet("\xff"));
}
{