From c018073384cc235f2caa3c3afe72cadd631ea9b9 Mon Sep 17 00:00:00 2001 From: Piotr Kubaj Date: Fri, 6 Nov 2026 20:13:14 +0100 Subject: [PATCH 01/38] Libc (FreeBSD): uses base objdump to detect libc version The FBSD version was only detected when binutils' /usr/local/bin/objdump was installed. Supported FreeBSD releases ship llvm-objdump as /usr/bin/objdump in base, which gives the same result, so try it first like MidnightBSD already does and keep /usr/local/bin/objdump as a fallback. DragonFly sets FreeBSD too, so exclude it from both branches. Until now the FreeBSD branch caught DragonFly first and the DF version was never detected. --- CHANGELOG.md | 5 +++++ CMakeLists.txt | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e020d1289b..7ec3cee647 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# Unreleased + +Bugfixes: +* Fixed libc version detection on FreeBSD without binutils installed, and on DragonFly BSD. (Libc, FreeBSD / DragonFly) + # 2.71.0 Features: diff --git a/CMakeLists.txt b/CMakeLists.txt index a272305020..42b98908c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1610,14 +1610,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]+)") From 6843b56f1fac8572ec915e66b719a8251bc7ea3e Mon Sep 17 00:00:00 2001 From: Carter Li Date: Sat, 7 Nov 2026 21:12:50 +0800 Subject: [PATCH 02/38] PhysicalMemory (Linux): reads unprivileged DMI physical memory slots from /run/udev/data/+dmi:id --- CMakeLists.txt | 15 +- .../physicalmemory/physicalmemory_linux.c | 407 +++++++++--------- .../physicalmemory/physicalmemory_shared.c | 252 +++++++++++ 3 files changed, 454 insertions(+), 220 deletions(-) create mode 100644 src/detection/physicalmemory/physicalmemory_shared.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 42b98908c6..25f5cd6446 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 @@ -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 @@ -1188,7 +1189,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 +1245,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 +1330,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 diff --git a/src/detection/physicalmemory/physicalmemory_linux.c b/src/detection/physicalmemory/physicalmemory_linux.c index 6abd1021bd..28bd8d7176 100644 --- a/src/detection/physicalmemory/physicalmemory_linux.c +++ b/src/detection/physicalmemory/physicalmemory_linux.c @@ -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" + +// 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 + +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(), + }; +} -// 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"); +static void ffUdevResultDestroy(FFPhysicalMemoryResult* device) { + ffStrbufDestroy(&device->type); + ffStrbufDestroy(&device->formFactor); + ffStrbufDestroy(&device->locator); + ffStrbufDestroy(&device->partNumber); + ffStrbufDestroy(&device->vendor); + ffStrbufDestroy(&device->serial); +} -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"; +// udev hex-escapes characters that are not allowed in property values (\xHH). +// Also drop the placeholder strings ("Unknown", "0x0000...", "", ...). +static void ffUdevSetString(FFstrbuf* strbuf, const char* value) { + ffStrbufSetS(strbuf, value); + ffStrbufDecodeHexEscapeSequences(strbuf); + // Older systemd versions print an empty value, newer ones "". + if (ffStrbufStartsWithS(strbuf, "")) { + ffStrbufClear(strbuf); } + ffCleanUpSmbiosValue(strbuf); +} - 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"; +// `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; } - 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; + 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); + } +} - const char* strings = (const char*) data + data->Header.Length; - uint16_t size = FF_READ_LE(data->Size); - bool installed = size != 0; +// 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; + } - if (!installed && !options->showEmptySlots) { - continue; + char* eq = strchr(line, '='); + if (!eq) { + return nullptr; + } + + 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; + } + + *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'; } - 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; + uint32_t index; + const char* value; + const char* field = ffUdevParseHeader(line, &index, &value); + if (!field) { + continue; } - 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; + 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); } + } - // 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); - } + if (!found) { + FF_DEBUG("No MEMORY_DEVICE_* properties in %s", FF_UDEV_DMI_ID_DB); + return false; + } - 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); + // 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; } - 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) { + device->ecc = totalWidths[index] > 0 && dataWidths[index] > 0 && + totalWidths[index] > dataWidths[index]; + + if (!device->installed) { + device->maxSpeed = device->runningSpeed = 0; ffStrbufSetStatic(&device->type, "Empty"); - } else if (data->MemoryType > 0 && data->MemoryType < ARRAY_SIZE(memoryTypeNames)) { - ffStrbufSetStatic(&device->type, memoryTypeNames[data->MemoryType]); + ffStrbufClear(&device->vendor); + ffStrbufClear(&device->serial); + ffStrbufClear(&device->partNumber); } 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; + if (device->type.length == 0) { + ffStrbufSetStatic(&device->type, "Unknown"); } - - 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); } + ++i; + } + return true; +} - 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; - } - } +const char* ffDetectPhysicalMemory(FFPhysicalMemoryOptions* options, FFlist* result) { + if (ffDetectPhysicalMemoryFromUdev(options, result)) { + FF_DEBUG("Physical memory detected from %s", FF_UDEV_DMI_ID_DB); + return nullptr; } - 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); } diff --git a/src/detection/physicalmemory/physicalmemory_shared.c b/src/detection/physicalmemory/physicalmemory_shared.c new file mode 100644 index 0000000000..a9febcaaaa --- /dev/null +++ b/src/detection/physicalmemory/physicalmemory_shared.c @@ -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 From ced33a83559f65aafe79a6e67d0acc71cf4a0c6a Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 9 Nov 2026 00:16:22 +0800 Subject: [PATCH 03/38] GPU (Linux): improves PCI GPU name resolution --- CHANGELOG.md | 3 ++ src/detection/gpu/gpu_linux.c | 69 +++++++++++++++++++++++++++++++++-- 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec3cee647..24e7f84077 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Unreleased +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) + Bugfixes: * Fixed libc version detection on FreeBSD without binutils installed, and on DragonFly BSD. (Libc, FreeBSD / DragonFly) diff --git a/src/detection/gpu/gpu_linux.c b/src/detection/gpu/gpu_linux.c index a594f74554..007e0633a4 100644 --- a/src/detection/gpu/gpu_linux.c +++ b/src/detection/gpu/gpu_linux.c @@ -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 -#include 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); From 2978651c9dee34a61e4855dd2a5f33d40834fabe Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 9 Nov 2026 09:55:32 +0800 Subject: [PATCH 04/38] GPU (Linux): marks Redhat Virtio GPU as integrated --- src/detection/gpu/gpu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/detection/gpu/gpu.c b/src/detection/gpu/gpu.c index 70313683c6..7118a14635 100644 --- a/src/detection/gpu/gpu.c +++ b/src/detection/gpu/gpu.c @@ -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; } From 798e2ccc24b56711205709185e8a8dc6533c7a1a Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 9 Nov 2026 12:27:18 +0800 Subject: [PATCH 05/38] Shell (Windows): add pwsh-preview version detection --- src/detection/terminalshell/terminalshell.c | 2 +- src/detection/terminalshell/terminalshell_windows.c | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/detection/terminalshell/terminalshell.c b/src/detection/terminalshell/terminalshell.c index 8f58c2c4b8..c5d49c947f 100644 --- a/src/detection/terminalshell/terminalshell.c +++ b/src/detection/terminalshell/terminalshell.c @@ -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")) { diff --git a/src/detection/terminalshell/terminalshell_windows.c b/src/detection/terminalshell/terminalshell_windows.c index eb5d59ffc0..a9bc51c3a9 100644 --- a/src/detection/terminalshell/terminalshell_windows.c +++ b/src/detection/terminalshell/terminalshell_windows.c @@ -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")) { From 6a82126aa99a81bd4c083f37ef52c140c1438c40 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Tue, 10 Nov 2026 18:39:07 +0800 Subject: [PATCH 06/38] Logo (Builtin): removes Turkmen Linux I **LOVE** removing code Ref: #2422 --- src/logo/ascii/t.inc | 12 ------------ src/logo/ascii/t/turkish.txt | 20 -------------------- 2 files changed, 32 deletions(-) delete mode 100644 src/logo/ascii/t/turkish.txt diff --git a/src/logo/ascii/t.inc b/src/logo/ascii/t.inc index d13b34d799..27bf55bf6f 100644 --- a/src/logo/ascii/t.inc +++ b/src/logo/ascii/t.inc @@ -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 { diff --git a/src/logo/ascii/t/turkish.txt b/src/logo/ascii/t/turkish.txt deleted file mode 100644 index 10a53786ca..0000000000 --- a/src/logo/ascii/t/turkish.txt +++ /dev/null @@ -1,20 +0,0 @@ - @@@@@@@@@ - @@@@@@ @@ - @@@@@ - @@@@@ -@@@@@@ - @@@@@ @@@@@ - @@@@@@ @@@@@@@@@@@@@ - @@@@@@@ @@ @@@@@@ @ - @@@@@@@@@@@ @@@@@ - @@@@ - @@@@ - @@@@@@@@@@ @@@@@ - @@@@@@@ @@ @@@@@@ @ - @@@@@@ @@@@@@@@@@@@@ - @@@@@ @@@@@@@ -@@@@@@ - @@@@@ - @@@@@ - @@@@@@ @@ - @@@@@@@@@@ \ No newline at end of file From c6c8bffbabcfa22809f3b9f092165b3e9a59d1d8 Mon Sep 17 00:00:00 2001 From: pro-laxmi Date: Wed, 11 Nov 2026 23:26:15 +0530 Subject: [PATCH 07/38] fix: cast char to unsigned char before passing to isspace to prevent UB --- src/common/FFstrbuf.h | 2 +- src/common/impl/FFstrbuf.c | 2 +- src/common/strutil.h | 2 +- tests/strutil.c | 2 ++ 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/common/FFstrbuf.h b/src/common/FFstrbuf.h index 214f4cdb63..7681299d4a 100644 --- a/src/common/FFstrbuf.h +++ b/src/common/FFstrbuf.h @@ -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) { diff --git a/src/common/impl/FFstrbuf.c b/src/common/impl/FFstrbuf.c index 494e487c88..cd0304360d 100644 --- a/src/common/impl/FFstrbuf.c +++ b/src/common/impl/FFstrbuf.c @@ -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; } diff --git a/src/common/strutil.h b/src/common/strutil.h index ee30dbc41c..a4fe126aa5 100644 --- a/src/common/strutil.h +++ b/src/common/strutil.h @@ -28,7 +28,7 @@ static inline bool ffStrSet(const char* str) { return false; } - while (isspace(*str)) { + while (isspace((unsigned char)*str)) { str++; } diff --git a/tests/strutil.c b/tests/strutil.c index 1b06ff5b74..4998889542 100644 --- a/tests/strutil.c +++ b/tests/strutil.c @@ -26,6 +26,8 @@ int main(void) { VERIFY(ffStrSet("a")); VERIFY(ffStrSet(" a")); VERIFY(ffStrSet("a ")); + VERIFY(ffStrSet("\x80")); + VERIFY(ffStrSet("\xff")); } { From 2b299cf97abc7bef73540d194538f081236b754b Mon Sep 17 00:00:00 2001 From: pro-laxmi Date: Wed, 11 Nov 2026 23:34:06 +0530 Subject: [PATCH 08/38] fix(initsystem): avoid mutating path buffer with POSIX basename --- src/detection/initsystem/initsystem_linux.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/detection/initsystem/initsystem_linux.c b/src/detection/initsystem/initsystem_linux.c index 12243bb4d2..9bbcbda03d 100644 --- a/src/detection/initsystem/initsystem_linux.c +++ b/src/detection/initsystem/initsystem_linux.c @@ -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)); } } From dc5e708b47a5221860cb916215eedb1ab6f64276 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Sun, 15 Nov 2026 11:12:46 +0800 Subject: [PATCH 09/38] Common (EDID): bounds-check CTA-861 extension parsing --- CMakeLists.txt | 10 ++ src/common/impl/edidHelper.c | 12 ++- tests/edid.c | 173 +++++++++++++++++++++++++++++++++++ 3 files changed, 191 insertions(+), 4 deletions(-) create mode 100644 tests/edid.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 25f5cd6446..324d111ddb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2497,6 +2497,13 @@ 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) @@ -2518,6 +2525,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() ################## diff --git a/src/common/impl/edidHelper.c b/src/common/impl/edidHelper.c index 4b8f4f84dc..b1a973e369 100644 --- a/src/common/impl/edidHelper.c +++ b/src/common/impl/edidHelper.c @@ -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; diff --git a/tests/edid.c b/tests/edid.c new file mode 100644 index 0000000000..75d3c59046 --- /dev/null +++ b/tests/edid.c @@ -0,0 +1,173 @@ +#include "common/edidHelper.h" +#include "common/textModifier.h" + +#include +#include +#include +#include +#include + +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; +} From de5fb51ba7a533f146b41327d206e309c537f60a Mon Sep 17 00:00:00 2001 From: Carter Li Date: Sun, 15 Nov 2026 11:13:00 +0800 Subject: [PATCH 10/38] Display (Linux): reads EDID from the correct sysfs path --- src/detection/displayserver/linux/drm.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/detection/displayserver/linux/drm.c b/src/detection/displayserver/linux/drm.c index 21d70ea069..5dd658d66e 100644 --- a/src/detection/displayserver/linux/drm.c +++ b/src/detection/displayserver/linux/drm.c @@ -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"), '-'); @@ -69,6 +66,9 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) { 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)) { From fa648eef607291b6e72ac69512fee020189713fa Mon Sep 17 00:00:00 2001 From: Carter Li Date: Sun, 15 Nov 2026 11:13:09 +0800 Subject: [PATCH 11/38] Display (Linux): NUL-terminate sysfs modes buffer before sscanf --- src/detection/displayserver/linux/drm.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/detection/displayserver/linux/drm.c b/src/detection/displayserver/linux/drm.c index 5dd658d66e..cac84967a1 100644 --- a/src/detection/displayserver/linux/drm.c +++ b/src/detection/displayserver/linux/drm.c @@ -60,7 +60,9 @@ 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); From aef14850a188f0f3e059782c0cf286d9b3a3c440 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Sun, 15 Nov 2026 11:13:20 +0800 Subject: [PATCH 12/38] Display (Linux): clears display name before appending EDID name --- src/detection/displayserver/linux/drm.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/detection/displayserver/linux/drm.c b/src/detection/displayserver/linux/drm.c index cac84967a1..81b6f6ecfd 100644 --- a/src/detection/displayserver/linux/drm.c +++ b/src/detection/displayserver/linux/drm.c @@ -74,6 +74,7 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) { 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); From 73368d36d99c5e647782346b7c075aac12599e45 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Fri, 13 Nov 2026 16:14:24 +0800 Subject: [PATCH 13/38] Logo (Windows): supports glob and environment variables in source paths --- CHANGELOG.md | 3 + CMakeLists.txt | 13 ++ doc/help.json | 2 +- doc/json_schema.json | 2 +- src/common/impl/io_windows.c | 27 +-- src/common/windows/glob.c | 393 +++++++++++++++++++++++++++++++++++ src/common/windows/glob.h | 16 ++ src/common/windows/nt.h | 3 + src/common/windows/unicode.c | 23 ++ src/common/windows/unicode.h | 77 +++++++ tests/glob.c | 181 ++++++++++++++++ 11 files changed, 718 insertions(+), 22 deletions(-) create mode 100644 src/common/windows/glob.c create mode 100644 src/common/windows/glob.h create mode 100644 tests/glob.c diff --git a/CHANGELOG.md b/CHANGELOG.md index 24e7f84077..27cbe19153 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Unreleased +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) + 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) diff --git a/CMakeLists.txt b/CMakeLists.txt index 324d111ddb..43b9f3214c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1148,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 @@ -2371,6 +2372,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 ) @@ -2507,6 +2517,9 @@ if (BUILD_TESTS) 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) diff --git a/doc/help.json b/doc/help.json index ceb4926d18..5d29a8bb63 100644 --- a/doc/help.json +++ b/doc/help.json @@ -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" } diff --git a/doc/json_schema.json b/doc/json_schema.json index 8f586889c8..1470870b47 100644 --- a/doc/json_schema.json +++ b/doc/json_schema.json @@ -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", diff --git a/src/common/impl/io_windows.c b/src/common/impl/io_windows.c index e787a83d07..ae5c539acd 100644 --- a/src/common/impl/io_windows.c +++ b/src/common/impl/io_windows.c @@ -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; - } - } - - 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; + 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); } - 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) { diff --git a/src/common/windows/glob.c b/src/common/windows/glob.c new file mode 100644 index 0000000000..a6bdf89d09 --- /dev/null +++ b/src/common/windows/glob.c @@ -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 +#include + +// 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; +} diff --git a/src/common/windows/glob.h b/src/common/windows/glob.h new file mode 100644 index 0000000000..81b0bb63be --- /dev/null +++ b/src/common/windows/glob.h @@ -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); diff --git a/src/common/windows/nt.h b/src/common/windows/nt.h index 6b9e4f2347..5487ef3cff 100644 --- a/src/common/windows/nt.h +++ b/src/common/windows/nt.h @@ -778,6 +778,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; diff --git a/src/common/windows/unicode.c b/src/common/windows/unicode.c index 534c399f20..db3034d1a8 100644 --- a/src/common/windows/unicode.c +++ b/src/common/windows/unicode.c @@ -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); diff --git a/src/common/windows/unicode.h b/src/common/windows/unicode.h index f58b425e5b..3de4421e88 100644 --- a/src/common/windows/unicode.h +++ b/src/common/windows/unicode.h @@ -3,6 +3,83 @@ #include "common/FFstrbuf.h" #include +// --------------------------------------------------------------------------------------------- +// 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); diff --git a/tests/glob.c b/tests/glob.c new file mode 100644 index 0000000000..5dc59417e0 --- /dev/null +++ b/tests/glob.c @@ -0,0 +1,181 @@ +#include "common/windows/glob.h" +#include "common/windows/unicode.h" +#include "common/textModifier.h" + +#include + +#include +#include +#include +#include +#include + +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; +} From 7aa8cba95b25f84e86b5793cd5e3ff83edc4edcb Mon Sep 17 00:00:00 2001 From: pro-laxmi Date: Sat, 14 Nov 2026 22:09:01 +0530 Subject: [PATCH 14/38] fix: cast char to unsigned char before passing to ctype functions --- src/common/impl/FFstrbuf.c | 4 ++-- src/common/impl/font.c | 2 +- src/common/impl/properties.c | 2 +- src/detection/chassis/chassis_linux.c | 2 +- src/detection/cpu/cpu_linux.c | 8 ++++---- src/detection/wm/wm_apple.m | 2 +- src/detection/wmtheme/wmtheme_windows.c | 4 ++-- src/logo/logo.c | 4 ++-- src/modules/media/media.c | 4 ++-- src/modules/packages/packages.c | 2 +- src/modules/player/player.c | 2 +- tests/strbuf.c | 8 ++++++++ 12 files changed, 26 insertions(+), 18 deletions(-) diff --git a/src/common/impl/FFstrbuf.c b/src/common/impl/FFstrbuf.c index cd0304360d..23f10ff85d 100644 --- a/src/common/impl/FFstrbuf.c +++ b/src/common/impl/FFstrbuf.c @@ -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]); } } diff --git a/src/common/impl/font.c b/src/common/impl/font.c index 681c249069..42ec359ed9 100644 --- a/src/common/impl/font.c +++ b/src/common/impl/font.c @@ -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); diff --git a/src/common/impl/properties.c b/src/common/impl/properties.c index 9a4fe290ec..54c1f67c85 100644 --- a/src/common/impl/properties.c +++ b/src/common/impl/properties.c @@ -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; } diff --git a/src/detection/chassis/chassis_linux.c b/src/detection/chassis/chassis_linux.c index e23f73463e..55ad895c9b 100644 --- a/src/detection/chassis/chassis_linux.c +++ b/src/detection/chassis/chassis_linux.c @@ -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; diff --git a/src/detection/cpu/cpu_linux.c b/src/detection/cpu/cpu_linux.c index 31c2331037..51887a0438 100644 --- a/src/detection/cpu/cpu_linux.c +++ b/src/detection/cpu/cpu_linux.c @@ -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]); } } diff --git a/src/detection/wm/wm_apple.m b/src/detection/wm/wm_apple.m index e02c089bb7..ccee2524f8 100644 --- a/src/detection/wm/wm_apple.m +++ b/src/detection/wm/wm_apple.m @@ -71,7 +71,7 @@ } ffStrbufAppendS(pluginName, comm); - pluginName->chars[0] = (char) toupper(pluginName->chars[0]); + pluginName->chars[0] = (char) toupper((unsigned char) pluginName->chars[0]); break; } diff --git a/src/detection/wmtheme/wmtheme_windows.c b/src/detection/wmtheme/wmtheme_windows.c index adaece574b..a622117ccd 100644 --- a/src/detection/wmtheme/wmtheme_windows.c +++ b/src/detection/wmtheme/wmtheme_windows.c @@ -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); diff --git a/src/logo/logo.c b/src/logo/logo.c index b95ac5fdc1..44d76ce0cf 100644 --- a/src/logo/logo.c +++ b/src/logo/logo.c @@ -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: diff --git a/src/modules/media/media.c b/src/modules/media/media.c index 14b7faa9ac..57baf266b5 100644 --- a/src/modules/media/media.c +++ b/src/modules/media/media.c @@ -7,7 +7,7 @@ #include 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; } diff --git a/src/modules/packages/packages.c b/src/modules/packages/packages.c index b8b7f39b2c..7ba7ce1aaa 100644 --- a/src/modules/packages/packages.c +++ b/src/modules/packages/packages.c @@ -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) ; diff --git a/src/modules/player/player.c b/src/modules/player/player.c index f5f4018839..76ea719614 100644 --- a/src/modules/player/player.c +++ b/src/modules/player/player.c @@ -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) { diff --git a/tests/strbuf.c b/tests/strbuf.c index 06cfe4754c..25a0907587 100644 --- a/tests/strbuf.c +++ b/tests/strbuf.c @@ -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); From 63a82100f654d5a15808ee00087034ccbb5299be Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:04:50 +0000 Subject: [PATCH 15/38] CI: Bump the github-actions group with 2 updates Bumps the github-actions group with 2 updates: [github/codeql-action/init](https://github.com/github/codeql-action) and [github/codeql-action/analyze](https://github.com/github/codeql-action). Updates `github/codeql-action/init` from 4.39.1 to 4.39.3 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9b3254085494b55a0f7c4c2b3d2d52cc712ce370...33d7b85da1a04171e211befe2c739303b9a4c066) Updates `github/codeql-action/analyze` from 4.39.1 to 4.39.3 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9b3254085494b55a0f7c4c2b3d2d52cc712ce370...33d7b85da1a04171e211befe2c739303b9a4c066) --- updated-dependencies: - dependency-name: github/codeql-action/init dependency-version: 4.39.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: github/codeql-action/analyze dependency-version: 4.39.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions ... Signed-off-by: dependabot[bot] --- .github/workflows/build-linux-hosts.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-linux-hosts.yml b/.github/workflows/build-linux-hosts.yml index 48d396fcd9..ba71403c89 100644 --- a/.github/workflows/build-linux-hosts.yml +++ b/.github/workflows/build-linux-hosts.yml @@ -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 From 7751a7fdd3aa56b99bc0855213ef960967ceb46c Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Mon, 16 Nov 2026 18:42:16 +0100 Subject: [PATCH 16/38] PhysicalDisk: adds health option and result fields Ref: #2726 --- doc/json_schema.json | 10 +- src/detection/physicaldisk/physicaldisk.h | 17 +++ .../physicaldisk/physicaldisk_apple.c | 3 + src/detection/physicaldisk/physicaldisk_bsd.c | 3 + .../physicaldisk/physicaldisk_haiku.c | 3 + .../physicaldisk/physicaldisk_linux.c | 3 + .../physicaldisk/physicaldisk_nbsd.c | 3 + .../physicaldisk/physicaldisk_obsd.c | 3 + .../physicaldisk/physicaldisk_sunos.c | 3 + .../physicaldisk/physicaldisk_windows.c | 3 + src/modules/physicaldisk/option.h | 3 + src/modules/physicaldisk/physicaldisk.c | 110 ++++++++++++++++++ 12 files changed, 163 insertions(+), 1 deletion(-) diff --git a/doc/json_schema.json b/doc/json_schema.json index 1470870b47..92368db678 100644 --- a/doc/json_schema.json +++ b/doc/json_schema.json @@ -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", "type": "string" }, "physicalmemoryFormat": { @@ -3967,6 +3967,14 @@ "temp": { "$ref": "#/$defs/temperature" }, + "health": { + "description": "Whether to detect and display drive health (NVMe wear / SMART status), if supported", + "type": "boolean", + "default": false + }, + "percent": { + "$ref": "#/$defs/percent" + }, "key": { "$ref": "#/$defs/key" }, diff --git a/src/detection/physicaldisk/physicaldisk.h b/src/detection/physicaldisk/physicaldisk.h index 3481063bef..7520c97121 100644 --- a/src/detection/physicaldisk/physicaldisk.h +++ b/src/detection/physicaldisk/physicaldisk.h @@ -2,6 +2,20 @@ #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_UNSET = UINT8_MAX, +} FFPhysicalDiskWarning; +static_assert(sizeof(FFPhysicalDiskWarning) == sizeof(uint8_t), ""); typedef struct FFPhysicalDiskResult { FFstrbuf name; @@ -12,6 +26,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); diff --git a/src/detection/physicaldisk/physicaldisk_apple.c b/src/detection/physicaldisk/physicaldisk_apple.c index 789ab624d5..e56bbb4f1a 100644 --- a/src/detection/physicaldisk/physicaldisk_apple.c +++ b/src/detection/physicaldisk/physicaldisk_apple.c @@ -144,6 +144,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); diff --git a/src/detection/physicaldisk/physicaldisk_bsd.c b/src/detection/physicaldisk/physicaldisk_bsd.c index 5d59fd9d91..93bdad0df9 100644 --- a/src/detection/physicaldisk/physicaldisk_bsd.c +++ b/src/detection/physicaldisk/physicaldisk_bsd.c @@ -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: diff --git a/src/detection/physicaldisk/physicaldisk_haiku.c b/src/detection/physicaldisk/physicaldisk_haiku.c index ab5599658c..8048786b6c 100644 --- a/src/detection/physicaldisk/physicaldisk_haiku.c +++ b/src/detection/physicaldisk/physicaldisk_haiku.c @@ -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); diff --git a/src/detection/physicaldisk/physicaldisk_linux.c b/src/detection/physicaldisk/physicaldisk_linux.c index 7a9fd5f798..8a0624c993 100644 --- a/src/detection/physicaldisk/physicaldisk_linux.c +++ b/src/detection/physicaldisk/physicaldisk_linux.c @@ -107,6 +107,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) { diff --git a/src/detection/physicaldisk/physicaldisk_nbsd.c b/src/detection/physicaldisk/physicaldisk_nbsd.c index bf9bd3adbf..23381b6135 100644 --- a/src/detection/physicaldisk/physicaldisk_nbsd.c +++ b/src/detection/physicaldisk/physicaldisk_nbsd.c @@ -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, diff --git a/src/detection/physicaldisk/physicaldisk_obsd.c b/src/detection/physicaldisk/physicaldisk_obsd.c index 7b8680675d..152df688b4 100644 --- a/src/detection/physicaldisk/physicaldisk_obsd.c +++ b/src/detection/physicaldisk/physicaldisk_obsd.c @@ -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, diff --git a/src/detection/physicaldisk/physicaldisk_sunos.c b/src/detection/physicaldisk/physicaldisk_sunos.c index 9ac2a30efd..10b14b7f48 100644 --- a/src/detection/physicaldisk/physicaldisk_sunos.c +++ b/src/detection/physicaldisk/physicaldisk_sunos.c @@ -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; diff --git a/src/detection/physicaldisk/physicaldisk_windows.c b/src/detection/physicaldisk/physicaldisk_windows.c index 3d6dccc2f0..923d0ac6b3 100644 --- a/src/detection/physicaldisk/physicaldisk_windows.c +++ b/src/detection/physicaldisk/physicaldisk_windows.c @@ -214,6 +214,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); diff --git a/src/modules/physicaldisk/option.h b/src/modules/physicaldisk/option.h index 0b3c81855e..f084dfdd67 100644 --- a/src/modules/physicaldisk/option.h +++ b/src/modules/physicaldisk/option.h @@ -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"); diff --git a/src/modules/physicaldisk/physicaldisk.c b/src/modules/physicaldisk/physicaldisk.c index bf8c5c389a..8a951cc1ef 100644 --- a/src/modules/physicaldisk/physicaldisk.c +++ b/src/modules/physicaldisk/physicaldisk.c @@ -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,19 @@ 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", +}; + +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 +49,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 +106,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 +169,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 +232,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 +257,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 +318,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 +360,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 +413,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 (none if healthy)", "critical-warning" }, })), .defaultOrder = 69, }; From 40c52ed4a4db5263f429879dce6110a1281e17be Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Mon, 16 Nov 2026 19:05:18 +0100 Subject: [PATCH 17/38] DBus: supports calling methods with an empty a{sv} argument Ref: #2726 --- src/common/dbus.h | 4 ++++ src/common/impl/dbus.c | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/common/dbus.h b/src/common/dbus.h index e4274180a7..09db3b1a1b 100644 --- a/src/common/dbus.h +++ b/src/common/dbus.h @@ -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); diff --git a/src/common/impl/dbus.c b/src/common/impl/dbus.c index 15041e079b..481796f13f 100644 --- a/src/common/impl/dbus.c +++ b/src/common/impl/dbus.c @@ -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) { From 3c4793cf3084403722baf3d3f43c932e59916f43 Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Mon, 16 Nov 2026 19:22:33 +0100 Subject: [PATCH 18/38] PhysicalDisk (Linux): adds health detection via udisks2 Ref: #2726 --- CHANGELOG.md | 3 + .../physicaldisk/physicaldisk_linux.c | 156 ++++++++++++++++++ 2 files changed, 159 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27cbe19153..840c2b5326 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ 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, which doesn't require root. (#2726, PhysicalDisk, Linux) + * 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}`. 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) diff --git a/src/detection/physicaldisk/physicaldisk_linux.c b/src/detection/physicaldisk/physicaldisk_linux.c index 8a0624c993..9db2a0cb9f 100644 --- a/src/detection/physicaldisk/physicaldisk_linux.c +++ b/src/detection/physicaldisk/physicaldisk_linux.c @@ -9,6 +9,156 @@ #include #include +#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" + +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) { + return; + } + + 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* devName, FFPhysicalDiskResult* device) { + char blockPath[128]; + snprintf(blockPath, ARRAY_SIZE(blockPath), "/org/freedesktop/UDisks2/block_devices/%s", devName); + + 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", devName); + return; + } + + uint64_t smartUpdated = 0; + if (!ffDBusGetPropertyUint(dbus, FF_UDISKS_BUS, drivePath.chars, FF_UDISKS_NVME_CONTROLLER, "SmartUpdated", &smartUpdated)) { + FF_DEBUG("%s has no NVMe controller interface", drivePath.chars); + return; + } + if (smartUpdated == 0) { + FF_DEBUG("udisks has not collected SMART data of %s yet", drivePath.chars); + return; + } + + DBusMessage* reply = ffDBusGetProperty(dbus, FF_UDISKS_BUS, drivePath.chars, FF_UDISKS_NVME_CONTROLLER, "SmartCriticalWarning"); + if (reply == nullptr) { + FF_DEBUG("Failed to get SmartCriticalWarning of %s", drivePath.chars); + return; + } + device->criticalWarning = parseCriticalWarning(dbus, reply); + dbus->lib->ffdbus_message_unref(reply); + + reply = ffDBusGetMethodReplyEmptyDict(dbus, FF_UDISKS_BUS, drivePath.chars, FF_UDISKS_NVME_CONTROLLER, "SmartGetAttributes"); + if (reply == nullptr) { + FF_DEBUG("SmartGetAttributes failed for %s", drivePath.chars); + return; + } + parseSmartAttributes(dbus, reply, device); + dbus->lib->ffdbus_message_unref(reply); +} + +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 (ffStrbufStartsWithS(&device->devPath, "/dev/nvme")) { + detectNvmeHealth(&dbus, device->devPath.chars + strlen("/dev/"), device); + } + } +} +#endif + static double detectNvmeTemp(int devfd) { char pathHwmon[] = "hwmon$/temp1_input"; @@ -203,5 +353,11 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) } } +#ifdef FF_HAVE_DBUS + if (options->health) { + detectHealth(result); + } +#endif + return nullptr; } From 012dbcad76c09a8d12d70fe1f5c348519f51f530 Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Tue, 17 Nov 2026 06:53:12 +0100 Subject: [PATCH 19/38] PhysicalDisk (macOS): adds health detection Ref: #2726 --- CHANGELOG.md | 2 +- src/detection/physicaldisk/physicaldisk_apple.c | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 840c2b5326..ad326f5df2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ 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, which doesn't require root. (#2726, PhysicalDisk, Linux) +* Added opt-in drive health detection for NVMe disks, via udisks2 on Linux (no root required) and NVMe SMART on macOS. (#2726, PhysicalDisk, Linux / macOS) * 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}`. diff --git a/src/detection/physicaldisk/physicaldisk_apple.c b/src/detection/physicaldisk/physicaldisk_apple.c index e56bbb4f1a..2953902168 100644 --- a/src/detection/physicaldisk/physicaldisk_apple.c +++ b/src/detection/physicaldisk/physicaldisk_apple.c @@ -21,7 +21,7 @@ static inline void wrapIoDestroyPlugInInterface(IOCFPlugInInterface*** 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 +39,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,7 +54,7 @@ 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 } @@ -186,10 +193,10 @@ 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 From fa341df5768698ac01db334434cb151ea2e04072 Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Tue, 17 Nov 2026 09:30:23 +0100 Subject: [PATCH 20/38] PhysicalDisk (Windows): adds health detection Ref: #2726 --- CHANGELOG.md | 2 +- .../physicaldisk/physicaldisk_windows.c | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad326f5df2..0ff57fdab7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ 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) and NVMe SMART on macOS. (#2726, PhysicalDisk, Linux / macOS) +* 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}`. diff --git a/src/detection/physicaldisk/physicaldisk_windows.c b/src/detection/physicaldisk/physicaldisk_windows.c index 923d0ac6b3..64b0482321 100644 --- a/src/detection/physicaldisk/physicaldisk_windows.c +++ b/src/detection/physicaldisk/physicaldisk_windows.c @@ -8,6 +8,7 @@ #include #include #include +#include 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); @@ -302,6 +303,41 @@ 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())); + } + } } return nullptr; From 634e99a6274d91769524205621d8f2d4a52d099d Mon Sep 17 00:00:00 2001 From: Carter Li Date: Tue, 17 Nov 2026 21:38:07 +0800 Subject: [PATCH 21/38] CI: tests physicaldisk.health --- presets/all.jsonc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/presets/all.jsonc b/presets/all.jsonc index 8b5f2d4d65..b1b4885f28 100644 --- a/presets/all.jsonc +++ b/presets/all.jsonc @@ -104,7 +104,8 @@ "diskio", { "type": "physicaldisk", - "temp": true + "temp": true, + "health": true }, { "type": "weather", From 9153929d2a0039965f10bd845d03aca62d8a54e6 Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Tue, 17 Nov 2026 15:09:22 +0100 Subject: [PATCH 22/38] PhysicalDisk (Linux): adds SMART failing status for ATA disks Ref: #2726 --- CHANGELOG.md | 1 + src/detection/physicaldisk/physicaldisk.h | 1 + .../physicaldisk/physicaldisk_linux.c | 92 +++++++++++++++---- src/modules/physicaldisk/physicaldisk.c | 1 + 4 files changed, 76 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ff57fdab7..faeb3c02b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Features: * 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}`. + * On Linux, ATA disks report the SMART `failing` status as a critical warning. 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) diff --git a/src/detection/physicaldisk/physicaldisk.h b/src/detection/physicaldisk/physicaldisk.h index 7520c97121..3d561f8e5f 100644 --- a/src/detection/physicaldisk/physicaldisk.h +++ b/src/detection/physicaldisk/physicaldisk.h @@ -13,6 +13,7 @@ typedef enum FFPhysicalDiskWarning: uint8_t { 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), ""); diff --git a/src/detection/physicaldisk/physicaldisk_linux.c b/src/detection/physicaldisk/physicaldisk_linux.c index 9db2a0cb9f..549b9d5b93 100644 --- a/src/detection/physicaldisk/physicaldisk_linux.c +++ b/src/detection/physicaldisk/physicaldisk_linux.c @@ -14,6 +14,7 @@ #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); @@ -80,7 +81,7 @@ static void parseSmartAttributes(FFDBusData* dbus, DBusMessage* reply, FFPhysica DBusMessageIter entryIter; dbus->lib->ffdbus_message_iter_recurse(&dictIter, &entryIter); if (dbus->lib->ffdbus_message_iter_get_arg_type(&entryIter) != DBUS_TYPE_STRING) { - return; + break; } const char* key; @@ -102,43 +103,81 @@ static void parseSmartAttributes(FFDBusData* dbus, DBusMessage* reply, FFPhysica } } -static void detectNvmeHealth(FFDBusData* dbus, const char* devName, FFPhysicalDiskResult* device) { - char blockPath[128]; - snprintf(blockPath, ARRAY_SIZE(blockPath), "/org/freedesktop/UDisks2/block_devices/%s", devName); - - 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", devName); - return; - } - +static void detectNvmeHealth(FFDBusData* dbus, const char* drivePath, FFPhysicalDiskResult* device) { uint64_t smartUpdated = 0; - if (!ffDBusGetPropertyUint(dbus, FF_UDISKS_BUS, drivePath.chars, FF_UDISKS_NVME_CONTROLLER, "SmartUpdated", &smartUpdated)) { - FF_DEBUG("%s has no NVMe controller interface", drivePath.chars); + 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.chars); + FF_DEBUG("udisks has not collected SMART data of %s yet", drivePath); return; } - DBusMessage* reply = ffDBusGetProperty(dbus, FF_UDISKS_BUS, drivePath.chars, FF_UDISKS_NVME_CONTROLLER, "SmartCriticalWarning"); + 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.chars); + 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.chars, FF_UDISKS_NVME_CONTROLLER, "SmartGetAttributes"); + reply = ffDBusGetMethodReplyEmptyDict(dbus, FF_UDISKS_BUS, drivePath, FF_UDISKS_NVME_CONTROLLER, "SmartGetAttributes"); if (reply == nullptr) { - FF_DEBUG("SmartGetAttributes failed for %s", drivePath.chars); + 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); @@ -152,8 +191,23 @@ static void detectHealth(FFlist* result) { } 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, device->devPath.chars + strlen("/dev/"), device); + detectNvmeHealth(&dbus, drivePath.chars, device); + } else { + detectAtaHealth(&dbus, drivePath.chars, device); } } } diff --git a/src/modules/physicaldisk/physicaldisk.c b/src/modules/physicaldisk/physicaldisk.c index 8a951cc1ef..3ae14dfa20 100644 --- a/src/modules/physicaldisk/physicaldisk.c +++ b/src/modules/physicaldisk/physicaldisk.c @@ -17,6 +17,7 @@ static const char* const warningNames[] = { "read-only", "backup failed", "pmr read-only", + "failing", }; static inline double getHealth(const FFPhysicalDiskResult* dev) { From 3bd01e5abce237c3915eb1e128e9ba4645ad2bf8 Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Wed, 18 Nov 2026 12:38:54 +0100 Subject: [PATCH 23/38] PhysicalDisk (Windows): adds SMART failing status for ATA disks Ref: #2726 --- CHANGELOG.md | 2 +- .../physicaldisk/physicaldisk_windows.c | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index faeb3c02b4..7f71e08bde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Features: * 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}`. - * On Linux, ATA disks report the SMART `failing` status as a critical warning. + * On Linux and Windows, ATA disks report the SMART `failing` status as a critical warning. 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) diff --git a/src/detection/physicaldisk/physicaldisk_windows.c b/src/detection/physicaldisk/physicaldisk_windows.c index 64b0482321..440ea382fd 100644 --- a/src/detection/physicaldisk/physicaldisk_windows.c +++ b/src/detection/physicaldisk/physicaldisk_windows.c @@ -340,6 +340,32 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s } } + 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; } From d3c9178f111a64f83eb8803dc7bfbb4ea967f7b5 Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Wed, 18 Nov 2026 14:24:03 +0100 Subject: [PATCH 24/38] PhysicalDisk (macOS): adds SMART failing status for ATA disks Ref: #2726 --- CHANGELOG.md | 2 +- .../physicaldisk/physicaldisk_apple.c | 42 ++++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f71e08bde..3d85950a74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Features: * 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}`. - * On Linux and Windows, ATA disks report the SMART `failing` status as a critical warning. + * ATA disks report the SMART `failing` status as a critical warning. 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) diff --git a/src/detection/physicaldisk/physicaldisk_apple.c b/src/detection/physicaldisk/physicaldisk_apple.c index 2953902168..38217bd639 100644 --- a/src/detection/physicaldisk/physicaldisk_apple.c +++ b/src/detection/physicaldisk/physicaldisk_apple.c @@ -8,18 +8,17 @@ #include #include #include +#include #ifdef MAC_OS_X_VERSION_10_15 #include #endif -#ifdef MAC_OS_X_VERSION_10_15 static inline void wrapIoDestroyPlugInInterface(IOCFPlugInInterface*** pluginInf) { assert(pluginInf); if (*pluginInf) { IODestroyPlugInInterface(*pluginInf); } } -#endif static const char* detectNvmeSmart(io_service_t entryPhysical, FFPhysicalDiskResult* device, FFPhysicalDiskOptions* options) { #ifdef MAC_OS_X_VERSION_10_15 @@ -59,6 +58,38 @@ static const char* detectNvmeSmart(io_service_t entryPhysical, FFPhysicalDiskRes #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) { @@ -200,6 +231,13 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* 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; From 69435f1e300bec5d123e465f64f5c3d06df2065f Mon Sep 17 00:00:00 2001 From: giovannilentini Date: Thu, 19 Nov 2026 11:19:32 +0100 Subject: [PATCH 25/38] PhysicalDisk: documents ATA SMART limits and HDD wake-up Ref: #2733 --- CHANGELOG.md | 2 +- doc/json_schema.json | 4 ++-- src/modules/physicaldisk/physicaldisk.c | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d85950a74..5d10bb3cd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Features: * 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. + * 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. 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) diff --git a/doc/json_schema.json b/doc/json_schema.json index 92368db678..fe1b220652 100644 --- a/doc/json_schema.json +++ b/doc/json_schema.json @@ -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)\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", + "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": { @@ -3968,7 +3968,7 @@ "$ref": "#/$defs/temperature" }, "health": { - "description": "Whether to detect and display drive health (NVMe wear / SMART status), if supported", + "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 }, diff --git a/src/modules/physicaldisk/physicaldisk.c b/src/modules/physicaldisk/physicaldisk.c index 3ae14dfa20..e5fd8fd152 100644 --- a/src/modules/physicaldisk/physicaldisk.c +++ b/src/modules/physicaldisk/physicaldisk.c @@ -417,7 +417,7 @@ FFModuleBaseInfo ffPhysicalDiskModuleInfo = { { "Device health, 100 - percentage used (formatted)", "health" }, { "Percentage of rated endurance used", "percent-used" }, { "Remaining spare capacity", "available-spare" }, - { "Critical warnings (none if healthy)", "critical-warning" }, + { "Critical warnings (NVMe warnings or ATA SMART failing status)", "critical-warning" }, })), .defaultOrder = 69, }; From 216d3b24f32871da92c630e19d49c67d7b5ca7ef Mon Sep 17 00:00:00 2001 From: Pratik Kumar Dhakar Date: Fri, 20 Nov 2026 06:00:28 +0530 Subject: [PATCH 26/38] CPUCache (Linux): skips offline CPUs --- CHANGELOG.md | 1 + src/detection/cpucache/cpucache_linux.c | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d10bb3cd6..4d13fcb3ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Changes: 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) # 2.71.0 diff --git a/src/detection/cpucache/cpucache_linux.c b/src/detection/cpucache/cpucache_linux.c index ff0551cbef..92fb63cf61 100644 --- a/src/detection/cpucache/cpucache_linux.c +++ b/src/detection/cpucache/cpucache_linux.c @@ -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); } From 3f73e9434be83fe2b2cdc14235a219d743921e06 Mon Sep 17 00:00:00 2001 From: "Pablo G. Alba" Date: Sat, 21 Nov 2026 02:34:07 +0100 Subject: [PATCH 27/38] Logo (Builtin): updates CuerdOS logo and colors (#2712) * Logo (Builtin): updates CuerdOS logo and colors * Fix CuerdOS logo alignment --- src/logo/ascii/c.inc | 4 ++-- src/logo/ascii/c/cuerdos.txt | 27 ++++++++++++++------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/logo/ascii/c.inc b/src/logo/ascii/c.inc index 7c751ec8aa..37053184b0 100644 --- a/src/logo/ascii/c.inc +++ b/src/logo/ascii/c.inc @@ -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 diff --git a/src/logo/ascii/c/cuerdos.txt b/src/logo/ascii/c/cuerdos.txt index 11610840db..9682c6ca46 100644 --- a/src/logo/ascii/c/cuerdos.txt +++ b/src/logo/ascii/c/cuerdos.txt @@ -1,13 +1,14 @@ - ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀ -⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣶⣾⣿⣿⣿⣶⣦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣶⣿⣿⣿⡇ -⠀⠀⡄⢀⣤⣤⣤⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣤⣤⣤⣤⣤⣄⠀⣿⣿⣿⣿⣿⡇ -⠀⠀⡇⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⠁ -⠀⠀⣧⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃ -⠀⠀⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁ -⠀⠀⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠋⠁ -⠀⠀⠇⠘⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠿⠿⠿⠿⠛⠛⠋⠉ -⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⡇ -⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉ -____________________________________ -| Optimizado hasta el último pixel | -************************************ \ No newline at end of file +⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⣴⣶⣿⣷ +⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⣤⣤⣤⣤⣤⣄⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⣿⣿⣿⣿⣿ +⢠⠀⠀⠀⠀⠀⢀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣀⠀⠀⠀⠀⣀⣠⣤⣤⣸⣿⣿⣿⣿⣿⡏ +⢸⠀⢠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁ +⢸⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠁⠀ +⢾⣿⣿⣿⣿⣿⡟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀ +⢸⠉⣿⣿⣿⣿⣷⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣠⣼⣿⣿⣿⣿⣿⣿⠿⠟⠉⠀⠀⠀⠀⠀ +⢸⠀⠹⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠟⠛⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀ +⠘⠀⠀⠀⠈⠉⠉⣽⣿⣍⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠈⢿⣿⠟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ + +╭─────────────────────────────────╮ +│ Filling The Void │ +╰─────────────────────────────────╯ \ No newline at end of file From c3ec79737f5819f7ecf091679246ceb947e199b1 Mon Sep 17 00:00:00 2001 From: Chareonwit Kunna <21arenabreakout12@gmail.com> Date: Sun, 22 Nov 2026 22:24:10 +0700 Subject: [PATCH 28/38] chore: fixes doubled word (#2743) Signed-off-by: Chareonwit Kunna <21arenabreakout12@gmail.com> --- src/detection/displayserver/linux/wayland/wayland.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/detection/displayserver/linux/wayland/wayland.c b/src/detection/displayserver/linux/wayland/wayland.c index ff29dc2c0f..49e46360a1 100644 --- a/src/detection/displayserver/linux/wayland/wayland.c +++ b/src/detection/displayserver/linux/wayland/wayland.c @@ -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; From 492bef51ab93b3248d871d5232a06e46402dc6f1 Mon Sep 17 00:00:00 2001 From: Piotr Kubaj Date: Sun, 22 Nov 2026 22:22:58 +0100 Subject: [PATCH 29/38] Display (Linux): fixes scale factor of rotated outputs on Wayland The scale factor is computed from the wl_output mode width and the zxdg_output_v1 logical width. The logical size is already transformed, but the mode is only swapped later in ffWaylandHandleRotation(), so a monitor rotated by 90 or 270 degrees compared its width with its logical height. A 1920x1200 monitor in portrait at scale 1 was reported as 1920 * 96 / 1200 = 153 dpi, shown as `@ 1.59x`. Compare with the mode height for 90 / 270 degree transforms instead. --- CHANGELOG.md | 1 + src/detection/displayserver/linux/wayland/global-output.c | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d13fcb3ef..3931b37f2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Changes: 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) # 2.71.0 diff --git a/src/detection/displayserver/linux/wayland/global-output.c b/src/detection/displayserver/linux/wayland/global-output.c index 6639a70c28..dcb394ccc9 100644 --- a/src/detection/displayserver/linux/wayland/global-output.c +++ b/src/detection/displayserver/linux/wayland/global-output.c @@ -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); } } From 0277bd3524d51f37ba4eface4089110b22587384 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:04:37 +0000 Subject: [PATCH 30/38] CI: Bump uraimo/run-on-arch-action Bumps the github-actions group with 1 update: [uraimo/run-on-arch-action](https://github.com/uraimo/run-on-arch-action). Updates `uraimo/run-on-arch-action` from 3.2.1 to 3.3 - [Release notes](https://github.com/uraimo/run-on-arch-action/releases) - [Commits](https://github.com/uraimo/run-on-arch-action/compare/fa1f3e7de95534497266c7265950b5188355fbfb...9893a0f995e5148dcc313ba661820f3992cffcc1) --- updated-dependencies: - dependency-name: uraimo/run-on-arch-action dependency-version: '3.3' dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions ... Signed-off-by: dependabot[bot] --- .github/workflows/build-linux-armv7l.yml | 2 +- .github/workflows/build-linux-vms.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-linux-armv7l.yml b/.github/workflows/build-linux-armv7l.yml index ec228b5074..c8eebba01e 100644 --- a/.github/workflows/build-linux-armv7l.yml +++ b/.github/workflows/build-linux-armv7l.yml @@ -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 diff --git a/.github/workflows/build-linux-vms.yml b/.github/workflows/build-linux-vms.yml index 5c7f7a1798..98d2c32480 100644 --- a/.github/workflows/build-linux-vms.yml +++ b/.github/workflows/build-linux-vms.yml @@ -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 }} From 7b3603707fe4b42e7deca52a729c64d13c479ea5 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 23 Nov 2026 09:29:19 +0800 Subject: [PATCH 31/38] CI: generates checksum files as release assets --- .github/workflows/build-release.yml | 52 +++++++++++++++-------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index 0c628d2c8f..7c6d1dfdfd 100644 --- a/.github/workflows/build-release.yml +++ b/.github/workflows/build-release.yml @@ -23,39 +23,41 @@ jobs: - name: download artifacts if: inputs.ffversion != steps.get_version_release.outputs.release uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - - - name: create release - if: inputs.ffversion != steps.get_version_release.outputs.release - uses: ncipollo/release-action@339a81892b84b4eeb0f6e744e4574d79d0d9b8dd # v1.21.0 with: - 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." + # Only release assets; benchmark artifacts are uploaded by a separate job. + pattern: fastfetch-* - - name: download source tarballs + - name: generate checksums and release notes 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-*/* + # 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 - - 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
SHA256SUMs
\n\n\`\`\`" >> fastfetch-release-notes.md - sha256sum fastfetch-*/* >> fastfetch-release-notes.md - echo -e "\`\`\`\n
" >> fastfetch-release-notes.md - echo -e "\n
SHA512SUMs
\n\n\`\`\`" >> fastfetch-release-notes.md - sha512sum fastfetch-*/* >> fastfetch-release-notes.md - echo -e "\`\`\`\n
" >> fastfetch-release-notes.md - - - name: update release body + for dir in fastfetch-*/; do + (cd "$dir" && sha512sum -- *) + done | sort -k2 > SHA512SUMS.txt + + cat SHA256SUMS.txt + cat SHA512SUMS.txt + + cat > fastfetch-release-notes.md < Date: Mon, 23 Nov 2026 19:30:15 +0800 Subject: [PATCH 32/38] CI: upgrades deps; fixes building --- .github/workflows/build-dragonfly-amd64.yml | 4 ++-- .github/workflows/build-freebsd-amd64.yml | 2 +- .github/workflows/build-haiku-amd64.yml | 4 ++-- .github/workflows/build-netbsd-amd64.yml | 4 ++-- .github/workflows/build-omnios-amd64.yml | 2 +- .github/workflows/build-openbsd-amd64.yml | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build-dragonfly-amd64.yml b/.github/workflows/build-dragonfly-amd64.yml index 39315ab7df..840d24335c 100644 --- a/.github/workflows/build-dragonfly-amd64.yml +++ b/.github/workflows/build-dragonfly-amd64.yml @@ -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: dragonflybsd version: '6.4.2' @@ -33,7 +33,7 @@ jobs: - 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 + sudo pkg install -y llvm cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3 egl opencl ocl-icd v4l_compat 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" . diff --git a/.github/workflows/build-freebsd-amd64.yml b/.github/workflows/build-freebsd-amd64.yml index 4b32e8eedd..568f3d0274 100644 --- a/.github/workflows/build-freebsd-amd64.yml +++ b/.github/workflows/build-freebsd-amd64.yml @@ -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' diff --git a/.github/workflows/build-haiku-amd64.yml b/.github/workflows/build-haiku-amd64.yml index 829aedb340..288a329d40 100644 --- a/.github/workflows/build-haiku-amd64.yml +++ b/.github/workflows/build-haiku-amd64.yml @@ -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 glib2_devel chafa_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 glib2_devel chafa_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' }} . diff --git a/.github/workflows/build-netbsd-amd64.yml b/.github/workflows/build-netbsd-amd64.yml index 49e859a1f6..a7e529e47e 100644 --- a/.github/workflows/build-netbsd-amd64.yml +++ b/.github/workflows/build-netbsd-amd64.yml @@ -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 diff --git a/.github/workflows/build-omnios-amd64.yml b/.github/workflows/build-omnios-amd64.yml index 23ee409d46..97691dd118 100644 --- a/.github/workflows/build-omnios-amd64.yml +++ b/.github/workflows/build-omnios-amd64.yml @@ -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' diff --git a/.github/workflows/build-openbsd-amd64.yml b/.github/workflows/build-openbsd-amd64.yml index 0a4ea6b019..f8e4e0f2a2 100644 --- a/.github/workflows/build-openbsd-amd64.yml +++ b/.github/workflows/build-openbsd-amd64.yml @@ -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' From 6dd3a8200d2418f372e08738fc2fbff778ef012d Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 23 Nov 2026 19:58:46 +0800 Subject: [PATCH 33/38] CI: fixes building v2 --- .github/workflows/build-dragonfly-amd64.yml | 2 +- .github/workflows/build-haiku-amd64.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-dragonfly-amd64.yml b/.github/workflows/build-dragonfly-amd64.yml index 840d24335c..3e587465bd 100644 --- a/.github/workflows/build-dragonfly-amd64.yml +++ b/.github/workflows/build-dragonfly-amd64.yml @@ -33,7 +33,7 @@ jobs: - 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 egl opencl ocl-icd v4l_compat libelf lua54 libva libvdpau + sudo pkg install -y llvm cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3 egl opencl ocl-icd v4l_compat libelf lua54 libva libvdpau openssl - 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" . diff --git a/.github/workflows/build-haiku-amd64.yml b/.github/workflows/build-haiku-amd64.yml index 288a329d40..3b39f55b4c 100644 --- a/.github/workflows/build-haiku-amd64.yml +++ b/.github/workflows/build-haiku-amd64.yml @@ -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 glib2_devel chafa_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 glib2_devel chafa_devel cmake llvm23_clang ninja pkgconfig python3.15 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' }} . From 76b377c8aadb983576e19edc854482fc518c02da Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 23 Nov 2026 22:17:38 +0800 Subject: [PATCH 34/38] CPU (Windows): adds support for querying CPU temp via PawnIO --- CMakeLists.txt | 5 + src/3rdparty/pawnio/COPYING.LGPL-2.1 | 502 ++++++++++++++++++++++++++ src/3rdparty/pawnio/IntelMSR.bin | Bin 0 -> 5452 bytes src/3rdparty/pawnio/pawnio.rc | 10 + src/3rdparty/pawnio/pawnio_resource.h | 3 + src/common/windows/nt.h | 5 +- src/detection/cpu/cpu_windows.c | 178 ++++++++- 7 files changed, 701 insertions(+), 2 deletions(-) create mode 100644 src/3rdparty/pawnio/COPYING.LGPL-2.1 create mode 100644 src/3rdparty/pawnio/IntelMSR.bin create mode 100644 src/3rdparty/pawnio/pawnio.rc create mode 100644 src/3rdparty/pawnio/pawnio_resource.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 43b9f3214c..d8c3fc9435 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2295,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 @@ -2334,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 diff --git a/src/3rdparty/pawnio/COPYING.LGPL-2.1 b/src/3rdparty/pawnio/COPYING.LGPL-2.1 new file mode 100644 index 0000000000..4362b49151 --- /dev/null +++ b/src/3rdparty/pawnio/COPYING.LGPL-2.1 @@ -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. + + + Copyright (C) + + 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. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/3rdparty/pawnio/IntelMSR.bin b/src/3rdparty/pawnio/IntelMSR.bin new file mode 100644 index 0000000000000000000000000000000000000000..67f18d9aeccb821938bf5bb49137369c80cd67f4 GIT binary patch literal 5452 zcmd^?dr(wW9LJ9cvVf)pB8HU{%!BHkD!HTjHA2q9~P1q!XnWUpDS_&G1q1!&b-~PCD2Z!*l?##~be$F|+*Ezr6 zy?2F^5P>ScoZz?^{rc-wr#GtSR8$oB<$5R1FD<&czsjj)Sd%%}v!U_zS9B9g!ltb; zq^jQSb+G+utuT&AHg1or^_jDGylc|BMJEe~N9>%dT^_S4u|uzZ@|Y?3R)}ZIm_6m% zG8a>AZF+pkr!K>uzgG9X;h4w1=Fx+7cc#zs-nez)q$L%V)nCN8d5pCL@9h2E{H4Yp zFTLHeCnWUugz(VvH%~g9iPsJo;8X22&~z!#`Tec_FF*8^+k25qrW|!i8dDJU%fSN= zPl(j0%1$5nrvA&ksI8Wp-OFpAb2R-#VZ)KI@;i53wU}?lXRRTyu1Xwqb=wG*Pu-V*{b?mn*<3^QTYMTA4 z*Qlx*%d5-c&TkJN?p&8SKK0tjRQK?XQkAyVb?$_Vr8CY3ly0~fTbMRvTa;^VQ+uD# zx2jf#THZ0ttUF|^yyla&;PQ>Uv*#|96bxzd{va>p6P4fM3;nMSjK6$)Q{K9TVs_Vtm)e(_%b;k4aoKilUvh9UbOXcSpFCiM6Jv@X^iI0R3Hn#r?g)n#uF~K_a zob{LfFTWk`LM*iDJS0S}Robq#4k4`S_Ny3jmsJiCX&Fh`=?R%BiOC5IvNC~-Gt;tD z?3`p+l$I>4GxjC+8~db~my(^3n3<#(;u+YZ7>t`}$exfAq>pUe7iy3TF{-+-8@mx60x~`VhwUQs^(^WsQ_vwdmcGZu$!%+zG z{pCI@^$+ul!g&}J&V|n{+6%zC-PUg<+a*6o$EXkzZn!=N>tiq;2x&qc4+H0eSA%oF zr@(sfWv~ux25Z2v2wV*=0tbPM!M@-UunJrXZbLur1)IV9z;)mry&M6Uz`elLU{~;N zunJrR?g!2XdxCSoUSK`g8>|ESf;HfQU^Une90VQ&_618|71$r#hB{V*&ET=%I`BBK z2|OOmev1I_#(X5W2s{y-51tCn0Z#|(!LeW+cpq2;?yN2!RA02A4m4)~^anav{j*EU67vomSOCC4% zqoGJUeT1m79i@bE&h!1zhI8gQ@IArzEc3Q4vzg#`75^7dpLS`7<9r`89u?x?xIZ|y z-4O`SDFWlPOMUBp*z;lhv?s~dbDnWfAIk*ezk&SeN3O^31+L@%be3m7IAWgsKH|C2 z5A87?vn(F^p@05=2!eh3VfcK0jFhtXHn@?zrejUQhp* zKCMARbyuIVUfBmcKlZiKcQW_674yf4V~E1`gt`h@i*x6iob_Lvv@ oU#TwH$IRn^!t +#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 diff --git a/src/3rdparty/pawnio/pawnio_resource.h b/src/3rdparty/pawnio/pawnio_resource.h new file mode 100644 index 0000000000..7d579e9218 --- /dev/null +++ b/src/3rdparty/pawnio/pawnio_resource.h @@ -0,0 +1,3 @@ +#pragma once + +#define FF_PAWNIO_INTEL_MSR_RC_ID 1 diff --git a/src/common/windows/nt.h b/src/common/windows/nt.h index 5487ef3cff..d3f6819ec6 100644 --- a/src/common/windows/nt.h +++ b/src/common/windows/nt.h @@ -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 { diff --git a/src/detection/cpu/cpu_windows.c b/src/detection/cpu/cpu_windows.c index 725a3bd122..9da281c2b6 100644 --- a/src/detection/cpu/cpu_windows.c +++ b/src/detection/cpu/cpu_windows.c @@ -7,10 +7,173 @@ #include "common/smbios.h" #include +#include #include "common/windows/perflib_.h" #include "common/windows/nt.h" +#include "common/time.h" +#include "3rdparty/pawnio/pawnio_resource.h" #include +#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", ffDebugNtError(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); } From 83a6783576f91cbfba52270d2ab673555a88d035 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Mon, 23 Nov 2026 10:17:45 +0800 Subject: [PATCH 35/38] Release: v2.72.0 --- CHANGELOG.md | 17 +++++++++++++++++ CMakeLists.txt | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3931b37f2b..792379e5a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,14 +6,31 @@ Features: * 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) + +Logos: +* Updated the CuerdOS logo and colors (#2712) +* Removed the Turkmen Linux (`Turkish`) logo # 2.71.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index d8c3fc9435..ee8ca3f832 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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" From e09925d303dfc1d3cb35b977017d65c9c1704366 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Tue, 24 Nov 2026 16:20:06 +0800 Subject: [PATCH 36/38] Chore: deprecates DFBSD support --- .github/workflows/build-dragonfly-amd64.yml | 66 --------------------- .github/workflows/ci.yml | 8 --- CHANGELOG.md | 6 +- 3 files changed, 5 insertions(+), 75 deletions(-) delete mode 100644 .github/workflows/build-dragonfly-amd64.yml diff --git a/.github/workflows/build-dragonfly-amd64.yml b/.github/workflows/build-dragonfly-amd64.yml deleted file mode 100644 index 3e587465bd..0000000000 --- a/.github/workflows/build-dragonfly-amd64.yml +++ /dev/null @@ -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@30cde56b87a128507bebea9531205087890ee360 # v1.8.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 egl opencl ocl-icd v4l_compat libelf lua54 libva libvdpau openssl - - - 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-*.* diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc963f28bd..dba030dc2f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,13 +129,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 @@ -200,7 +193,6 @@ jobs: - freebsd-amd64 - openbsd-amd64 - netbsd-amd64 - - dragonfly-amd64 - solaris-amd64 - omnios-amd64 - haiku-amd64 diff --git a/CHANGELOG.md b/CHANGELOG.md index 792379e5a3..ab5db85b2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ -# Unreleased +# 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) From 51d749eba4a4b9c4c5a17b03b15a5b8ea24d576d Mon Sep 17 00:00:00 2001 From: Carter Li Date: Thu, 26 Nov 2026 21:37:40 +0800 Subject: [PATCH 37/38] CI: fixes building --- .github/workflows/build-freebsd-amd64.yml | 2 +- .github/workflows/build-linux-loong64.yml | 60 ----------------------- .github/workflows/ci.yml | 8 --- src/common/time.h | 3 +- src/detection/cpu/cpu_windows.c | 2 +- 5 files changed, 4 insertions(+), 71 deletions(-) delete mode 100644 .github/workflows/build-linux-loong64.yml diff --git a/.github/workflows/build-freebsd-amd64.yml b/.github/workflows/build-freebsd-amd64.yml index 568f3d0274..2fafadf82e 100644 --- a/.github/workflows/build-freebsd-amd64.yml +++ b/.github/workflows/build-freebsd-amd64.yml @@ -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" . diff --git a/.github/workflows/build-linux-loong64.yml b/.github/workflows/build-linux-loong64.yml deleted file mode 100644 index 8c35ee0826..0000000000 --- a/.github/workflows/build-linux-loong64.yml +++ /dev/null @@ -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-*.* diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dba030dc2f..bb7d3f1824 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 }} @@ -185,7 +178,6 @@ jobs: - linux-hosts - linux-i686 - linux-armv7l - - linux-loong64 - linux-vms - musl-amd64 - android diff --git a/src/common/time.h b/src/common/time.h index a4d25341bb..44f8f4b6e8 100644 --- a/src/common/time.h +++ b/src/common/time.h @@ -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 } diff --git a/src/detection/cpu/cpu_windows.c b/src/detection/cpu/cpu_windows.c index 9da281c2b6..6523ccd374 100644 --- a/src/detection/cpu/cpu_windows.c +++ b/src/detection/cpu/cpu_windows.c @@ -101,7 +101,7 @@ 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", ffDebugNtError(status)); + FF_DEBUG("Failed to set thread affinity mask: %s", ffDebugNtStatus(status)); } // Changing the affinity mask does not migrate an already running thread immediately. From 7087abff73d429dd281d634f63efc4142dfbe837 Mon Sep 17 00:00:00 2001 From: Carter Li Date: Sat, 28 Nov 2026 10:42:32 +0800 Subject: [PATCH 38/38] OS (FreeBSD): fixes os-release not found when TARGET_DIR_ETC is set Fixes #2759 --- CHANGELOG.md | 1 + CMakeLists.txt | 2 +- src/detection/os/os_bsd.c | 27 +++++++++++++++++++++++++++ src/detection/os/os_linux.c | 2 -- 4 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 src/detection/os/os_bsd.c diff --git a/CHANGELOG.md b/CHANGELOG.md index ab5db85b2f..99b68aa64d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ Bugfixes: * 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) diff --git a/CMakeLists.txt b/CMakeLists.txt index ee8ca3f832..80a6d60d13 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -836,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 diff --git a/src/detection/os/os_bsd.c b/src/detection/os/os_bsd.c new file mode 100644 index 0000000000..29564f7668 --- /dev/null +++ b/src/detection/os/os_bsd.c @@ -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 }, + }); +} diff --git a/src/detection/os/os_linux.c b/src/detection/os/os_linux.c index 02dcb240ac..2f270f1b06 100644 --- a/src/detection/os/os_linux.c +++ b/src/detection/os/os_linux.c @@ -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 }